Skip to content

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

FEATURE: First iteration of nested replies (#38888)

Mark VanLandingham8feeaa5d69cd
diff --git a/app/assets/stylesheets/common.scss b/app/assets/stylesheets/common.scss
index ac22dbd54d8..8befcb94233 100644
--- a/app/assets/stylesheets/common.scss
+++ b/app/assets/stylesheets/common.scss
@@ -23,3 +23,4 @@
@import "common/table-builder/_index";
@import "common/post-action-feedback";
@import "common/toolbar-popup-menu-options";
+@import "common/nested-view";
diff --git a/app/assets/stylesheets/common/nested-view.scss b/app/assets/stylesheets/common/nested-view.scss
new file mode 100644
index 00000000000..67cede92f12
--- /dev/null
+++ b/app/assets/stylesheets/common/nested-view.scss
@@ -0,0 +1,989 @@
+@use "lib/viewport";
+
+// ── Top-level nested view ──────────────────────────────────────────
+.nested-view {
+ background: var(--secondary);
+ padding: var(--space-4);
+ border-radius: var(--d-border-radius-large);
+
+ &__header {
+ margin-bottom: 1em;
+ padding-bottom: 0.75em;
+ border-bottom: 1px solid var(--primary-low);
+ }
+
+ &__title {
+ margin: 0;
+ font-size: var(--font-up-4);
+ line-height: var(--line-height-medium);
+ overflow-wrap: break-word;
+
+ a {
+ color: var(--primary);
+ }
+
+ .edit-topic__wrapper {
+ white-space: nowrap;
+ font-size: var(--font-down-3);
+ vertical-align: 0.125em;
+ margin-left: var(--space-1);
+ }
+
+ html.discourse-no-touch & {
+ .fancy-title {
+ .edit-topic {
+ opacity: 0;
+ transition: opacity 0.15s linear;
+ background: none;
+ }
+
+ &:hover,
+ &:focus-visible {
+ .edit-topic {
+ opacity: 1;
+ }
+ }
+ }
+ }
+ }
+
+ .edit-topic-title {
+ display: flex;
+ flex-wrap: wrap;
+ box-sizing: border-box;
+ gap: 0.5em;
+ width: 100%;
+
+ .edit-title__wrapper {
+ flex: 1 1 100%;
+
+ #edit-title {
+ width: 100%;
+ margin: 0;
+ }
+ }
+
+ .edit-category__wrapper {
+ flex: 1 1 5%;
+
+ .select-kit.combo-box.category-chooser {
+ width: 100%;
+ height: 100%;
+ }
+ }
+
+ .edit-tags__wrapper {
+ flex: 1 1 33%;
+
+ .mini-tag-chooser {
+ width: 100%;
+ }
+ }
+
+ .edit-controls {
+ display: flex;
+ width: 100%;
+ gap: 0.5em;
+ }
+ }
+
+ &__topic-map {
+ margin-bottom: 1em;
+ max-width: none;
+
+ .top-replies {
+ display: none;
+ }
+ }
+
+ &__controls {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 1em;
+ margin-bottom: 1em;
+ }
+
+ &__flat-link {
+ font-size: var(--font-down-1);
+ white-space: nowrap;
+ margin-left: auto;
+ }
+
+ &__op {
+ margin-bottom: 1.5em;
+ padding: 1em;
+ background: var(--primary-very-low);
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius);
+
+ // Establish a containing block for the absolutely-positioned
+ // .read-state dot so it anchors to the post-infos right edge
+ // instead of climbing to a distant ancestor.
+ .post-infos {
+ position: relative;
+
+ .read-state {
+ right: -10px;
+ }
+ }
+ }
+
+ &__op-row {
+ display: flex;
+ gap: 0.75em;
+
+ .topic-avatar {
+ border-top: none;
+ float: none;
+ width: auto;
+ padding-top: 0;
+ height: auto;
+ }
+
+ .topic-meta-data {
+ padding: 0;
+ }
+ }
+
+ &__op-body {
+ flex: 1;
+ min-width: 0;
+ }
+
+ &__op-content {
+ margin-top: 0.5em;
+ }
+
+ &__op-menu {
+ margin: 0.25em 0;
+
+ .post-action-menu__show-replies {
+ display: none;
+ }
+
+ // Left-align the post menu in nested view on desktop (mobile keeps the
+ // Core right-aligned layout). Compounded with .post-menu-area to beat
+ // the Core `.post-menu-area { padding-left: ... }` rule from
+ // desktop/topic.scss, which has equal specificity but loads later.
+ @include viewport.from(sm) {
+ &.post-menu-area {
+ padding-left: 0;
+ margin-top: 1em;
+ }
+
+ nav.post-controls {
+ justify-content: flex-start;
+
+ .actions {
+ margin-left: 0;
+ }
+ }
+ }
+ }
+
+ &__roots {
+ display: flex;
+ flex-direction: column;
+ }
+
+ &__empty {
+ padding: 2em;
+ text-align: center;
+ color: var(--primary-medium);
+ font-size: var(--font-up-1);
+ }
+
+ &__new-replies {
+ display: flex;
+ justify-content: center;
+ margin-bottom: 1em;
+ }
+
+ &__floating-actions {
+ position: sticky;
+ bottom: 2em;
+ float: right;
+ z-index: z("header") - 2; // below header, above page content and footer-nav
+ display: flex;
+ align-items: center;
+ gap: 0.5em;
+ transition:
+ transform 0.3s ease,
+ opacity 0.3s ease;
+
+ &.--hidden {
+ opacity: 0;
+ pointer-events: none;
+ transform: translateY(2em);
+ }
+
+ .select-kit.topic-notifications-button .select-kit-header {
+ box-shadow: var(--shadow-dropdown);
+ border-radius: 2em;
+ background: var(--secondary);
+ }
+
+ .topic-admin-menu-button-container .fk-d-menu__trigger {
+ box-shadow: var(--shadow-dropdown);
+ border-radius: 2em;
+ background: var(--secondary);
+ }
+ }
+
+ &__floating-reply {
+ box-shadow: var(--shadow-dropdown);
+ border-radius: 2em;
+ padding: 0.65em 1.25em;
+ }
+}
+
+// ── Sort selector ──────────────────────────────────────────────────
+.nested-sort-selector {
+ display: flex;
+ align-items: center;
+ gap: 0.25em;
+
+ &__label {
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ margin-right: 0.25em;
+ }
+
+ &__option {
+ font-size: var(--font-down-1);
+ padding: 0.25em 0.5em;
+ color: var(--primary-medium);
+
+ &--active {
+ color: var(--tertiary);
+ font-weight: bold;
+ }
+ }
+}
+
+// ── Nested post (single comment in tree) ───────────────────────────
+.nested-post {
+ // Avatar size for the "small" PostAvatar used in nested posts.
+ // Used to calculate horizontal connector positions.
+ --nested-avatar-size: 24px;
+ --nested-column-gap: 8px;
+ --nested-connector-offset: 8px;
+ --nested-vertical-gap: 0.5em;
+ --nested-hook-width: calc(var(--nested-avatar-size) / 2);
+ --nested-line-offset: calc(
+ var(--nested-connector-offset) + var(--nested-avatar-size) / 2
+ );
+ --nested-load-more-left-adjust: 2px;
+
+ // Grid splits article (row 1) from children (row 2) so the gutter's
+ // depth-line naturally stops at the article bottom.
+ display: grid;
+ grid-template-columns: var(--nested-avatar-size) 1fr;
+ column-gap: var(--nested-column-gap);
+ position: relative;
+
+ &:not(.--depth-0) {
+ padding-top: var(--nested-vertical-gap);
+
+ // L-shaped connector from parent's depth-line to this post's avatar.
+ // Extends 4px above the element to bridge the gap between the parent's
+ // depth-line (grid row 1) and this child (grid row 2).
+ &::before {
+ content: "";
+ position: absolute;
+ top: -4px; // overlap parent grid row by 4px to bridge gap
+ left: calc(-1 * var(--nested-line-offset));
+ width: var(--nested-hook-width);
+ height: calc(
+ var(--nested-vertical-gap) + var(--nested-avatar-size) / 2 + 5px // +5px visually centers the hook on the avatar
+ );
+ border-left: 2px solid var(--primary-low);
+ border-bottom: 2px solid var(--primary-low);
+ border-radius: 0 0 0 12px;
+ transition: border-color 0.15s ease;
+ }
+
+ // Vertical continuation line connecting to the next sibling.
+ // Only drawn for non-last children; last child stops at its connector.
+ // Overlaps the L-connector curve by 4px to prevent thin-line rendering
+ // caused by border-radius anti-aliasing.
+ &:not(:last-child)::after {
+ content: "";
+ position: absolute;
+ left: calc(-1 * var(--nested-line-offset));
+
+ // +1px aligns with L-connector bottom; -10px overlaps its border-radius
+ // curve to prevent subpixel gaps from anti-aliasing
+ top: calc(
+ var(--nested-vertical-gap) + var(--nested-avatar-size) / 2 + 1px - 10px
+ );
+ bottom: 0;
+ width: 2px;
+ background: var(--primary-low);
+ transition: background-color 0.15s ease;
+ }
+ }
+
+ // When the parent's depth-line is hovered, highlight child connectors
+ &:not(.--depth-0).--parent-line-highlighted {
+ &::before {
+ border-color: var(--tertiary);
+ }
+
+ &:not(:last-child)::after {
+ background: var(--tertiary);
+ }
+ }
+
+ // Transparent overlay covering the parent's line area through this child.
+ // Provides click-to-collapse and hover-to-highlight for the parent line.
+ &__parent-line-btn {
+ position: absolute;
+ left: calc(-1 * var(--nested-line-offset) - 10px);
+ top: 0;
+ bottom: 0;
+ width: 22px;
+ background: none;
+ border: none;
+ cursor: pointer;
+ padding: 0;
+
+ // Visual feedback is provided by --parent-line-highlighted class (JS).
+ // Transparent outline ensures visibility in Windows High Contrast Mode.
+ &:focus-visible {
+ outline: 2px solid transparent;
+ }
+ }
+
+ &.--depth-0 {
+ padding-bottom: 0.75em;
+ margin-top: 0.5em;
+
+ &:first-child {
+ margin-top: 0;
+ }
+ }
+
+ // Left column: avatar on top, clickable depth line below.
+ // Grid row 1 only — does not extend into the children row.
+ &__gutter {
+ grid-column: 1;
+ grid-row: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+
+ .topic-avatar {
+ border-top: none;
+ float: none;
+ width: auto;
+ padding-top: 0;
+ height: auto;
+
+ .avatar-flair {
+ background-size: 12px 12px;
+ width: 12px;
+ height: 12px;
+ right: -3px;
+ bottom: -2px;
+ }
+ }
+ }
+
+ // Depth line sits below the avatar. Extends 1em below the gutter so it
+ // overlaps the first child's L-connector, masking any subpixel rounding
+ // offset between grid column 1 (gutter) and column 2 (children).
+ &__depth-line {
+ flex: 1;
+ width: 100%;
+ position: relative;
+ padding: 0;
+ background: none;
+ border: none;
+ cursor: pointer;
+ min-height: 8px;
+
+ &::after {
+ content: "";
+ position: absolute;
+ left: calc(var(--nested-avatar-size) / 2);
+ top: 6px;
+ bottom: 0;
+ width: 2px;
+ border-radius: 1px;
+ background: var(--primary-low);
+ transition: background-color 0.15s ease;
+ }
+
+ // Transparent outline preserves WHCM focus visibility while
+ // letting the tertiary line color serve as the primary indicator.
+ &:focus-visible,
+ &--highlighted {
+ outline: 2px solid transparent;
+
+ &::after {
+ background: var(--tertiary);
+ }
+
+ .nested-post__depth-line-icon .d-icon {
+ color: var(--tertiary);
+ }
+ }
+
+ @media (hover: hover) {
+ &:hover {
+ &::after {
+ background: var(--tertiary);
+ }
+
+ .nested-post__depth-line-icon .d-icon {
+ color: var(--tertiary);
+ }
+ }
+ }
+
+ // When children are collapsed, turn the vertical line into an L-shape
+ // that bends toward the "N replies" expand button
+ &--collapsed {
+ &::after {
+ left: calc(var(--nested-avatar-size) / 2);
+ bottom: 14px; // aligns L-bend with the "N replies" expand button
+ width: calc(var(--nested-avatar-size) / 2);
+ transform: none;
+ background: none;
+ border-left: 2px solid var(--primary-low);
+ border-bottom: 2px solid var(--primary-low);
+ border-radius: 0 0 0 12px;
+ transition: border-color 0.15s ease;
+ }
+
+ @media (hover: hover) {
+ &:hover {
+ &::after {
+ background: none;
+ border-color: var(--tertiary);
+ }
+ }
+ }
+
+ &:focus-visible {
+ outline: 2px solid transparent;
+
+ &::after {
+ background: none;
+ border-color: var(--tertiary);
+ }
+ }
+ }
+ }
+
+ &__depth-line-icon {
+ position: absolute;
+ bottom: 0;
+ left: calc(50% + 1px);
+ transform: translateX(-50%);
+ z-index: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 14px;
+ height: 14px;
+ padding: 1px;
+ border-radius: 50%;
+ background: var(--secondary);
+
+ .d-icon {
+ width: 100%;
+ height: 100%;
+ color: var(--primary-low);
+ transition: color 0.15s ease;
+ }
+ }
+
+ // display: contents dissolves __main from the grid so its children
+ // (article + nested-post-children) become grid items directly.
+ &__main {
+ display: contents;
+ }
+
+ &__article {
+ grid-column: 2;
+ grid-row: 1;
+ min-width: 0;
+
+ .topic-meta-data {
+ padding: 0;
+ }
+ }
+
+ &__header {
+ display: flex;
+ align-items: center;
+ gap: 0.5em;
+
+ // Hide the reply-to line, as the lines between posts already visually indicate the reply structure
+ .reply-to-tab {
+ display: none;
+ }
+
+ .topic-meta-data {
+ display: contents;
+ }
+
+ .post-infos {
+ margin-left: auto;
+ order: 1;
+ }
+
+ // Read state was all whacky, this makes it nice.
+ .read-state {
+ position: relative;
+ margin-left: 3px;
+ }
+ }
+
+ &__op-badge {
+ font-size: var(--font-down-2);
+ font-weight: bold;
+ color: var(--tertiary);
+ background: var(--tertiary-very-low);
+ border: 1px solid var(--tertiary-low);
+ border-radius: var(--d-border-radius);
+ padding: 0.1em 0.4em;
+ line-height: 1;
+ }
+
+ &__pinned-badge {
+ font-size: var(--font-down-2);
+ font-weight: bold;
+ color: var(--success);
+ background: var(--success-low);
+ border: 1px solid var(--success-medium);
+ border-radius: var(--d-border-radius);
+ padding: 0.1em 0.4em;
+ line-height: 1;
+ }
+
+ &__content {
+ margin-top: 0.25em;
+ margin-bottom: 0.25em;
+ }
+
+ &__menu {
+ margin: 0.25em 0;
+
+ .post-action-menu__show-replies {
+ display: none;
+ }
+
+ // Left-align the post menu in nested view on desktop (mobile keeps the
+ // Core right-aligned layout). Compounded with .post-menu-area to beat
+ // the Core `.post-menu-area { padding-left: ... }` rule from
+ // desktop/topic.scss, which has equal specificity but loads later.
+ @include viewport.from(sm) {
+ &.post-menu-area {
+ padding-left: 0;
+ margin-top: 0;
+ }
+
+ nav.post-controls {
+ justify-content: flex-start;
+
+ .actions {
+ margin-left: 0;
+ }
+ }
+ }
+ }
+
+ &__expand-replies.btn {
+ color: var(--tertiary);
+ font-size: var(--font-down-1);
+
+ .d-icon {
+ color: var(--tertiary);
+ }
+ }
+
+ &__controls {
+ display: flex;
+ align-items: center;
+ gap: 0.75em;
+ font-size: var(--font-down-1);
+ }
+
+ &__collapsed-bar {
+ grid-column: 2;
+ grid-row: 1;
+ display: flex;
+ align-items: center;
+ gap: 0.35em;
+ padding: 0.15em 0.25em;
+ border: none;
+ background: none;
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ cursor: pointer;
+ border-radius: var(--d-border-radius);
+ white-space: nowrap;
+ align-self: center;
+
+ &:hover {
+ color: var(--tertiary);
+ }
+ }
+
+ &__collapsed-separator {
+ color: var(--primary-low-mid);
+ }
+
+ &__collapsed-reply-count {
+ color: var(--tertiary);
+ }
+
+ &__deleted-placeholder {
+ grid-column: 2;
+ grid-row: 1;
+ padding: 0 0 2em;
+ margin-top: -0.35em;
+ }
+
+ &__deleted-actions {
+ display: flex;
+ align-items: center;
+ gap: 0.25em;
+ }
+
+ &__deleted-label {
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ font-style: italic;
+ }
+
+ &__deleted-content {
+ background-color: var(--danger-low-mid);
+ padding: 0.5em;
+ width: 100%;
+ }
+
+ &__deleted-content-header {
+ display: flex;
+ align-items: center;
+ gap: 0.5em;
+ margin-bottom: 0.5em;
+
+ .topic-meta-data {
+ display: contents;
+ }
+
+ .post-infos {
+ margin-left: auto;
+ order: 1;
+ }
+ }
+
+ &--whisper {
+ .nested-post__content .cooked {
+ font-style: italic;
+ color: var(--primary-medium);
+ }
+ }
+
+ &__deleted-avatar-placeholder {
+ width: var(--nested-avatar-size);
+ height: var(--nested-avatar-size);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--primary-low-mid);
+
+ .d-icon {
+ width: 14px;
+ height: 14px;
+ }
+ }
+
+ &__continue-link {
+ color: var(--tertiary);
+ font-weight: bold;
+ }
+}
+
+// ── Children container ─────────────────────────────────────────────
+.nested-post-children {
+ grid-column: 2;
+ grid-row: 2;
+
+ &__load-more {
+ margin: 0.5em 0;
+ color: var(--tertiary);
+ font-size: var(--font-down-1);
+ position: relative;
+
+ // L-shaped hook connecting the sibling continuation line to this button
+ &::before {
+ content: "";
+ position: absolute;
+ left: calc(
+ -1 * var(--nested-line-offset) - var(--nested-load-more-left-adjust) +
+ 1px
+ );
+ top: -1em;
+ height: calc(50% + 1em);
+ width: var(--nested-line-offset);
+ border-left: 2px solid var(--primary-low);
+ border-bottom: 2px solid var(--primary-low);
+ border-radius: 0 0 0 12px;
+ transition: border-color 0.15s ease;
+ }
+
+ // When the parent's depth-line is hovered, highlight this hook to match
+ // the sibling continuation lines above it.
+ &.--parent-line-highlighted::before {
+ border-color: var(--tertiary);
+ }
+ }
+}
+
+// ── Context view ──────────────────────────────────────────────────
+.nested-context-view {
+ &__banner {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 0.5em;
+ padding: 0.75em 1em;
+ margin-bottom: 1em;
+ background: var(--tertiary-very-low);
+ border: 1px solid var(--tertiary-low);
+ border-radius: var(--d-border-radius);
+ font-size: var(--font-down-1);
+ }
+
+ &__banner-icon {
+ color: var(--tertiary);
+
+ .d-icon {
+ width: 1em;
+ height: 1em;
+ }
+ }
+
+ &__banner-text {
+ color: var(--primary-high);
+ margin-right: auto;
+ }
+
+ &__nav {
+ display: flex;
+ gap: 0.5em;
+ align-items: center;
+ }
+
+ &__chain {
+ border-left: 3px solid var(--tertiary-low);
+ padding-left: 0.75em;
+ }
+}
+
+// ── Topic connector link ───────────────────────────────────────────
+.nested-view-link {
+ font-size: var(--font-down-1);
+ display: block;
+ margin-top: 0.5em;
+}
+
+// ── Deep-link highlight animation ──────────────────────────────────
+.nested-post--highlighted {
+ animation: nested-post-highlight 2s ease-out;
+}
+
+@keyframes nested-post-highlight {
+ 0% {
+ background-color: var(--tertiary-low);
+ }
+
+ 100% {
+ background-color: transparent;
+ }
+}
+
+// ── Mobile layout ─────────────────────────────────────────────────
+// Reddit-style mobile redesign: avatars move inline into the post
+// header (handled via JS template conditional), the gutter becomes a
+// narrow column holding only vertical depth-lines that run the full
+// height of each subtree for continuous visual hierarchy.
+@include viewport.until(sm) {
+ // ── View-level overrides ──
+ .nested-view {
+ padding: 0.5em;
+ border-radius: 0;
+ }
+
+ .nested-view__title {
+ font-size: var(--font-up-3);
+ }
+
+ .nested-view__controls {
+ flex-wrap: wrap;
+ background: var(--secondary);
+ margin-left: -0.5em;
+ margin-right: -0.5em;
+ padding: 0.5em;
+ margin-bottom: 0;
+ }
+
+ .nested-context-view__banner {
+ margin-left: -0.5em;
+ margin-right: -0.5em;
+ border-radius: 0;
+ border-left: none;
+ border-right: none;
+ }
+
+ // Full-width cards: break out of container side padding
+ .nested-view__op,
+ .nested-view__roots {
+ margin-left: -0.5em;
+ margin-right: -0.5em;
+ }
+
+ .nested-view__topic-map {
+ background: var(--secondary);
+ margin-left: -0.5em;
+ margin-right: -0.5em;
+ padding: 0.5em;
+ margin-bottom: 0;
+ }
+
+ // OP rendered as a full-width white card
+ .nested-view__op {
+ padding: 0.5em;
+ background: var(--secondary);
+ border: none;
+ border-radius: 0;
+ margin-bottom: 0;
+ }
+
+ .nested-view__op-row {
+ gap: 0.5em;
+ }
+
+ // Grey gap between root-level thread cards (and after OP)
+ .nested-view__roots {
+ gap: 0.5em;
+ }
+
+ .nested-view__floating-actions {
+ bottom: 1em;
+ }
+
+ .nested-sort-selector {
+ flex-wrap: wrap;
+ }
+
+ // Strip L-hook connectors on load-more buttons
+ .nested-post-children__load-more::before {
+ content: none;
+ }
+
+ // ── Individual nested post overrides ──
+ // Gutter shrinks to a narrow line-only column (avatar rendered inline
+ // in the header instead). Lines run full subtree height.
+ .nested-post {
+ --nested-line-gutter: 10px;
+ grid-template-columns: var(--nested-line-gutter) 1fr;
+
+ // Explicit rows are required so grid-row: 1 / -1 on the gutter
+ // can resolve -1 to the end of the explicit grid (line 3).
+ // Without this, -1 falls back to line 1 and the gutter only spans row 1.
+ grid-template-rows: auto 1fr;
+ column-gap: 4px;
+
+ // Tighter vertical spacing between siblings
+ --nested-vertical-gap: 0.25em;
+
+ // Gutter spans all grid rows so the depth-line runs continuously
+ // through the article AND children areas
+ > .nested-post__gutter {
+ grid-row: 1 / -1;
+ }
+
+ // Depth-line: full-height vertical bar, no decorative hooks
+ > .nested-post__gutter .nested-post__depth-line {
+ &::after {
+ left: calc(var(--nested-line-gutter) / 2 - 1px);
+ top: 0;
+ bottom: 0;
+ }
+
+ // Override the desktop L-bend on collapsed lines — straight bar
+ &--collapsed::after {
+ border: none;
+ background: var(--primary-low);
+ width: 2px;
+ border-radius: 0;
+ left: calc(var(--nested-line-gutter) / 2 - 1px);
+ bottom: 0;
+ }
+ }
+
+ // Hide the collapse icon — tapping the line itself collapses
+ .nested-post__depth-line-icon {
+ display: none;
+ }
+
+ // Inline avatar in the post header (rendered via template)
+ .nested-post__header .topic-avatar {
+ border-top: none;
+ float: none;
+ width: auto;
+ padding-top: 0;
+ height: auto;
+ }
+
+ // Strip all decorative connectors (L-hooks, sibling lines)
+ &:not(.--depth-0) {
+ &::before,
+ &:not(:last-child)::after {
+ content: none;
+ }
+ }
+
+ // No hover interaction on touch — depth-line handles collapse
+ > .nested-post__parent-line-btn {
+ display: none;
+ }
+
+ // Root threads rendered as full-width white cards.
+ // padding-left: 0 so the gutter starts at the card edge (= viewport
+ // edge after negative margins), giving consistent line spacing.
+ &.--depth-0 {
+ background: var(--secondary);
+ border-radius: 0;
+ padding: 0.5em 0.5em 0.5em 0;
+ margin-top: 0;
+ }
+
+ // Compact post headers
+ .nested-post__header {
+ flex-wrap: wrap;
+ gap: 0.25em;
+
+ .topic-meta-data {
+ margin-left: 0;
+ }
+ }
+
+ .nested-post__content {
+ overflow-x: auto;
+ }
+ }
+}
+
+html.footer-nav-visible {
+ .nested-view__floating-actions {
+ bottom: calc(var(--footer-nav-height) + env(safe-area-inset-bottom) + 1em);
+ }
+}
diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rb
index 1065e77c019..1448ba89c54 100644
--- a/app/controllers/categories_controller.rb
+++ b/app/controllers/categories_controller.rb
@@ -659,6 +659,7 @@ class CategoriesController < ApplicationController
num_auto_bump_daily
require_reply_approval
require_topic_approval
+ nested_replies_default
topic_posting_review_mode
reply_posting_review_mode
],
diff --git a/app/controllers/nested_topics_controller.rb b/app/controllers/nested_topics_controller.rb
new file mode 100644
index 00000000000..d4c0c28b3e1
--- /dev/null
+++ b/app/controllers/nested_topics_controller.rb
@@ -0,0 +1,189 @@
+# frozen_string_literal: true
+
+class NestedTopicsController < ApplicationController
+ skip_before_action :check_xhr, only: %i[show context]
+
+ before_action :ensure_nested_replies_enabled
+ before_action :find_topic_with_topic_view, only: %i[show children context]
+ before_action :find_topic, only: %i[pin toggle]
+ before_action :ensure_not_pm
+ after_action :track_visit, only: %i[show context]
+
+ # GET /n/:slug/:topic_id (HTML + JSON)
+ # HTML: preloads initial data into the Ember shell (crawlers redirect to flat view)
+ # JSON page 0: includes topic metadata, OP post, sort, and message_bus_last_id
+ # JSON page 1+: returns only roots for pagination
+ def show
+ if spa_boot_request?
+ if use_crawler_layout?
+ redirect_to "/t/#{params[:slug]}/#{params[:topic_id]}", status: :moved_permanently
+ return
+ end
+
+ store_preloaded("nested_topic_#{@topic.id}", MultiJson.dump(list_roots_response(page: 0)))
+ render "default/empty"
+ return
+ end
+
+ page = params[:page].to_i.clamp(0, 1000)
+ render json: list_roots_response(page: page)
+ end
+
+ # GET /n/:slug/:topic_id/children/:post_number
+ def children
+ NestedTopic::ListChildren.call(
+ service_params.deep_merge(
+ params: {
+ parent_post_number: params[:post_number].to_i,
+ sort: validated_sort,
+ page: params[:page].to_i.clamp(0, 1000),
+ depth: params[:depth].to_i.clamp(1, 100),
+ },
+ topic_view: @topic_view,
+ ),
+ ) do
+ on_success { |response:| render json: response }
+ on_failed_contract { raise Discourse::NotFound }
+ on_failure { raise Discourse::NotFound }
+ end
+ end
+
+ # GET /n/:slug/:topic_id/:post_number (HTML + JSON)
+ # HTML: preloads context data into the Ember shell (crawlers redirect to flat view)
+ # JSON param: context (integer) -- controls ancestor depth.
+ # nil/absent = windowed ancestor chain capped at max_depth (deep-links, notifications)
+ # 0 = no ancestors, target at depth 0 ("Continue this thread")
+ def context
+ if spa_boot_request?
+ if use_crawler_layout?
+ redirect_to "/t/#{params[:slug]}/#{params[:topic_id]}/#{params[:post_number]}",
+ status: :moved_permanently
+ return
+ end
+
+ store_preloaded("nested_topic_#{@topic.id}", MultiJson.dump(show_context_response))
+ render "default/empty"
+ return
+ end
+
+ render json: show_context_response
+ end
+
+ # PUT /n/:slug/:topic_id/pin
+ def pin
+ NestedTopic::TogglePin.call(service_params.deep_merge(params: { topic_id: @topic.id })) do
+ on_success { |nested_topic:| render json: { pinned_post_ids: nested_topic.pinned_post_ids } }
+ on_failed_contract { raise Discourse::NotFound }
+ on_model_not_found(:topic) { raise Discourse::NotFound }
+ on_model_not_found(:post) { raise Discourse::NotFound }
+ on_failed_policy(:staff_can_edit) { raise Discourse::InvalidAccess }
+ on_failed_policy(:post_is_root) { raise Discourse::InvalidParameters.new(:post_id) }
+ on_failed_policy(:within_pin_limit) { raise Discourse::InvalidParameters.new(:post_id) }
+ on_failure { raise Discourse::InvalidParameters }
+ end
+ end
+
+ # PUT /n/:slug/:topic_id/toggle
+ def toggle
+ NestedTopic::Toggle.call(service_params.deep_merge(params: { topic_id: @topic.id })) do
+ on_success { |params:| render json: { is_nested_view: params.enabled } }
+ on_failed_contract { raise Discourse::InvalidParameters }
+ on_model_not_found(:topic) { raise Discourse::NotFound }
+ on_failed_policy(:staff_can_edit) { raise Discourse::InvalidAccess }
+ on_failure { raise Discourse::InvalidParameters }
+ end
+ end
+
+ private
+
+ def list_roots_response(page:)
+ result = nil
+ NestedTopic::ListRoots.call(
+ service_params.deep_merge(
+ params: {
+ sort: validated_sort,
+ page: page,
+ },
+ topic_view: @topic_view,
+ ),
+ ) do
+ on_success { |response:| result = response }
+ on_failed_contract { raise Discourse::NotFound }
+ on_failure { raise Discourse::NotFound }
+ end
+ result
+ end
+
+ def show_context_response
+ result = nil
+ NestedTopic::ShowContext.call(
+ service_params.deep_merge(
+ params: {
+ target_post_number: params[:post_number].to_i,
+ sort: validated_sort,
+ context_depth: params[:context]&.to_i,
+ },
+ topic_view: @topic_view,
+ ),
+ ) do
+ on_success { |response:| result = response }
+ on_failed_contract { raise Discourse::NotFound }
+ on_model_not_found(:target_post) { raise Discourse::NotFound }
+ on_failure { raise Discourse::NotFound }
+ end
+ result
+ end
+
+ def ensure_nested_replies_enabled
+ raise Discourse::NotFound unless SiteSetting.nested_replies_enabled
+ end
+
+ def ensure_not_pm
+ return unless @topic.private_message?
+
+ if request.get?
+ url = "/t/#{@topic.slug}/#{@topic.id}"
+ post_number = params[:post_number].to_i
+ url << "/#{post_number}" if post_number > 0
+ redirect_to url, status: :found
+ else
+ raise Discourse::NotFound
+ end
+ end
+
+ def find_topic_with_topic_view
+ topic_id = params[:topic_id].to_i
+ @topic_view =
+ TopicView.new(topic_id, current_user, skip_custom_fields: true, skip_post_loading: true)
+ @topic = @topic_view.topic
+ guardian.ensure_can_see!(@topic)
+ rescue Discourse::InvalidAccess
+ raise Discourse::NotFound
+ end
+
+ def find_topic
+ @topic = Topic.find_by(id: params[:topic_id].to_i)
+ raise Discourse::NotFound if @topic.blank? || !guardian.can_see?(@topic)
+ end
+
+ def track_visit
+ return if response.redirect?
+
+ topic_id = @topic.id
+ user_id = current_user&.id
+ ip = request.remote_ip
+
+ TopicsController.defer_track_visit(topic_id, user_id) if should_track_visit?
+
+ TopicsController.defer_topic_view(topic_id, ip, user_id)
+ end
+
+ def should_track_visit?
+ !!((!request.format.json? || params[:track_visit]) && current_user)
+ end
+
+ def validated_sort
+ sort = params[:sort].to_s.downcase
+ NestedReplies::Sort.valid?(sort) ? sort : SiteSetting.nested_replies_default_sort
+ end
+end
diff --git a/app/controllers/similar_topics_controller.rb b/app/controllers/similar_topics_controller.rb
index 05a87e14196..efc1d8de2cf 100644
--- a/app/controllers/similar_topics_controller.rb
+++ b/app/controllers/similar_topics_controller.rb
@@ -22,6 +22,7 @@ class SimilarTopicsController < ApplicationController
end
topics = Topic.similar_to(title, raw, current_user).to_a
+ ActiveRecord::Associations::Preloader.new(records: topics, associations: [:nested_topic]).call
topics.map! { |t| SimilarTopic.new(t) }
render_serialized(topics, SimilarTopicSerializer, root: :similar_topics, rest_serializer: true)
end
diff --git a/app/controllers/topics_controller.rb b/app/controllers/topics_controller.rb
index 39465fe8e91..c525460c695 100644
--- a/app/controllers/topics_controller.rb
+++ b/app/controllers/topics_controller.rb
@@ -181,6 +181,17 @@ class TopicsController < ApplicationController
return
end
+ if !request.format.json? && !use_crawler_layout? && SiteSetting.nested_replies_enabled &&
+ !@topic_view.topic.private_message? &&
+ (@topic_view.topic.nested_topic.present? || SiteSetting.nested_replies_default) &&
+ params[:flat] != "1"
+ url = "/n/#{@topic_view.topic.slug}/#{@topic_view.topic.id}"
+ post_number = opts[:post_number].to_i
+ url << "/#{post_number}" if post_number > 0
+ redirect_to url, status: :found
+ return
+ end
+
track_visit_to_topic
if should_track_visit_to_topic?
diff --git a/app/jobs/scheduled/backfill_nested_reply_stats.rb b/app/jobs/scheduled/backfill_nested_reply_stats.rb
new file mode 100644
index 00000000000..7890ccc5775
--- /dev/null
+++ b/app/jobs/scheduled/backfill_nested_reply_stats.rb
@@ -0,0 +1,132 @@
+# frozen_string_literal: true
+
+module Jobs
+ class BackfillNestedReplyStats < ::Jobs::Scheduled
+ every 5.minutes
+
+ cluster_concurrency 1
+
+ def execute(_ = nil)
+ return unless SiteSetting.nested_replies_enabled
+
+ topic_ids =
+ DB.query_single(<<~SQL, batch_size: SiteSetting.nested_replies_backfill_batch_size)
+ SELECT t.id FROM topics t
+ INNER JOIN nested_topics nt ON nt.topic_id = t.id
+ LEFT JOIN nested_view_post_stats s ON s.post_id = (
+ SELECT p.id FROM posts p
+ WHERE p.topic_id = t.id AND p.post_number = 1
+ LIMIT 1
+ )
+ WHERE t.deleted_at IS NULL
+ AND t.archetype = 'regular'
+ AND s.post_id IS NULL
+ ORDER BY t.id DESC
+ LIMIT :batch_size
+ SQL
+
+ return if topic_ids.empty?
+
+ topic_ids.each do |topic_id|
+ backfill_topic(topic_id)
+ ensure_op_stat_row(topic_id)
+ end
+ end
+
+ private
+
+ # Guarantees the OP has a stats row so the selector (which keys on
+ # s.post_id IS NULL for post_number = 1) will not re-pick this topic
+ # on the next run when it has no qualifying replies. When a reply later
+ # arrives, nested_replies_increment_stats upserts into the same row.
+ def ensure_op_stat_row(topic_id)
+ DB.exec(<<~SQL, topic_id: topic_id)
+ INSERT INTO nested_view_post_stats
+ (post_id, direct_reply_count, whisper_direct_reply_count,
+ total_descendant_count, whisper_total_descendant_count,
+ created_at, updated_at)
+ SELECT p.id, 0, 0, 0, 0, NOW(), NOW()
+ FROM posts p
+ WHERE p.topic_id = :topic_id AND p.post_number = 1
+ ON CONFLICT (post_id) DO NOTHING
+ SQL
+ end
+
+ def backfill_topic(topic_id)
+ DB.exec(<<~SQL, topic_id: topic_id, whisper_type: Post.types[:whisper])
+ WITH RECURSIVE
+ direct_counts AS (
+ SELECT reply_to_post_number AS parent_number, post_type,
+ COUNT(*) AS cnt
+ FROM posts
+ WHERE topic_id = :topic_id
+ AND reply_to_post_number IS NOT NULL
+ AND post_number > 1
+ GROUP BY reply_to_post_number, post_type
+ ),
+ direct_agg AS (
+ SELECT parent_number,
+ SUM(cnt) AS direct_reply_count,
+ SUM(CASE WHEN post_type = :whisper_type THEN cnt ELSE 0 END) AS whisper_direct_reply_count
+ FROM direct_counts
+ GROUP BY parent_number
+ ),
+ edges AS (
+ SELECT id, post_number, reply_to_post_number, post_type
+ FROM posts
+ WHERE topic_id = :topic_id
+ AND reply_to_post_number IS NOT NULL
+ AND post_number > 1
+ ),
+ ancestor_walk AS (
+ SELECT e.reply_to_post_number AS ancestor_number,
+ 1 AS descendant_count,
+ CASE WHEN e.post_type = :whisper_type THEN 1 ELSE 0 END AS whisper_descendant_count,
+ 1 AS depth
+ FROM edges e
+ UNION ALL
+ SELECT p.reply_to_post_number,
+ a.descendant_count,
+ a.whisper_descendant_count,
+ a.depth + 1
+ FROM ancestor_walk a
+ JOIN edges p ON p.post_number = a.ancestor_number
+ WHERE a.depth < 500
+ ),
+ descendant_agg AS (
+ SELECT ancestor_number,
+ COUNT(*) AS total_descendant_count,
+ SUM(whisper_descendant_count) AS whisper_total_descendant_count
+ FROM ancestor_walk
+ GROUP BY ancestor_number
+ ),
+ combined AS (
+ SELECT p.id AS post_id,
+ COALESCE(d.direct_reply_count, 0) AS direct_reply_count,
+ COALESCE(d.whisper_direct_reply_count, 0) AS whisper_direct_reply_count,
+ COALESCE(t.total_descendant_count, 0) AS total_descendant_count,
+ COALESCE(t.whisper_total_descendant_count, 0) AS whisper_total_descendant_count
+ FROM posts p
+ LEFT JOIN direct_agg d ON d.parent_number = p.post_number
+ LEFT JOIN descendant_agg t ON t.ancestor_number = p.post_number
+ WHERE p.topic_id = :topic_id
+ AND (d.parent_number IS NOT NULL OR t.ancestor_number IS NOT NULL)
+ )
+ INSERT INTO nested_view_post_stats
+ (post_id, direct_reply_count, whisper_direct_reply_count,
+ total_descendant_count, whisper_total_descendant_count,
+ created_at, updated_at)
+ SELECT post_id, direct_reply_count, whisper_direct_reply_count,
+ total_descendant_count, whisper_total_descendant_count,
+ NOW(), NOW()
+ FROM combined
+ ON CONFLICT (post_id) DO UPDATE SET
+ direct_reply_count = GREATEST(EXCLUDED.direct_reply_count, nested_view_post_stats.direct_reply_count),
+ whisper_direct_reply_count = GREATEST(EXCLUDED.whisper_direct_reply_count, nested_view_post_stats.whisper_direct_reply_count),
+ total_descendant_count = GREATEST(EXCLUDED.total_descendant_count, nested_view_post_stats.total_descendant_count),
+ whisper_total_descendant_count = GREATEST(EXCLUDED.whisper_total_descendant_count, nested_view_post_stats.whisper_total_descendant_count),
+ updated_at = NOW()
+ SQL
+ end
+ end
+end
diff --git a/app/models/category.rb b/app/models/category.rb
index 87c5fb12999..ba682b5d7c7 100644
--- a/app/models/category.rb
+++ b/app/models/category.rb
@@ -62,6 +62,8 @@ class Category < ActiveRecord::Base
:require_topic_approval,
:require_topic_approval=,
:require_topic_approval?,
+ :nested_replies_default,
+ :nested_replies_default=,
:topic_posting_review_mode,
:topic_posting_review_mode=,
:reply_posting_review_mode,
diff --git a/app/models/category_setting.rb b/app/models/category_setting.rb
index 90e4787916e..378841ca6d5 100644
--- a/app/models/category_setting.rb
+++ b/app/models/category_setting.rb
@@ -51,6 +51,7 @@ end
#
# id :bigint not null, primary key
# auto_bump_cooldown_days :integer default(1)
+# nested_replies_default :boolean default(FALSE), not null
# num_auto_bump_daily :integer default(0)
# reply_posting_review_mode :integer default("no_one"), not null
# topic_posting_review_mode :integer default("no_one"), not null
diff --git a/app/models/concerns/has_nested_reply_stats.rb b/app/models/concerns/has_nested_reply_stats.rb
new file mode 100644
index 00000000000..c05cd4e744a
--- /dev/null
+++ b/app/models/concerns/has_nested_reply_stats.rb
@@ -0,0 +1,106 @@
+# frozen_string_literal: true
+
+module HasNestedReplyStats
+ extend ActiveSupport::Concern
+
+ included do
+ after_create :nested_replies_increment_stats
+ after_destroy :nested_replies_decrement_stats
+ end
+
+ private
+
+ def nested_replies_increment_stats
+ return unless SiteSetting.nested_replies_enabled
+ return if reply_to_post_number.blank?
+
+ ancestors =
+ NestedReplies.walk_ancestors(
+ topic_id: topic_id,
+ start_post_number: reply_to_post_number,
+ exclude_deleted: false,
+ )
+
+ return if ancestors.empty?
+
+ ancestor_ids = ancestors.map(&:id).uniq
+ direct_parent_id = ancestors.find { |a| a.depth == 1 }&.id
+ is_whisper = post_type == Post.types[:whisper] ? 1 : 0
+
+ DB.exec(<<~SQL, ids: ancestor_ids, parent_id: direct_parent_id, whisper: is_whisper)
+ INSERT INTO nested_view_post_stats (post_id, direct_reply_count, total_descendant_count,
+ whisper_direct_reply_count, whisper_total_descendant_count,
+ created_at, updated_at)
+ SELECT aid,
+ CASE WHEN aid = :parent_id THEN 1 ELSE 0 END,
+ 1,
+ CASE WHEN aid = :parent_id THEN :whisper ELSE 0 END,
+ :whisper,
+ NOW(), NOW()
+ FROM unnest(ARRAY[:ids]::int[]) AS aid
+ ON CONFLICT (post_id) DO UPDATE SET
+ total_descendant_count = nested_view_post_stats.total_descendant_count + 1,
+ direct_reply_count = nested_view_post_stats.direct_reply_count +
+ CASE WHEN nested_view_post_stats.post_id = :parent_id THEN 1 ELSE 0 END,
+ whisper_total_descendant_count = nested_view_post_stats.whisper_total_descendant_count + :whisper,
+ whisper_direct_reply_count = nested_view_post_stats.whisper_direct_reply_count +
+ CASE WHEN nested_view_post_stats.post_id = :parent_id THEN :whisper ELSE 0 END,
+ updated_at = NOW()
+ SQL
+ end
+
+ def nested_replies_decrement_stats
+ return unless SiteSetting.nested_replies_enabled
+ if reply_to_post_number.present?
+ stat =
+ NestedViewPostStat.where(post_id: id).pick(
+ :total_descendant_count,
+ :whisper_total_descendant_count,
+ )
+ my_descendants = stat&.first || 0
+ my_whisper_descendants = stat&.second || 0
+ removed = 1 + my_descendants
+ is_whisper = post_type == Post.types[:whisper] ? 1 : 0
+ whisper_removed = is_whisper + my_whisper_descendants
+
+ # Include deleted ancestors — they may still have stat rows from when
+ # they were alive, and those counts need to be decremented.
+ ancestors =
+ NestedReplies.walk_ancestors(
+ topic_id: topic_id,
+ start_post_number: reply_to_post_number,
+ exclude_deleted: false,
+ )
+
+ if ancestors.present?
+ ancestor_ids = ancestors.map(&:id)
+ direct_parent_id = ancestors.find { |a| a.depth == 1 }&.id
+
+ DB.exec(
+ <<~SQL,
+ UPDATE nested_view_post_stats
+ SET total_descendant_count = GREATEST(total_descendant_count - :removed, 0),
+ direct_reply_count = GREATEST(
+ direct_reply_count - CASE WHEN post_id = :parent_id THEN 1 ELSE 0 END,
+ 0
+ ),
+ whisper_total_descendant_count = GREATEST(whisper_total_descendant_count - :whisper_removed, 0),
+ whisper_direct_reply_count = GREATEST(
+ whisper_direct_reply_count - CASE WHEN post_id = :parent_id THEN :is_whisper ELSE 0 END,
+ 0
+ ),
+ updated_at = NOW()
+ WHERE post_id = ANY(ARRAY[:ids]::int[])
+ SQL
+ ids: ancestor_ids,
+ parent_id: direct_parent_id,
+ removed: removed,
+ whisper_removed: whisper_removed,
+ is_whisper: is_whisper,
+ )
+ end
+ end
+
+ NestedViewPostStat.where(post_id: id).delete_all
+ end
+end
diff --git a/app/models/nested_topic.rb b/app/models/nested_topic.rb
new file mode 100644
index 00000000000..02d94da6635
--- /dev/null
+++ b/app/models/nested_topic.rb
@@ -0,0 +1,39 @@
+# frozen_string_literal: true
+
+class NestedTopic < ActiveRecord::Base
+ self.ignored_columns = ["pinned_post_number"]
+
+ MAX_PINNED_POSTS = 10
+
+ belongs_to :topic, -> { with_deleted }
+
+ validates :topic_id, presence: true, uniqueness: true
+
+ def pin_limit_reached?
+ pinned_post_ids.length >= MAX_PINNED_POSTS
+ end
+
+ def toggle_pin(post_id)
+ if pinned_post_ids.include?(post_id)
+ self.pinned_post_ids = pinned_post_ids - [post_id]
+ else
+ self.pinned_post_ids = pinned_post_ids + [post_id]
+ end
+ save!
+ end
+end
+
+# == Schema Information
+#
+# Table name: nested_topics
+#
+# id :bigint not null, primary key
+# pinned_post_ids :bigint default([]), not null, is an Array
+# created_at :datetime not null
+# updated_at :datetime not null
+# topic_id :bigint not null
+#
+# Indexes
+#
+# index_nested_topics_on_topic_id (topic_id) UNIQUE
+#
diff --git a/app/models/nested_view_post_stat.rb b/app/models/nested_view_post_stat.rb
new file mode 100644
index 00000000000..ae2c325ae81
--- /dev/null
+++ b/app/models/nested_view_post_stat.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+class NestedViewPostStat < ActiveRecord::Base
+ belongs_to :post
+end
+
+# == Schema Information
+#
+# Table name: nested_view_post_stats
+#
+# id :bigint not null, primary key
+# direct_reply_count :integer default(0), not null
+# total_descendant_count :integer default(0), not null
+# whisper_direct_reply_count :integer default(0), not null
+# whisper_total_descendant_count :integer default(0), not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# post_id :bigint not null
+#
+# Indexes
+#
+# index_nested_view_post_stats_on_post_id (post_id) UNIQUE
+#
diff --git a/app/models/post.rb b/app/models/post.rb
index a5e64d658fd..69df17c11c1 100644
--- a/app/models/post.rb
+++ b/app/models/post.rb
@@ -11,6 +11,7 @@ class Post < ActiveRecord::Base
include LimitedEdit
include Localizable
include HasPostUploadReferences
+ include HasNestedReplyStats
cattr_accessor :plugin_permitted_create_params, :plugin_permitted_update_params
self.plugin_permitted_create_params = {}
diff --git a/app/models/topic.rb b/app/models/topic.rb
index 4e5f17068a5..8744538033f 100644
--- a/app/models/topic.rb
+++ b/app/models/topic.rb
@@ -307,6 +307,7 @@ class Topic < ActiveRecord::Base
has_one :topic_search_data
has_one :topic_embed, dependent: :destroy
has_one :linked_topic, dependent: :destroy
+ has_one :nested_topic, dependent: :destroy
belongs_to :image_upload, class_name: "Upload"
has_many :topic_thumbnails, through: :image_upload
diff --git a/app/serializers/category_serializer.rb b/app/serializers/category_serializer.rb
index 3909129b77a..13382413640 100644
--- a/app/serializers/category_serializer.rb
+++ b/app/serializers/category_serializer.rb
@@ -8,6 +8,7 @@ class CategorySerializer < SiteCategorySerializer
:num_auto_bump_daily,
:require_reply_approval,
:require_topic_approval,
+ :nested_replies_default,
:topic_posting_review_mode,
:reply_posting_review_mode
end
diff --git a/app/serializers/current_user_serializer.rb b/app/serializers/current_user_serializer.rb
index 1c9ff8bb1e9..fd2ddda623d 100644
--- a/app/serializers/current_user_serializer.rb
+++ b/app/serializers/current_user_serializer.rb
@@ -27,6 +27,7 @@ class CurrentUserSerializer < BasicUserSerializer
:no_password,
:can_delete_account,
:can_post_anonymously,
+ :can_toggle_nested_mode,
:can_ignore_users,
:can_edit_tags,
:can_delete_all_posts_and_topics,
@@ -199,6 +200,14 @@ class CurrentUserSerializer < BasicUserSerializer
(is_anonymous || object.in_any_groups?(SiteSetting.anonymous_posting_allowed_groups_map))
end
+ def can_toggle_nested_mode
+ object.in_any_groups?(SiteSetting.nested_replies_toggle_mode_groups_map)
+ end
+
+ def include_can_toggle_nested_mode?
+ SiteSetting.nested_replies_enabled
+ end
+
def can_ignore_users
scope.can_ignore_users?
end
diff --git a/app/serializers/topic_list_item_serializer.rb b/app/serializers/topic_list_item_serializer.rb
index 0e5194b1e69..6c4d02098e7 100644
--- a/app/serializers/topic_list_item_serializer.rb
+++ b/app/serializers/topic_list_item_serializer.rb
@@ -19,7 +19,8 @@ class TopicListItemSerializer < ListableTopicSerializer
:featured_link_root_domain,
:allowed_user_count,
:participant_groups,
- :is_hot
+ :is_hot,
+ :is_nested_view
has_many :posters, serializer: TopicPosterSerializer, embed: :objects
has_many :participants, serializer: TopicPosterSerializer, embed: :objects
@@ -147,6 +148,14 @@ class TopicListItemSerializer < ListableTopicSerializer
theme_enabled || plugin_enabled
end
+ def is_nested_view
+ object.nested_topic.present? || SiteSetting.nested_replies_default
+ end
+
+ def include_is_nested_view?
+ SiteSetting.nested_replies_enabled && !object.private_message?
+ end
+
private
def serialize_topic_op_likes_data_enabled?
diff --git a/app/serializers/topic_view_serializer.rb b/app/serializers/topic_view_serializer.rb
index a21afc1a7ca..a730b493c98 100644
--- a/app/serializers/topic_view_serializer.rb
+++ b/app/serializers/topic_view_serializer.rb
@@ -80,6 +80,7 @@ class TopicViewSerializer < ApplicationSerializer
:slow_mode_enabled_until,
:has_localized_content,
:can_localize_topic,
+ :is_nested_view,
)
has_one :details, serializer: TopicViewDetailsSerializer, root: false, embed: :objects
@@ -338,4 +339,12 @@ class TopicViewSerializer < ApplicationSerializer
def include_can_localize_topic?
SiteSetting.content_localization_enabled && scope.can_localize_topic?(object.topic)
end
+
+ def is_nested_view
+ object.topic.nested_topic.present? || SiteSetting.nested_replies_default
+ end
+
+ def include_is_nested_view?
+ SiteSetting.nested_replies_enabled && !object.topic.private_message?
+ end
end
diff --git a/app/services/nested_topic/list_children.rb b/app/services/nested_topic/list_children.rb
new file mode 100644
index 00000000000..e22053bda23
--- /dev/null
+++ b/app/services/nested_topic/list_children.rb
@@ -0,0 +1,126 @@
+# frozen_string_literal: true
+
+class NestedTopic::ListChildren
+ include Service::Base
+
+ params do
+ attribute :parent_post_number, :integer
+ attribute :sort, :string
+ attribute :page, :integer
+ attribute :depth, :integer
+
+ validates :parent_post_number, presence: true
+ validates :sort, presence: true
+ validates :page, presence: true, numericality: { greater_than_or_equal_to: 0 }
+ validates :depth, presence: true, numericality: { greater_than_or_equal_to: 1 }
+ end
+
+ model :loader, :build_loader
+ model :preloader, :build_preloader
+ model :serializer, :build_serializer
+ step :load_children
+ only_if(:nested) { step :expand_reply_trees }
+ step :prepare_posts
+ step :serialize_children
+
+ private
+
+ def build_loader(topic_view:, guardian:)
+ NestedReplies::TreeLoader.new(topic: topic_view.topic, guardian: guardian)
+ end
+
+ def build_preloader(topic_view:, guardian:)
+ NestedReplies::PostPreloader.new(
+ topic_view: topic_view,
+ topic: topic_view.topic,
+ current_user: guardian.user,
+ guardian: guardian,
+ )
+ end
+
+ def build_serializer(topic_view:, guardian:)
+ NestedReplies::PostTreeSerializer.new(
+ topic: topic_view.topic,
+ topic_view: topic_view,
+ guardian: guardian,
+ )
+ end
+
+ def nested(params:, loader:)
+ !flattened?(params, loader)
+ end
+
+ def load_children(params:, loader:, topic_view:)
+ context[:flatten] = flattened?(params, loader)
+ per_page = NestedReplies::TreeLoader::CHILDREN_PER_PAGE
+
+ children_scope =
+ if context[:flatten]
+ loader.flat_descendants_scope(
+ params.parent_post_number,
+ sort: params.sort,
+ offset: params.page * per_page,
+ limit: per_page,
+ )
+ else
+ scope =
+ topic_view
+ .topic
+ .posts
+ .where(reply_to_post_number: params.parent_post_number)
+ .where(post_number: 2..)
+ scope = loader.apply_visibility(scope)
+ scope = NestedReplies::Sort.apply(scope, params.sort)
+ scope.offset(params.page * per_page).limit(per_page)
+ end
+
+ context[:children_posts] = loader.load_posts_for_tree(children_scope).to_a
+ context[:children_map] = {}
+ context[:all_posts] = context[:children_posts]
+ end
+
+ def expand_reply_trees(params:, loader:, children_posts:)
+ remaining_depth =
+ if params.depth < loader.configured_max_depth
+ [NestedReplies::TreeLoader::PRELOAD_DEPTH, loader.configured_max_depth - params.depth].min
+ else
+ 0
+ end
+ tree_data = loader.batch_preload_tree(children_posts, params.sort, max_depth: remaining_depth)
+ context[:children_map] = tree_data[:children_map]
+ context[:all_posts] = tree_data[:all_posts]
+ end
+
+ def prepare_posts(loader:, preloader:, all_posts:)
+ preloader.prepare(all_posts)
+ context[:reply_counts] = loader.direct_reply_counts(all_posts.map(&:post_number))
+ context[:descendant_counts] = loader.total_descendant_counts(all_posts.map(&:id))
+ end
+
+ def serialize_children(
+ params:,
+ children_posts:,
+ children_map:,
+ reply_counts:,
+ descendant_counts:,
+ serializer:,
+ flatten:
+ )
+ context[:response] = {
+ children:
+ children_posts.map do |child|
+ if flatten
+ serializer.serialize_post(child, reply_counts, descendant_counts).merge(children: [])
+ else
+ serializer.serialize_tree(child, children_map, reply_counts, descendant_counts)
+ end
+ end,
+ has_more: children_posts.size == NestedReplies::TreeLoader::CHILDREN_PER_PAGE,
+ page: params.page,
+ }
+ end
+
+ def flattened?(params, loader)
+ SiteSetting.nested_replies_cap_nesting_depth && params.depth >= loader.configured_max_depth
+ end
+end
diff --git a/app/services/nested_topic/list_roots.rb b/app/services/nested_topic/list_roots.rb
new file mode 100644
index 00000000000..4977f17a04d
--- /dev/null
+++ b/app/services/nested_topic/list_roots.rb
@@ -0,0 +1,123 @@
+# frozen_string_literal: true
+
+class NestedTopic::ListRoots
+ include Service::Base
+
+ params do
+ attribute :sort, :string
+ attribute :page, :integer
+
+ validates :sort, presence: true
+ validates :page, presence: true, numericality: { greater_than_or_equal_to: 0 }
+ end
+
+ model :loader, :build_loader
+ model :preloader, :build_preloader
+ model :serializer, :build_serializer
+ step :load_roots
+ only_if(:initial_page) { step :promote_pinned_roots }
+ step :expand_reply_trees
+ step :prepare_posts
+ step :serialize_roots
+ only_if(:initial_page) { step :enrich_with_topic_metadata }
+
+ private
+
+ def build_loader(topic_view:, guardian:)
+ NestedReplies::TreeLoader.new(topic: topic_view.topic, guardian: guardian)
+ end
+
+ def build_preloader(topic_view:, guardian:)
+ NestedReplies::PostPreloader.new(
+ topic_view: topic_view,
+ topic: topic_view.topic,
+ current_user: guardian.user,
+ guardian: guardian,
+ )
+ end
+
+ def build_serializer(topic_view:, guardian:)
+ NestedReplies::PostTreeSerializer.new(
+ topic: topic_view.topic,
+ topic_view: topic_view,
+ guardian: guardian,
+ )
+ end
+
+ def initial_page(params:)
+ params.page == 0
+ end
+
+ def load_roots(params:, loader:, topic_view:)
+ pinned_post_ids = topic_view.topic.nested_topic&.pinned_post_ids.presence
+ 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
+ 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)
+ end
+
+ def expand_reply_trees(loader:, params:, roots:)
+ tree_data =
+ loader.batch_preload_tree(
+ roots,
+ params.sort,
+ max_depth: NestedReplies::TreeLoader::PRELOAD_DEPTH,
+ )
+ context[:children_map] = tree_data[:children_map]
+ context[:all_posts] = tree_data[:all_posts]
+ end
+
+ def prepare_posts(params:, loader:, preloader:, all_posts:)
+ posts = params.page == 0 ? [loader.op_post] + all_posts : all_posts.dup
+
+ preloader.prepare(posts)
+ context[:reply_counts] = loader.direct_reply_counts(posts.map(&:post_number))
+ context[:descendant_counts] = loader.total_descendant_counts(posts.map(&:id))
+ end
+
+ def serialize_roots(
+ params:,
+ roots:,
+ has_more_roots:,
+ children_map:,
+ reply_counts:,
+ descendant_counts:,
+ serializer:
+ )
+ context[:response] = {
+ roots:
+ roots.map do |root|
+ serializer.serialize_tree(root, children_map, reply_counts, descendant_counts)
+ end,
+ has_more_roots: has_more_roots,
+ page: params.page,
+ }
+ end
+
+ def enrich_with_topic_metadata(
+ params:,
+ serializer:,
+ loader:,
+ topic_view:,
+ reply_counts:,
+ descendant_counts:,
+ response:,
+ pinned_post_ids:
+ )
+ response[:topic] = serializer.serialize_topic
+ response[:op_post] = serializer.serialize_post(loader.op_post, reply_counts, descendant_counts)
+ response[:sort] = params.sort
+ response[:message_bus_last_id] = topic_view.message_bus_last_id
+ response[:pinned_post_ids] = pinned_post_ids if pinned_post_ids.present?
+ end
+end
diff --git a/app/services/nested_topic/show_context.rb b/app/services/nested_topic/show_context.rb
new file mode 100644
index 00000000000..e9a73246c41
--- /dev/null
+++ b/app/services/nested_topic/show_context.rb
@@ -0,0 +1,159 @@
+# frozen_string_literal: true
+
+class NestedTopic::ShowContext
+ include Service::Base
+
+ params do
+ attribute :target_post_number, :integer
+ attribute :sort, :string
+ attribute :context_depth, :integer
+
+ validates :target_post_number, presence: true
+ validates :sort, presence: true
+ validates :context_depth,
+ numericality: {
+ greater_than_or_equal_to: 0,
+ less_than_or_equal_to: 100,
+ },
+ allow_nil: true
+ end
+
+ model :loader, :build_loader
+ model :preloader, :build_preloader
+ model :serializer, :build_serializer
+ model :target_post
+ step :initialize_ancestor_data
+ only_if(:should_walk_ancestors) do
+ step :walk_ancestors
+ only_if(:ancestors_found) { step :load_siblings }
+ end
+ step :expand_reply_trees
+ step :prepare_posts
+ step :serialize_context
+
+ private
+
+ def build_loader(topic_view:, guardian:)
+ NestedReplies::TreeLoader.new(topic: topic_view.topic, guardian: guardian)
+ end
+
+ def build_preloader(topic_view:, guardian:)
+ NestedReplies::PostPreloader.new(
+ topic_view: topic_view,
+ topic: topic_view.topic,
+ current_user: guardian.user,
+ guardian: guardian,
+ )
+ end
+
+ def build_serializer(topic_view:, guardian:)
+ NestedReplies::PostTreeSerializer.new(
+ topic: topic_view.topic,
+ topic_view: topic_view,
+ guardian: guardian,
+ )
+ end
+
+ def fetch_target_post(params:, topic_view:, loader:)
+ post = topic_view.topic.posts.find_by(post_number: params.target_post_number)
+ return if post.nil?
+ return if loader.visible_post_types.exclude?(post.post_type)
+ post
+ end
+
+ def should_walk_ancestors(params:, target_post:)
+ return if params.context_depth == 0
+ return if target_post.reply_to_post_number.blank?
+ return if target_post.reply_to_post_number == 1
+ true
+ end
+
+ def initialize_ancestor_data
+ context[:ancestors] = []
+ context[:ancestors_truncated] = false
+ context[:siblings_map] = {}
+ end
+
+ def walk_ancestors(params:, target_post:, topic_view:, loader:)
+ depth_limit = params.context_depth || loader.configured_max_depth
+
+ ancestor_rows =
+ NestedReplies.walk_ancestors(
+ topic_id: topic_view.topic.id,
+ start_post_number: target_post.reply_to_post_number,
+ limit: depth_limit,
+ exclude_deleted: false,
+ stop_at_op: true,
+ )
+ ancestor_post_numbers = ancestor_rows.sort_by { |a| -a.depth }.map(&:post_number)
+
+ if ancestor_post_numbers.present?
+ scope = topic_view.topic.posts.where(post_number: ancestor_post_numbers)
+ scope = loader.apply_visibility(scope)
+ loaded = loader.load_posts_for_tree(scope).to_a.index_by(&:post_number)
+ context[:ancestors] = ancestor_post_numbers.filter_map { |pn| loaded[pn] }
+ end
+
+ if context[:ancestors].present?
+ top_ancestor = context[:ancestors].first
+ context[:ancestors_truncated] = top_ancestor.reply_to_post_number.present? &&
+ top_ancestor.reply_to_post_number != 1
+ end
+ end
+
+ def ancestors_found(ancestors:)
+ ancestors.present?
+ end
+
+ def load_siblings(params:, loader:, ancestors:)
+ context[:siblings_map] = loader.batch_load_siblings(ancestors, params.sort)
+ end
+
+ def expand_reply_trees(params:, loader:, target_post:)
+ tree_data =
+ loader.batch_preload_tree(
+ [target_post],
+ params.sort,
+ max_depth: NestedReplies::TreeLoader::PRELOAD_DEPTH,
+ )
+ context[:children_map] = tree_data[:children_map]
+ context[:tree_posts] = tree_data[:all_posts]
+ end
+
+ def prepare_posts(loader:, preloader:, target_post:, ancestors:, siblings_map:, tree_posts:)
+ all_posts = [loader.op_post, target_post] + ancestors + siblings_map.values.flatten + tree_posts
+ all_posts.uniq!(&:id)
+
+ preloader.prepare(all_posts)
+ context[:reply_counts] = loader.direct_reply_counts(all_posts.map(&:post_number))
+ context[:descendant_counts] = loader.total_descendant_counts(all_posts.map(&:id))
+ end
+
+ def serialize_context(
+ loader:,
+ serializer:,
+ target_post:,
+ topic_view:,
+ ancestors:,
+ ancestors_truncated:,
+ siblings_map:,
+ children_map:,
+ reply_counts:,
+ descendant_counts:
+ )
+ context[:response] = {
+ topic: serializer.serialize_topic,
+ op_post: serializer.serialize_post(loader.op_post, reply_counts, descendant_counts),
+ ancestor_chain:
+ ancestors.map { |a| serializer.serialize_post(a, reply_counts, descendant_counts) },
+ ancestors_truncated: ancestors_truncated,
+ siblings:
+ siblings_map.transform_values do |posts|
+ posts.map { |p| serializer.serialize_post(p, reply_counts, descendant_counts) }
+ end,
+ target_post:
+ serializer.serialize_tree(target_post, children_map, reply_counts, descendant_counts),
+ message_bus_last_id: topic_view.message_bus_last_id,
+ }
+ end
+end
diff --git a/app/services/nested_topic/toggle.rb b/app/services/nested_topic/toggle.rb
new file mode 100644
index 00000000000..7706a6ebfd6
--- /dev/null
+++ b/app/services/nested_topic/toggle.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+class NestedTopic::Toggle
+ include Service::Base
+
+ params do
+ attribute :topic_id, :integer
+ attribute :enabled, :boolean
+
+ validates :topic_id, presence: true
+ validates :enabled, inclusion: { in: [true, false] }
+ end
+
+ model :topic
+ policy :staff_can_edit
+
+ transaction do
+ only_if(:enabling) { step :enable_nested_view }
+ only_if(:disabling) { step :disable_nested_view }
+ end
+
+ private
+
+ def fetch_topic(params:)
+ Topic.find_by(id: params.topic_id)
+ end
+
+ def staff_can_edit(guardian:, topic:)
+ guardian.can_edit?(topic) && guardian.is_staff?
+ end
+
+ def enabling(params:)
+ params.enabled
+ end
+
+ def disabling(params:)
+ !params.enabled
+ end
+
+ def enable_nested_view(topic:)
+ NestedTopic.find_or_create_by!(topic: topic) unless topic.nested_topic
+ end
+
+ def disable_nested_view(topic:)
+ topic.nested_topic&.destroy!
+ end
+end
diff --git a/app/services/nested_topic/toggle_pin.rb b/app/services/nested_topic/toggle_pin.rb
new file mode 100644
index 00000000000..28556f1c5ef
--- /dev/null
+++ b/app/services/nested_topic/toggle_pin.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+class NestedTopic::TogglePin
+ include Service::Base
+
+ params do
+ attribute :topic_id, :integer
+ attribute :post_id, :integer
+
+ validates :topic_id, presence: true
+ validates :post_id, presence: true
+ end
+
+ model :topic
+ model :post
+ policy :staff_can_edit
+ policy :post_is_root
+ model :nested_topic, :find_or_create_nested_topic
+ policy :within_pin_limit
+ transaction { step :toggle_pin }
+
+ private
+
+ def fetch_topic(params:)
+ Topic.find_by(id: params.topic_id)
+ end
+
+ def fetch_post(topic:, params:)
+ topic.posts.find_by(id: params.post_id)
+ end
+
+ def staff_can_edit(guardian:, topic:)
+ guardian.can_edit?(topic) && guardian.is_staff?
+ end
+
+ def post_is_root(post:)
+ post.reply_to_post_number.blank? || post.reply_to_post_number == 1
+ end
+
+ def find_or_create_nested_topic(topic:)
+ topic.nested_topic || NestedTopic.find_or_create_by!(topic: topic)
+ end
+
+ def within_pin_limit(nested_topic:, post:)
+ !nested_topic.pin_limit_reached? || nested_topic.pinned_post_ids.include?(post.id)
+ end
+
+ def toggle_pin(nested_topic:, post:)
+ nested_topic.toggle_pin(post.id)
+ end
+end
diff --git a/config/initializers/300-nested-replies.rb b/config/initializers/300-nested-replies.rb
new file mode 100644
index 00000000000..8e298559a6e
--- /dev/null
+++ b/config/initializers/300-nested-replies.rb
@@ -0,0 +1,12 @@
+# frozen_string_literal: true
+
+Rails.application.config.to_prepare { require "nested_replies" }
+
+DiscourseEvent.on(:topic_created) do |topic, _opts, _user|
+ next unless SiteSetting.nested_replies_enabled
+ next unless topic.regular?
+
+ if SiteSetting.nested_replies_default || topic.category&.nested_replies_default
+ NestedTopic.find_or_create_by!(topic: topic)
+ end
+end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index fc2b2896cc4..5136e3039fd 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -3905,6 +3905,44 @@ en:
name: "Un-pin"
description: "Un-pin all the selected topics that are pinned to a category or pinned globally"
+ nested_replies:
+ nested_view: "Nested view"
+ flat_view: "Flat view"
+ view_as_nested: "View as nested"
+ view_as_flat: "View as flat"
+ sort:
+ label: "Sort by"
+ top: "Top"
+ new: "New"
+ old: "Old"
+ load_more_children:
+ one: "%{count} more reply"
+ other: "%{count} more replies"
+ load_more_children_generic: "More replies"
+ continue_thread: "Continue this thread"
+ new_replies:
+ one: "%{count} new reply"
+ other: "%{count} new replies"
+ collapsed_replies:
+ one: "%{count} reply"
+ other: "%{count} replies"
+ collapse: "Collapse"
+ collapse_parent: "Collapse parent thread"
+ category_settings:
+ default_nested_view: "Use nested view as default for topics in this category"
+ no_replies: "No replies yet."
+ deleted_post_placeholder: "[deleted]"
+ op_badge: "OP"
+ pinned_reply: "Pinned"
+ pin_reply: "Pin to top"
+ unpin_reply: "Unpin"
+ topic_admin_menu:
+ enable_nested_replies: "Enable nested replies"
+ disable_nested_replies: "Disable nested replies"
+ context:
+ banner: "You are viewing a single thread from this topic."
+ view_full_topic: "View full topic"
+ view_parent_context: "View parent context"
topic:
filter_to:
one: "%{count} post in topic"
@@ -4583,6 +4621,7 @@ en:
delete: "delete this post"
undelete_action: "Undelete post"
undelete: "undelete this post"
+ view_deleted: "view deleted post content"
share_action: "Share"
share: "share a link to this post"
copy_action: "Copy link"
@@ -8888,6 +8927,7 @@ en:
groups: "Groups"
dashboard: "Dashboard"
navigation: "Navigation"
+ nested_replies: "Nested replies"
experimental: "Experimental"
secret_list:
invalid_input: "Input fields cannot be empty or contain vertical bar character."
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 357fd96bd90..865dbc522cf 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -2786,6 +2786,13 @@ en:
content_localization_crawler_param: "Serve localized content to web crawlers when 'content localization enabled' and 'set locale from param' is enabled. The list of supported locales is defined in 'content localization supported locales'."
content_localization_use_default_locale_when_unsupported: "Serve localized content in the site's default locale to users whose preferred language is not listed in 'content localization supported locales'."
content_localization_allow_author_localization: "Allow authors update localizations of their own topics and posts via the post menu."
+ nested_replies_enabled: "Enable the nested replies view for topics."
+ nested_replies_default: "Use nested replies as the default view for all topics."
+ nested_replies_default_sort: "Default sort algorithm for nested replies view."
+ nested_replies_max_depth: "Maximum visual nesting depth for threaded replies. Posts deeper than this show a 'Continue this thread' link."
+ nested_replies_toggle_mode_groups: "Groups that can toggle between nested and flat view."
+ nested_replies_backfill_batch_size: "Number of topics to backfill nested reply stats for per scheduled run."
+ nested_replies_cap_nesting_depth: "Cap reply nesting at the maximum visual depth. When enabled, replies to the deepest level are re-parented as siblings instead of children."
fake_upcoming_change: "This is a fake upcoming change for testing purposes. No need to translate this string."
floating_dismiss_topics_on_mobile: "Shows a floating 'Dismiss...' button on mobile for the topic list for easier access and to free up space in the top of the topic list"
rename_faq_to_guidelines: "This change renames the FAQ page to Guidelines. The FAQ page will still be available at /faq. The 'faq url' setting works as before."
diff --git a/config/routes.rb b/config/routes.rb
index 05fd437bc07..029b3ecb1fb 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1416,6 +1416,19 @@ Discourse::Application.routes.draw do
get "search" => "search#show"
post "search/click" => "search#click"
+ # Nested replies routes
+ scope "n/:slug/:topic_id", constraints: { topic_id: /\d+/ } do
+ get "/children/:post_number" => "nested_topics#children",
+ :constraints => {
+ post_number: /\d+/,
+ }
+ get "/context/:post_number" => "nested_topics#context", :constraints => { post_number: /\d+/ }
+ put "/pin" => "nested_topics#pin"
+ put "/toggle" => "nested_topics#toggle"
+ get "/:post_number" => "nested_topics#context", :constraints => { post_number: /\d+/ }
+ get "/" => "nested_topics#show"
+ end
+
# Topics resource
get "t/:id" => "topics#show"
put "t/:topic_id" => "topics#update", :constraints => { topic_id: /\d+/ }
diff --git a/config/site_settings.yml b/config/site_settings.yml
index 2ecce012776..58d291adb23 100644
--- a/config/site_settings.yml
+++ b/config/site_settings.yml
@@ -1804,6 +1804,70 @@ content_localization:
default: true
area: "localization"
+nested_replies:
+ nested_replies_enabled:
+ default: false
+ client: true
+ area: "posts_and_topics"
+ hidden: true
+ nested_replies_default:
+ default: false
+ client: true
+ area: "posts_and_topics"
+ depends_on:
+ - "nested_replies_enabled"
+ depends_behavior: "hidden"
+ hidden: true
+ nested_replies_default_sort:
+ default: "top"
+ client: true
+ type: enum
+ choices:
+ - top
+ - new
+ - old
+ area: "posts_and_topics"
+ depends_on:
+ - "nested_replies_enabled"
+ depends_behavior: "hidden"
+ hidden: true
+ nested_replies_max_depth:
+ default: 10
+ client: true
+ type: integer
+ min: 1
+ max: 10
+ area: "posts_and_topics"
+ depends_on:
+ - "nested_replies_enabled"
+ depends_behavior: "hidden"
+ hidden: true
+ nested_replies_cap_nesting_depth:
+ default: false
+ client: true
+ area: "posts_and_topics"
+ depends_on:
+ - "nested_replies_enabled"
+ depends_behavior: "hidden"
+ hidden: true
+ nested_replies_backfill_batch_size:
+ default: 100
+ type: integer
+ min: 1
+ max: 10000
+ hidden: true
+ nested_replies_toggle_mode_groups:
+ type: group_list
+ list_type: compact
+ default: "3"
+ allow_any: false
+ refresh: true
+ area: "posts_and_topics"
+ depends_on:
+ - "nested_replies_enabled"
+ depends_behavior: "hidden"
+ hidden: true
+
email:
email_time_window_mins:
default: 10
diff --git a/db/migrate/20260325120000_create_nested_view_post_stats_in_core.rb b/db/migrate/20260325120000_create_nested_view_post_stats_in_core.rb
new file mode 100644
index 00000000000..a50b11da1fb
--- /dev/null
+++ b/db/migrate/20260325120000_create_nested_view_post_stats_in_core.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+class CreateNestedViewPostStatsInCore < ActiveRecord::Migration[8.0]
+ def change
+ create_table :nested_view_post_stats, if_not_exists: true do |t|
+ t.bigint :post_id, null: false
+ t.integer :direct_reply_count, default: 0, null: false
+ t.integer :total_descendant_count, default: 0, null: false
+ t.integer :whisper_direct_reply_count, default: 0, null: false
+ t.integer :whisper_total_descendant_count, default: 0, null: false
+ t.timestamps
+ end
+
+ add_index :nested_view_post_stats, :post_id, unique: true, if_not_exists: true
+
+ create_table :nested_topics, if_not_exists: true do |t|
+ t.bigint :topic_id, null: false
+ t.bigint :pinned_post_ids, array: true, default: [], null: false
+ t.timestamps
+ end
+
+ # On sites that ran the nested-replies plugin, nested_topics was created with
+ # pinned_post_number instead of pinned_post_ids. Add the new column if missing.
+ unless column_exists?(:nested_topics, :pinned_post_ids)
+ add_column :nested_topics, :pinned_post_ids, :bigint, array: true, default: [], null: false
+ end
+
+ add_index :nested_topics, :topic_id, unique: true, if_not_exists: true
+
+ unless column_exists?(:category_settings, :nested_replies_default)
+ add_column :category_settings, :nested_replies_default, :boolean, default: false, null: false
+ end
+ end
+end
diff --git a/db/post_migrate/20260330161714_drop_pinned_post_number_from_nested_topics.rb b/db/post_migrate/20260330161714_drop_pinned_post_number_from_nested_topics.rb
new file mode 100644
index 00000000000..472716983b3
--- /dev/null
+++ b/db/post_migrate/20260330161714_drop_pinned_post_number_from_nested_topics.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+class DropPinnedPostNumberFromNestedTopics < ActiveRecord::Migration[8.0]
+ def up
+ if column_exists?(:nested_topics, :pinned_post_number)
+ remove_column :nested_topics, :pinned_post_number
+ end
+ end
+
+ def down
+ unless column_exists?(:nested_topics, :pinned_post_number)
+ add_column :nested_topics, :pinned_post_number, :integer
+ end
+ end
+end
diff --git a/frontend/discourse/app/adapters/post.js b/frontend/discourse/app/adapters/post.js
index 0ba377304a0..baea6f2a347 100644
--- a/frontend/discourse/app/adapters/post.js
+++ b/frontend/discourse/app/adapters/post.js
@@ -11,6 +11,9 @@ export default class PostAdapter extends RestAdapter {
createRecord(store, type, args) {
const typeField = underscore(type);
+ // "nested_post" is unrelated to the nested replies feature — it tells
+ // the server to return the full JSON envelope ({post, action, success})
+ // instead of the bare post object (legacy API compat).
args.nested_post = true;
return ajax(this.pathFor(store, type), {
type: "POST",
diff --git a/frontend/discourse/app/components/admin-post-menu.gjs b/frontend/discourse/app/components/admin-post-menu.gjs
index 1f44576ee91..8a7a06253c0 100644
--- a/frontend/discourse/app/components/admin-post-menu.gjs
+++ b/frontend/discourse/app/components/admin-post-menu.gjs
@@ -1,6 +1,7 @@
import Component from "@glimmer/component";
import { fn } from "@ember/helper";
import { action } from "@ember/object";
+import { getOwner } from "@ember/owner";
import { service } from "@ember/service";
import DButton from "discourse/components/d-button";
import DropdownMenu from "discourse/components/dropdown-menu";
@@ -10,6 +11,7 @@ import { and, not, or } from "discourse/truth-helpers";
export default class AdminPostMenu extends Component {
@service currentUser;
@service siteSettings;
+ @service router;
@service adminPostMenuButtons;
get reviewUrl() {
@@ -28,6 +30,34 @@ export default class AdminPostMenu extends Component {
return this.currentUser?.canChangePostOwner;
}
+ get nestedPinButton() {
+ if (!this.siteSettings.nested_replies_enabled) {
+ return null;
+ }
+ if (!this.router.currentRouteName?.startsWith("nested")) {
+ return null;
+ }
+
+ const post = this.args.data.post;
+ if (post.post_number === 1) {
+ return null;
+ }
+ if (post.reply_to_post_number && post.reply_to_post_number !== 1) {
+ return null;
+ }
+
+ const nestedController = getOwner(this).lookup("controller:nested");
+ const isPinned = nestedController?.pinnedPostIds?.includes(post.id);
+
+ return {
+ isPinned,
+ label: isPinned
+ ? "nested_replies.unpin_reply"
+ : "nested_replies.pin_reply",
+ action: () => nestedController?.togglePinPost(post),
+ };
+ }
+
@action
async topicAction(actionName) {
await this.args.close();
@@ -226,6 +256,17 @@ export default class AdminPostMenu extends Component {
</dropdown.item>
{{/if}}
+ {{#if this.nestedPinButton}}
+ <dropdown.item>
+ <DButton
+ @label={{this.nestedPinButton.label}}
+ @icon="thumbtack"
+ class="btn btn-transparent pin-reply"
+ @action={{fn this.extraAction this.nestedPinButton}}
+ />
+ </dropdown.item>
+ {{/if}}
+
{{#each this.extraButtons as |button|}}
<dropdown.item>
<DButton
diff --git a/frontend/discourse/app/components/nested-context-view.gjs b/frontend/discourse/app/components/nested-context-view.gjs
new file mode 100644
index 00000000000..ae2ab29d010
--- /dev/null
+++ b/frontend/discourse/app/components/nested-context-view.gjs
@@ -0,0 +1,196 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { array, fn } from "@ember/helper";
+import { action } from "@ember/object";
+import { cancel, next, schedule } from "@ember/runloop";
+import { service } from "@ember/service";
+import DButton from "discourse/components/d-button";
+import icon from "discourse/helpers/d-icon";
+import getURL from "discourse/lib/get-url";
+import PostStreamViewportTracker from "discourse/modifiers/post-stream-viewport-tracker";
+import { or } from "discourse/truth-helpers";
+import { i18n } from "discourse-i18n";
+import NestedFloatingActions from "./nested-floating-actions";
+import NestedOp from "./nested-op";
+import NestedPost from "./nested-post";
+import NestedSortSelector from "./nested-sort-selector";
+import NestedViewHeader from "./nested-view-header";
+
+export default class NestedContextView extends Component {
+ @service currentUser;
+ @service header;
+ @service screenTrack;
+
+ @tracked cloakAbove = 0;
+ @tracked cloakBelow = 0;
+ viewportTracker = new PostStreamViewportTracker();
+ #scrollAttempts = 0;
+ #maxScrollAttempts = 20;
+ #destroyed = false;
+ #nextTimer = null;
+ #retryTimer = null;
+ #highlightTimer = null;
+
+ constructor() {
+ super(...arguments);
+ // Use next() so this runs after RouteScrollManager's next() callback,
+ // which otherwise resets scroll position on route transitions.
+ this.#nextTimer = next(this, this.#scrollToTarget);
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.#destroyed = true;
+ cancel(this.#nextTimer);
+ cancel(this.#retryTimer);
+ clearTimeout(this.#highlightTimer);
+ this.viewportTracker.destroy();
+ }
+
+ get flatViewUrl() {
+ return getURL(`/t/${this.args.topic.slug}/${this.args.topic.id}?flat=1`);
+ }
+
+ #scrollToTarget() {
+ if (this.#destroyed) {
+ return;
+ }
+
+ const postNumber = this.args.targetPostNumber;
+ if (!postNumber) {
+ return;
+ }
+
+ const target = document.querySelector(
+ `.nested-context-view [data-post-number="${postNumber}"]`
+ );
+
+ if (target) {
+ const postEl = target.closest(".nested-post");
+ if (postEl) {
+ postEl.classList.add("nested-post--highlighted");
+ this.#highlightTimer = setTimeout(
+ () => postEl.classList.remove("nested-post--highlighted"),
+ 2000
+ );
+ }
+ target.scrollIntoView({ behavior: "smooth", block: "center" });
+ } else if (this.#scrollAttempts < this.#maxScrollAttempts) {
+ // Element may not be in the DOM yet (async child rendering).
+ // Retry after the next render cycle.
+ this.#scrollAttempts++;
+ this.#retryTimer = schedule("afterRender", this, this.#scrollToTarget);
+ }
+ }
+
+ @action
+ setCloakingBoundaries(above, below) {
+ this.cloakAbove = above;
+ this.cloakBelow = below;
+ }
+
+ <template>
+ <div
+ class="nested-view nested-context-view"
+ {{this.viewportTracker.setup
+ eyeline=false
+ headerOffset=this.header.headerOffset
+ screenTrack=this.screenTrack
+ setCloakingBoundaries=this.setCloakingBoundaries
+ }}
+ >
+ <NestedViewHeader
+ @topic={{@topic}}
+ @editingTopic={{@editingTopic}}
+ @buffered={{@buffered}}
+ @showCategoryChooser={{@showCategoryChooser}}
+ @canEditTags={{@canEditTags}}
+ @minimumRequiredTags={{@minimumRequiredTags}}
+ @finishedEditingTopic={{@finishedEditingTopic}}
+ @cancelEditingTopic={{@cancelEditingTopic}}
+ @topicCategoryChanged={{@topicCategoryChanged}}
+ @topicTagsChanged={{@topicTagsChanged}}
+ @startEditingTopic={{@startEditingTopic}}
+ />
+
+ <NestedOp
+ @post={{@opPost}}
+ @topic={{@topic}}
+ @editPost={{@editPost}}
+ @showHistory={{@showHistory}}
+ @registerPost={{this.viewportTracker.registerPost}}
+ />
+
+ <div class="nested-view__controls">
+ <NestedSortSelector @current={{@sort}} @onChange={{@changeSort}} />
+ {{#if this.currentUser.can_toggle_nested_mode}}
+ <a href={{this.flatViewUrl}} class="nested-view__flat-link">{{i18n
+ "nested_replies.view_as_flat"
+ }}</a>
+ {{/if}}
+ </div>
+
+ <div class="nested-context-view__banner">
+ <span class="nested-context-view__banner-icon">{{icon
+ "nested-thread"
+ }}</span>
+ <span class="nested-context-view__banner-text">{{i18n
+ "nested_replies.context.banner"
+ }}</span>
+ <div class="nested-context-view__nav">
+ <DButton
+ class="btn-default btn-small nested-context-view__full-thread"
+ @action={{@viewFullThread}}
+ @icon="arrow-left"
+ @translatedLabel={{i18n "nested_replies.context.view_full_topic"}}
+ />
+ {{#if (or @contextNoAncestors @ancestorsTruncated)}}
+ <DButton
+ class="btn-default btn-small nested-context-view__parent-context"
+ @action={{@viewParentContext}}
+ @icon="arrow-up"
+ @translatedLabel={{i18n
+ "nested_replies.context.view_parent_context"
+ }}
+ />
+ {{/if}}
+ </div>
+ </div>
+
+ {{#if @contextChain}}
+ <div class="nested-context-view__chain">
+ {{! Use each+key to force full component recreation when the chain root changes,
+ e.g. navigating from context=0 to full ancestor view }}
+ {{#each (array @contextChain) key="post.id" as |chainRoot|}}
+ <NestedPost
+ @post={{chainRoot.post}}
+ @children={{chainRoot.children}}
+ @topic={{@topic}}
+ @depth={{0}}
+ @sort={{@sort}}
+ @replyToPost={{@replyToPost}}
+ @editPost={{@editPost}}
+ @deletePost={{@deletePost}}
+ @recoverPost={{@recoverPost}}
+ @showFlags={{@showFlags}}
+ @showHistory={{@showHistory}}
+ @expansionState={{@expansionState}}
+ @fetchedChildrenCache={{@fetchedChildrenCache}}
+ @scrollAnchor={{@scrollAnchor}}
+ @registerPost={{this.viewportTracker.registerPost}}
+ @getCloakingData={{this.viewportTracker.getCloakingData}}
+ @cloakAbove={{this.cloakAbove}}
+ @cloakBelow={{this.cloakBelow}}
+ />
+ {{/each}}
+ </div>
+ {{/if}}
+
+ <NestedFloatingActions
+ @topic={{@topic}}
+ @replyAction={{fn @replyToPost @opPost 0}}
+ />
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/app/components/nested-floating-actions.gjs b/frontend/discourse/app/components/nested-floating-actions.gjs
new file mode 100644
index 00000000000..1a745b57541
--- /dev/null
+++ b/frontend/discourse/app/components/nested-floating-actions.gjs
@@ -0,0 +1,67 @@
+import Component from "@glimmer/component";
+import { getOwner } from "@ember/owner";
+import { service } from "@ember/service";
+import DButton from "discourse/components/d-button";
+import PluginOutlet from "discourse/components/plugin-outlet";
+import TopicAdminMenu from "discourse/components/topic-admin-menu";
+import concatClass from "discourse/helpers/concat-class";
+import lazyHash from "discourse/helpers/lazy-hash";
+import TopicNotificationsButton from "discourse/select-kit/components/topic-notifications-button";
+import { i18n } from "discourse-i18n";
+
+export default class NestedFloatingActions extends Component {
+ @service composer;
+ @service currentUser;
+
+ topicController = getOwner(this).lookup("controller:topic");
+ topicRoute = getOwner(this).lookup("route:topic");
+
+ get canCreatePost() {
+ return this.currentUser && this.args.topic?.details?.can_create_post;
+ }
+
+ <template>
+ <div
+ class={{concatClass
+ "nested-view__floating-actions"
+ (if this.composer.visible "--hidden")
+ }}
+ >
+ <PluginOutlet
+ @name="nested-view-floating-actions"
+ @outletArgs={{lazyHash topic=@topic}}
+ />
+
+ {{#if this.currentUser}}
+ <TopicNotificationsButton @topic={{@topic}} @expanded={{false}} />
+ {{/if}}
+
+ <TopicAdminMenu
+ @topic={{@topic}}
+ @toggleMultiSelect={{this.topicController.toggleMultiSelect}}
+ @deleteTopic={{this.topicController.deleteTopic}}
+ @recoverTopic={{this.topicController.recoverTopic}}
+ @toggleClosed={{this.topicController.toggleClosed}}
+ @toggleArchived={{this.topicController.toggleArchived}}
+ @toggleVisibility={{this.topicController.toggleVisibility}}
+ @resetBumpDate={{this.topicController.resetBumpDate}}
+ @convertToPublicTopic={{this.topicController.convertToPublicTopic}}
+ @convertToPrivateMessage={{this.topicController.convertToPrivateMessage}}
+ @showTopicSlowModeUpdate={{this.topicRoute.showTopicSlowModeUpdate}}
+ @showTopicTimerModal={{this.topicRoute.showTopicTimerModal}}
+ @showFeatureTopic={{this.topicRoute.showFeatureTopic}}
+ @showChangeTimestamp={{this.topicRoute.showChangeTimestamp}}
+ />
+
+ {{#if this.canCreatePost}}
+ <DButton
+ class="btn-primary nested-view__floating-reply"
+ @action={{@replyAction}}
+ @icon="reply"
+ @label="topic.reply.title"
+ title={{i18n "topic.reply.help"}}
+ />
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/app/components/nested-op.gjs b/frontend/discourse/app/components/nested-op.gjs
new file mode 100644
index 00000000000..19c09a77c7e
--- /dev/null
+++ b/frontend/discourse/app/components/nested-op.gjs
@@ -0,0 +1,161 @@
+import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import { getOwner } from "@ember/owner";
+import { service } from "@ember/service";
+import ShareTopicModal from "discourse/components/modal/share-topic";
+import PluginOutlet from "discourse/components/plugin-outlet";
+import PostAvatar from "discourse/components/post/avatar";
+import PostCookedHtml from "discourse/components/post/cooked-html";
+import PostLinks from "discourse/components/post/links";
+import PostMenu from "discourse/components/post/menu";
+import PostMetaData from "discourse/components/post/meta-data";
+import lazyHash from "discourse/helpers/lazy-hash";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { isTesting } from "discourse/lib/environment";
+import { getAbsoluteURL } from "discourse/lib/get-url";
+import nestedPostUrl from "discourse/lib/nested-post-url";
+import postActionFeedback from "discourse/lib/post-action-feedback";
+import { nativeShare } from "discourse/lib/pwa-utils";
+import { clipboardCopy } from "discourse/lib/utilities";
+
+export default class NestedOp extends Component {
+ @service capabilities;
+ @service currentUser;
+ @service modal;
+ @service site;
+
+ get nestedShareUrl() {
+ return nestedPostUrl(this.args.topic, this.args.post.post_number);
+ }
+
+ @action
+ copyLink() {
+ if (this.site.mobileView) {
+ return this.share();
+ }
+
+ const post = this.args.post;
+
+ let actionCallback = () =>
+ clipboardCopy(getAbsoluteURL(this.nestedShareUrl));
+
+ if (isTesting()) {
+ actionCallback = () => {};
+ }
+
+ postActionFeedback({
+ postId: post.id,
+ actionClass: "post-action-menu__copy-link",
+ messageKey: "post.controls.link_copied",
+ actionCallback,
+ errorCallback: () => this.share(),
+ });
+ }
+
+ @action
+ async share() {
+ const post = this.args.post;
+ const topic = this.args.topic;
+
+ try {
+ await nativeShare(this.capabilities, {
+ url: getAbsoluteURL(this.nestedShareUrl),
+ });
+ } catch {
+ this.modal.show(ShareTopicModal, {
+ model: { category: topic.category, topic, post },
+ });
+ }
+ }
+
+ @action
+ async toggleLike() {
+ const post = this.args.post;
+ const likeAction = post.likeAction;
+ if (likeAction?.canToggle) {
+ try {
+ await likeAction.togglePromise(post);
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+ }
+
+ get canCreatePost() {
+ return this.currentUser && this.args.topic?.details?.can_create_post;
+ }
+
+ @action
+ showLogin() {
+ getOwner(this).lookup("route:application").send("showLogin");
+ }
+
+ <template>
+ {{#if @post}}
+ <div class="nested-view__op">
+ {{#let (lazyHash post=@post) as |postOutletArgs|}}
+ <PluginOutlet @name="post-article" @outletArgs={{postOutletArgs}}>
+ <article
+ class="nested-view__op-article boxed"
+ data-post-id={{@post.id}}
+ data-post-number={{@post.post_number}}
+ {{@registerPost @post}}
+ >
+ <PluginOutlet
+ @name="post-article-content"
+ @outletArgs={{postOutletArgs}}
+ >
+ <div class="nested-view__op-row">
+ <PostAvatar @post={{@post}} />
+ <div class="nested-view__op-body">
+ <PluginOutlet
+ @name="post-metadata"
+ @outletArgs={{postOutletArgs}}
+ >
+ <PostMetaData
+ @post={{@post}}
+ @editPost={{fn @editPost @post}}
+ @showHistory={{fn @showHistory @post}}
+ />
+ </PluginOutlet>
+ <div class="nested-view__op-content">
+ <PluginOutlet
+ @name="post-content-cooked-html"
+ @outletArgs={{postOutletArgs}}
+ >
+ <PostCookedHtml @post={{@post}} />
+ </PluginOutlet>
+ </div>
+ {{#if @showPostMenu}}
+ <section
+ class="nested-view__op-menu post-menu-area clearfix"
+ >
+ <PostMenu
+ @post={{@post}}
+ @canCreatePost={{this.canCreatePost}}
+ @copyLink={{this.copyLink}}
+ @replyToPost={{@replyToPost}}
+ @editPost={{fn @editPost @post}}
+ @share={{this.share}}
+ @toggleLike={{this.toggleLike}}
+ @showLogin={{this.showLogin}}
+ />
+ </section>
+ {{/if}}
+ <PluginOutlet
+ @name="post-links"
+ @outletArgs={{postOutletArgs}}
+ >
+ <PostLinks @post={{@post}} />
+ </PluginOutlet>
+ </div>
+ </div>
+ </PluginOutlet>
+ </article>
+ </PluginOutlet>
+ {{/let}}
+ </div>
+ {{/if}}
+ </template>
+}
diff --git a/frontend/discourse/app/components/nested-post-children.gjs b/frontend/discourse/app/components/nested-post-children.gjs
new file mode 100644
index 00000000000..748988ab1b5
--- /dev/null
+++ b/frontend/discourse/app/components/nested-post-children.gjs
@@ -0,0 +1,252 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";
+import DButton from "discourse/components/d-button";
+import concatClass from "discourse/helpers/concat-class";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { i18n } from "discourse-i18n";
+import processNode from "../lib/process-node";
+import NestedPost from "./nested-post";
+
+export default class NestedPostChildren extends Component {
+ @service appEvents;
+ @service store;
+ @service siteSettings;
+
+ @tracked childNodes = [];
+ @tracked loading = false;
+ @tracked page = 0;
+ @tracked hasMore = false;
+ @tracked loadingMore = false;
+ @tracked loaded = false;
+
+ // Tracks whether we've fetched from the server yet (vs only having preloaded data)
+ _fetchedFromServer = false;
+
+ constructor() {
+ super(...arguments);
+ this.appEvents.on(
+ "nested-replies:child-created",
+ this,
+ this._onChildCreated
+ );
+
+ const cached = this.args.fetchedChildrenCache?.get(
+ this.args.parentPostNumber
+ );
+ if (cached) {
+ this.childNodes = cached.childNodes;
+ this.page = cached.page;
+ this.hasMore = cached.hasMore;
+ this.loaded = true;
+ this._fetchedFromServer = cached.fetchedFromServer;
+ return;
+ }
+
+ if (this.args.preloadedChildren?.length > 0) {
+ this.childNodes = this.args.preloadedChildren;
+ this.loaded = true;
+ // When cap is ON at last level, the children endpoint returns flattened
+ // descendants, so use total_descendant_count for the "more" threshold.
+ const flatten =
+ this.siteSettings.nested_replies_cap_nesting_depth &&
+ this.childDepth >= this.siteSettings.nested_replies_max_depth;
+ const expectedCount = flatten
+ ? this.args.totalDescendantCount || this.args.directReplyCount || 0
+ : this.args.directReplyCount || 0;
+ this.hasMore = expectedCount > this.args.preloadedChildren.length;
+ } else if (this.args.directReplyCount > 0) {
+ this.loadChildren();
+ }
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.appEvents.off(
+ "nested-replies:child-created",
+ this,
+ this._onChildCreated
+ );
+ this._reportToCache();
+ }
+
+ _reportToCache() {
+ if (!this.loaded || !this.args.fetchedChildrenCache) {
+ return;
+ }
+ this.args.fetchedChildrenCache.set(this.args.parentPostNumber, {
+ childNodes: this.childNodes,
+ page: this.page,
+ hasMore: this.hasMore,
+ fetchedFromServer: this._fetchedFromServer,
+ });
+ }
+
+ _onChildCreated({ post, parentPostNumber }) {
+ if (parentPostNumber !== this.args.parentPostNumber) {
+ return;
+ }
+
+ const alreadyExists = this.childNodes.some(
+ (n) => n.post.id === post.id || n.post.post_number === post.post_number
+ );
+ if (alreadyExists) {
+ return;
+ }
+
+ this.childNodes = [{ post, children: [] }, ...this.childNodes];
+ this.loaded = true;
+ this._reportToCache();
+ }
+
+ get childDepth() {
+ return this.args.depth + 1;
+ }
+
+ get remainingCount() {
+ const flatten =
+ this.siteSettings.nested_replies_cap_nesting_depth &&
+ this.childDepth >= this.siteSettings.nested_replies_max_depth;
+ const total = flatten
+ ? this.args.totalDescendantCount || this.args.directReplyCount || 0
+ : this.args.directReplyCount || 0;
+ return Math.max(total - this.childNodes.length, 0);
+ }
+
+ get loadMoreLabel() {
+ const count = this.remainingCount;
+ if (count > 0) {
+ return i18n("nested_replies.load_more_children", { count });
+ }
+ return i18n("nested_replies.load_more_children_generic");
+ }
+
+ async loadChildren() {
+ this.loading = true;
+ try {
+ const data = await ajax(
+ `/n/${this.args.topic.slug}/${this.args.topic.id}/children/${this.args.parentPostNumber}.json?sort=${this.args.sort || "top"}&depth=${this.childDepth}`
+ );
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+ this.childNodes = (data.children || []).map((child) =>
+ this._processNode(child)
+ );
+ this.page = data.page;
+ this.hasMore = data.has_more || false;
+ this.loaded = true;
+ this._fetchedFromServer = true;
+ this._reportToCache();
+ } catch (e) {
+ if (!(this.isDestroying || this.isDestroyed)) {
+ popupAjaxError(e);
+ }
+ } finally {
+ if (!(this.isDestroying || this.isDestroyed)) {
+ this.loading = false;
+ }
+ }
+ }
+
+ @action
+ async loadMore() {
+ if (this.loadingMore || !this.hasMore) {
+ return;
+ }
+
+ this.loadingMore = true;
+ try {
+ // First server fetch after preloaded data: get page 0 and merge
+ // to preserve expanded state on already-loaded nodes.
+ // Subsequent fetches: normal pagination.
+ const nextPage = this._fetchedFromServer ? this.page + 1 : 0;
+ const data = await ajax(
+ `/n/${this.args.topic.slug}/${this.args.topic.id}/children/${this.args.parentPostNumber}.json?page=${nextPage}&sort=${this.args.sort || "top"}&depth=${this.childDepth}`
+ );
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+ const newNodes = (data.children || []).map((child) =>
+ this._processNode(child)
+ );
+
+ if (!this._fetchedFromServer) {
+ // Merge: keep preloaded children (may have expanded subtrees),
+ // append only siblings not already present.
+ const existing = new Set(
+ this.childNodes.map((n) => n.post.post_number)
+ );
+ const additional = newNodes.filter(
+ (n) => !existing.has(n.post.post_number)
+ );
+ this.childNodes = [...this.childNodes, ...additional];
+ this._fetchedFromServer = true;
+ } else {
+ this.childNodes = [...this.childNodes, ...newNodes];
+ }
+
+ this.page = data.page;
+ this.hasMore = data.has_more || false;
+ this._reportToCache();
+ } catch (e) {
+ if (!(this.isDestroying || this.isDestroyed)) {
+ popupAjaxError(e);
+ }
+ } finally {
+ if (!(this.isDestroying || this.isDestroyed)) {
+ this.loadingMore = false;
+ }
+ }
+ }
+
+ _processNode(nodeData) {
+ return processNode(this.store, this.args.topic, nodeData);
+ }
+
+ <template>
+ <div class="nested-post-children">
+ <ConditionalLoadingSpinner @condition={{this.loading}}>
+ {{#each this.childNodes key="post.id" as |node|}}
+ <NestedPost
+ @post={{node.post}}
+ @children={{node.children}}
+ @topic={{@topic}}
+ @depth={{this.childDepth}}
+ @sort={{@sort}}
+ @replyToPost={{@replyToPost}}
+ @editPost={{@editPost}}
+ @deletePost={{@deletePost}}
+ @recoverPost={{@recoverPost}}
+ @showFlags={{@showFlags}}
+ @showHistory={{@showHistory}}
+ @collapseParent={{@collapseParent}}
+ @highlightParentLine={{@highlightParentLine}}
+ @unhighlightParentLine={{@unhighlightParentLine}}
+ @parentLineHighlighted={{@parentLineHighlighted}}
+ @expansionState={{@expansionState}}
+ @fetchedChildrenCache={{@fetchedChildrenCache}}
+ @scrollAnchor={{@scrollAnchor}}
+ @registerPost={{@registerPost}}
+ />
+ {{/each}}
+
+ {{#if this.hasMore}}
+ <DButton
+ class={{concatClass
+ "btn-flat"
+ "nested-post-children__load-more"
+ (if @parentLineHighlighted "--parent-line-highlighted")
+ }}
+ @action={{this.loadMore}}
+ @disabled={{this.loadingMore}}
+ @translatedLabel={{this.loadMoreLabel}}
+ />
+ {{/if}}
+ </ConditionalLoadingSpinner>
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/app/components/nested-post.gjs b/frontend/discourse/app/components/nested-post.gjs
new file mode 100644
index 00000000000..7fa7a856e5f
--- /dev/null
+++ b/frontend/discourse/app/components/nested-post.gjs
@@ -0,0 +1,541 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { getOwner } from "@ember/owner";
+import { service } from "@ember/service";
+import { modifier } from "ember-modifier";
+import DButton from "discourse/components/d-button";
+import ShareTopicModal from "discourse/components/modal/share-topic";
+import NestedRepliesExpandButton from "discourse/components/nested-replies-expand-button";
+import PluginOutlet from "discourse/components/plugin-outlet";
+import PostAvatar from "discourse/components/post/avatar";
+import PostCookedHtml from "discourse/components/post/cooked-html";
+import PostLinks from "discourse/components/post/links";
+import PostMenu from "discourse/components/post/menu";
+import PostMetaData from "discourse/components/post/meta-data";
+import concatClass from "discourse/helpers/concat-class";
+import icon from "discourse/helpers/d-icon";
+import lazyHash from "discourse/helpers/lazy-hash";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { isTesting } from "discourse/lib/environment";
+import getURL, { getAbsoluteURL } from "discourse/lib/get-url";
+import postActionFeedback from "discourse/lib/post-action-feedback";
+import { nativeShare } from "discourse/lib/pwa-utils";
+import { clipboardCopy } from "discourse/lib/utilities";
+import { and, not, or } from "discourse/truth-helpers";
+import { i18n } from "discourse-i18n";
+import nestedPostUrl from "../lib/nested-post-url";
+import NestedPostChildren from "./nested-post-children";
+
+export default class NestedPost extends Component {
+ @service appEvents;
+ @service capabilities;
+ @service currentUser;
+ @service modal;
+ @service site;
+ @service siteSettings;
+
+ @tracked expanded;
+ @tracked lineHighlighted = false;
+ @tracked collapsed;
+ @tracked showDeletedContent = false;
+
+ restoreScroll = modifier((element) => {
+ const anchor = this.args.scrollAnchor;
+ if (anchor?.postNumber !== this.args.post.post_number) {
+ return;
+ }
+ const rect = element.getBoundingClientRect();
+ window.scrollTo(0, window.scrollY + rect.top - anchor.offsetFromTop);
+ });
+
+ @tracked _childWasCreated = false;
+
+ constructor() {
+ super(...arguments);
+
+ const cached = this.args.expansionState?.get(this.args.post.post_number);
+ if (cached !== undefined) {
+ this.expanded = cached.expanded;
+ this.collapsed = cached.collapsed;
+ } else {
+ this.expanded =
+ (this.args.children?.length ?? 0) > 0 ||
+ this.args.post.deleted_post_placeholder === true;
+ this.collapsed = false;
+ }
+
+ this.appEvents.on(
+ "nested-replies:child-created",
+ this,
+ this._onChildCreated
+ );
+ this.appEvents.trigger("nested-replies:post-registered", this.args.post);
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.appEvents.off(
+ "nested-replies:child-created",
+ this,
+ this._onChildCreated
+ );
+ this.appEvents.trigger("nested-replies:post-unregistered", this.args.post);
+ }
+
+ _onChildCreated({ parentPostNumber }) {
+ if (parentPostNumber !== this.args.post.post_number) {
+ return;
+ }
+
+ const post = this.args.post;
+ post.set("direct_reply_count", (post.direct_reply_count || 0) + 1);
+ post.set("total_descendant_count", (post.total_descendant_count || 0) + 1);
+ this._childWasCreated = true;
+
+ if (!this.expanded) {
+ this.expanded = true;
+ this.collapsed = false;
+ this.args.expansionState?.set(this.args.post.post_number, {
+ expanded: true,
+ collapsed: false,
+ });
+ }
+ }
+
+ get isRoot() {
+ return this.args.depth === 0;
+ }
+
+ get cloakingData() {
+ if (!this.isRoot || !this.args.getCloakingData) {
+ return { active: false };
+ }
+ return this.args.getCloakingData(this.args.post, {
+ above: this.args.cloakAbove,
+ below: this.args.cloakBelow,
+ });
+ }
+
+ get depthClass() {
+ return `--depth-${this.args.depth}`;
+ }
+
+ get isMobile() {
+ return this.site.mobileView;
+ }
+
+ get canCreatePost() {
+ return this.currentUser && this.args.topic?.details?.can_create_post;
+ }
+
+ get hasReplies() {
+ return (
+ this._childWasCreated ||
+ (this.args.post.direct_reply_count || 0) > 0 ||
+ (this.args.children?.length ?? 0) > 0
+ );
+ }
+
+ get replyCount() {
+ const count =
+ this.args.post.total_descendant_count ||
+ this.args.post.direct_reply_count ||
+ this.args.children?.length ||
+ 0;
+ return this._childWasCreated ? Math.max(count, 1) : count;
+ }
+
+ get atMaxDepth() {
+ return this.args.depth >= this.siteSettings.nested_replies_max_depth;
+ }
+
+ get isDeletedPlaceholder() {
+ return this.args.post.deleted_post_placeholder === true;
+ }
+
+ get showContinueThread() {
+ return (
+ this.atMaxDepth &&
+ this.hasReplies &&
+ !this.siteSettings.nested_replies_cap_nesting_depth
+ );
+ }
+
+ get showDepthLine() {
+ return this.hasReplies && (!this.atMaxDepth || this.showContinueThread);
+ }
+
+ get showExpandRepliesButton() {
+ return this.hasReplies && !this.expanded && !this.atMaxDepth;
+ }
+
+ get isOP() {
+ return this.args.post.user_id === this.args.topic?.user_id;
+ }
+
+ get contextUrl() {
+ return getURL(
+ `/n/${this.args.topic.slug}/${this.args.topic.id}/${this.args.post.post_number}?context=0`
+ );
+ }
+
+ get expandLabel() {
+ return i18n("nested_replies.collapsed_replies", {
+ count: this.replyCount,
+ });
+ }
+
+ @action
+ toggleExpanded() {
+ if (this.expanded) {
+ this.expanded = false;
+ this.collapsed = true;
+ this.lineHighlighted = false;
+ } else {
+ this.expanded = true;
+ this.collapsed = false;
+ }
+ this.args.expansionState?.set(this.args.post.post_number, {
+ expanded: this.expanded,
+ collapsed: this.collapsed,
+ });
+ }
+
+ @action
+ toggleDeletedContent() {
+ this.showDeletedContent = !this.showDeletedContent;
+ }
+
+ @action
+ highlightLine() {
+ if (!this.site.mobileView) {
+ this.lineHighlighted = true;
+ }
+ }
+
+ @action
+ unhighlightLine() {
+ this.lineHighlighted = false;
+ }
+
+ get nestedShareUrl() {
+ return nestedPostUrl(this.args.topic, this.args.post.post_number);
+ }
+
+ @action
+ copyLink() {
+ if (this.site.mobileView) {
+ return this.share();
+ }
+
+ const post = this.args.post;
+ const postId = post.id;
+
+ let actionCallback = () =>
+ clipboardCopy(getAbsoluteURL(this.nestedShareUrl));
+
+ if (isTesting()) {
+ actionCallback = () => {};
+ }
+
+ postActionFeedback({
+ postId,
+ actionClass: "post-action-menu__copy-link",
+ messageKey: "post.controls.link_copied",
+ actionCallback,
+ errorCallback: () => this.share(),
+ });
+ }
+
+ @action
+ async share() {
+ const post = this.args.post;
+
+ try {
+ await nativeShare(this.capabilities, {
+ url: getAbsoluteURL(this.nestedShareUrl),
+ });
+ } catch {
+ const topic = this.args.topic;
+ this.modal.show(ShareTopicModal, {
+ model: { category: topic.category, topic, post },
+ });
+ }
+ }
+
+ @action
+ async toggleLike() {
+ const post = this.args.post;
+ const likeAction = post.likeAction;
+
+ if (likeAction?.canToggle) {
+ try {
+ await likeAction.togglePromise(post);
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+ }
+
+ @action
+ showLogin() {
+ getOwner(this).lookup("route:application").send("showLogin");
+ }
+
+ <template>
+ <div
+ class={{concatClass
+ "nested-post"
+ this.depthClass
+ (if @parentLineHighlighted "--parent-line-highlighted")
+ (if this.collapsed "nested-post--collapsed")
+ (if @isPinned "nested-post--pinned")
+ (if @post.isWhisper "nested-post--whisper")
+ (if (or @post.deleted @post.user_deleted) "nested-post--deleted")
+ (if this.cloakingData.active "nested-post--cloaked")
+ }}
+ style={{this.cloakingData.style}}
+ {{this.restoreScroll}}
+ {{! 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)}}
+ >
+ {{#unless this.cloakingData.active}}
+ {{#if @collapseParent}}
+ <button
+ type="button"
+ class="nested-post__parent-line-btn"
+ {{on "click" @collapseParent}}
+ {{on "mouseenter" @highlightParentLine}}
+ {{on "mouseleave" @unhighlightParentLine}}
+ aria-label={{i18n "nested_replies.collapse_parent"}}
+ ></button>
+ {{/if}}
+ <div class="nested-post__gutter">
+ {{#unless this.isMobile}}
+ {{#if this.isDeletedPlaceholder}}
+ <div class="nested-post__deleted-avatar-placeholder">
+ {{icon "trash-can"}}
+ </div>
+ {{else}}
+ <PostAvatar @post={{@post}} @size="small" />
+ {{/if}}
+ {{/unless}}
+ {{#if (and this.showDepthLine (not this.collapsed))}}
+ <button
+ type="button"
+ class={{concatClass
+ "nested-post__depth-line"
+ (if this.lineHighlighted "nested-post__depth-line--highlighted")
+ (unless this.expanded "nested-post__depth-line--collapsed")
+ }}
+ {{on "click" this.toggleExpanded}}
+ {{on "mouseenter" this.highlightLine}}
+ {{on "mouseleave" this.unhighlightLine}}
+ aria-label={{if
+ this.expanded
+ (i18n "nested_replies.collapse")
+ this.expandLabel
+ }}
+ >
+ {{#if this.expanded}}
+ <span class="nested-post__depth-line-icon">
+ {{icon "nested-circle-minus"}}
+ </span>
+ {{/if}}
+ </button>
+ {{/if}}
+ </div>
+ <div class="nested-post__main">
+ {{#if this.collapsed}}
+ <button
+ type="button"
+ class="nested-post__collapsed-bar"
+ data-post-number={{@post.post_number}}
+ {{on "click" this.toggleExpanded}}
+ >
+ {{icon "nested-circle-plus"}}
+ {{#if this.isDeletedPlaceholder}}
+ <span class="nested-post__collapsed-username">{{i18n
+ "nested_replies.deleted_post_placeholder"
+ }}</span>
+ {{else}}
+ <span
+ class="nested-post__collapsed-username"
+ >{{@post.username}}</span>
+ {{/if}}
+ <span
+ class="nested-post__collapsed-separator"
+ aria-hidden="true"
+ >&middot;</span>
+ <span
+ class="nested-post__collapsed-reply-count"
+ >{{this.expandLabel}}</span>
+ </button>
+ {{else if this.isDeletedPlaceholder}}
+ <div
+ class="nested-post__deleted-placeholder"
+ data-post-number={{@post.post_number}}
+ >
+ <div class="nested-post__deleted-actions">
+ <span class="nested-post__deleted-label">{{i18n
+ "nested_replies.deleted_post_placeholder"
+ }}</span>
+ {{#if this.currentUser.staff}}
+ <DButton
+ class="btn-flat toggle-deleted-content"
+ @action={{this.toggleDeletedContent}}
+ @icon={{if
+ this.showDeletedContent
+ "far-eye-slash"
+ "far-eye"
+ }}
+ @ariaLabel="post.controls.view_deleted"
+ />
+ {{/if}}
+ {{#if @post.can_recover}}
+ <DButton
+ class="btn-flat recover"
+ @action={{fn @recoverPost @post}}
+ @icon="arrow-rotate-left"
+ @ariaLabel="post.controls.undelete"
+ />
+ {{/if}}
+ </div>
+ {{#if this.showDeletedContent}}
+ <div class="nested-post__deleted-content">
+ <div class="nested-post__deleted-content-header">
+ <PostAvatar @post={{@post}} @size="small" />
+ <PostMetaData @post={{@post}} />
+ </div>
+ <PostCookedHtml @post={{@post}} />
+ </div>
+ {{/if}}
+ </div>
+ {{else}}
+ {{#let (lazyHash post=@post) as |postOutletArgs|}}
+ <PluginOutlet @name="post-article" @outletArgs={{postOutletArgs}}>
+ <article
+ class="nested-post__article boxed"
+ data-post-id={{@post.id}}
+ data-post-number={{@post.post_number}}
+ {{@registerPost @post trackOnly=true}}
+ >
+ <PluginOutlet
+ @name="post-article-content"
+ @outletArgs={{postOutletArgs}}
+ >
+ <div class="nested-post__header">
+ {{#if this.isMobile}}
+ <PostAvatar @post={{@post}} @size="small" />
+ {{/if}}
+ <PluginOutlet
+ @name="post-metadata"
+ @outletArgs={{postOutletArgs}}
+ >
+ <PostMetaData
+ @post={{@post}}
+ @editPost={{fn @editPost @post}}
+ @showHistory={{fn @showHistory @post}}
+ />
+ </PluginOutlet>
+ {{#if this.isOP}}
+ <span class="nested-post__op-badge">{{i18n
+ "nested_replies.op_badge"
+ }}</span>
+ {{/if}}
+ {{#if @isPinned}}
+ <span class="nested-post__pinned-badge">{{i18n
+ "nested_replies.pinned_reply"
+ }}</span>
+ {{/if}}
+ </div>
+ <div class="nested-post__content">
+ <PluginOutlet
+ @name="post-content-cooked-html"
+ @outletArgs={{postOutletArgs}}
+ >
+ <PostCookedHtml @post={{@post}} />
+ </PluginOutlet>
+ </div>
+ <section class="nested-post__menu post-menu-area clearfix">
+ <PostMenu
+ @post={{@post}}
+ @canCreatePost={{this.canCreatePost}}
+ @copyLink={{this.copyLink}}
+ @deletePost={{fn @deletePost @post}}
+ @editPost={{fn @editPost @post}}
+ @recoverPost={{fn @recoverPost @post}}
+ @replyToPost={{fn @replyToPost @post @depth}}
+ @share={{this.share}}
+ @showFlags={{fn @showFlags @post}}
+ @toggleLike={{this.toggleLike}}
+ @toggleReplies={{unless
+ this.atMaxDepth
+ this.toggleExpanded
+ }}
+ @repliesShown={{if this.atMaxDepth true this.expanded}}
+ @showLogin={{this.showLogin}}
+ />
+ </section>
+ {{#if this.showExpandRepliesButton}}
+ <NestedRepliesExpandButton
+ @replyCount={{this.replyCount}}
+ @onClick={{this.toggleExpanded}}
+ />
+ {{/if}}
+ <PluginOutlet
+ @name="post-links"
+ @outletArgs={{postOutletArgs}}
+ >
+ <PostLinks @post={{@post}} />
+ </PluginOutlet>
+ </PluginOutlet>
+ {{#if this.showContinueThread}}
+ <div class="nested-post__controls">
+ <a
+ href={{this.contextUrl}}
+ class="nested-post__continue-link"
+ >
+ {{i18n "nested_replies.continue_thread"}}
+ </a>
+ </div>
+ {{/if}}
+ </article>
+ </PluginOutlet>
+ {{/let}}
+ {{/if}}
+
+ {{#if (and this.expanded (not this.collapsed) (not this.atMaxDepth))}}
+ <NestedPostChildren
+ @topic={{@topic}}
+ @parentPostNumber={{@post.post_number}}
+ @preloadedChildren={{@children}}
+ @directReplyCount={{@post.direct_reply_count}}
+ @totalDescendantCount={{@post.total_descendant_count}}
+ @depth={{@depth}}
+ @sort={{@sort}}
+ @replyToPost={{@replyToPost}}
+ @editPost={{@editPost}}
+ @deletePost={{@deletePost}}
+ @recoverPost={{@recoverPost}}
+ @showFlags={{@showFlags}}
+ @showHistory={{@showHistory}}
+ @collapseParent={{this.toggleExpanded}}
+ @highlightParentLine={{this.highlightLine}}
+ @unhighlightParentLine={{this.unhighlightLine}}
+ @parentLineHighlighted={{this.lineHighlighted}}
+ @expansionState={{@expansionState}}
+ @fetchedChildrenCache={{@fetchedChildrenCache}}
+ @scrollAnchor={{@scrollAnchor}}
+ @registerPost={{@registerPost}}
+ />
+ {{/if}}
+ </div>
+ {{/unless}}
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/app/components/nested-replies-expand-button.gjs b/frontend/discourse/app/components/nested-replies-expand-button.gjs
new file mode 100644
index 00000000000..e589d454f00
--- /dev/null
+++ b/frontend/discourse/app/components/nested-replies-expand-button.gjs
@@ -0,0 +1,21 @@
+import Component from "@glimmer/component";
+import DButton from "discourse/components/d-button";
+import { i18n } from "discourse-i18n";
+
+export default class NestedRepliesExpandButton extends Component {
+ get label() {
+ return i18n("nested_replies.collapsed_replies", {
+ count: this.args.replyCount,
+ });
+ }
+
+ <template>
+ <DButton
+ class="nested-post__expand-replies btn-flat"
+ ...attributes
+ @action={{@onClick}}
+ @icon="nested-circle-plus"
+ @translatedLabel={{this.label}}
+ />
+ </template>
+}
diff --git a/frontend/discourse/app/components/nested-sort-selector.gjs b/frontend/discourse/app/components/nested-sort-selector.gjs
new file mode 100644
index 00000000000..57abf48f98c
--- /dev/null
+++ b/frontend/discourse/app/components/nested-sort-selector.gjs
@@ -0,0 +1,46 @@
+import { fn } from "@ember/helper";
+import DButton from "discourse/components/d-button";
+import concatClass from "discourse/helpers/concat-class";
+import { eq } from "discourse/truth-helpers";
+import { i18n } from "discourse-i18n";
+
+const NestedSortSelector = <template>
+ <div
+ class="nested-sort-selector"
+ role="group"
+ aria-label={{i18n "nested_replies.sort.label"}}
+ >
+ <span class="nested-sort-selector__label">{{i18n
+ "nested_replies.sort.label"
+ }}</span>
+ <DButton
+ class={{concatClass
+ "btn-flat nested-sort-selector__option"
+ (if (eq @current "top") "nested-sort-selector__option--active")
+ }}
+ aria-pressed={{if (eq @current "top") "true" "false"}}
+ @action={{fn @onChange "top"}}
+ @translatedLabel={{i18n "nested_replies.sort.top"}}
+ />
+ <DButton
+ class={{concatClass
+ "btn-flat nested-sort-selector__option"
+ (if (eq @current "new") "nested-sort-selector__option--active")
+ }}
+ aria-pressed={{if (eq @current "new") "true" "false"}}
+ @action={{fn @onChange "new"}}
+ @translatedLabel={{i18n "nested_replies.sort.new"}}
+ />
+ <DButton
+ class={{concatClass
+ "btn-flat nested-sort-selector__option"
+ (if (eq @current "old") "nested-sort-selector__option--active")
+ }}
+ aria-pressed={{if (eq @current "old") "true" "false"}}
+ @action={{fn @onChange "old"}}
+ @translatedLabel={{i18n "nested_replies.sort.old"}}
+ />
+ </div>
+</template>;
+
+export default NestedSortSelector;
diff --git a/frontend/discourse/app/components/nested-view-header.gjs b/frontend/discourse/app/components/nested-view-header.gjs
new file mode 100644
index 00000000000..2942ec51158
--- /dev/null
+++ b/frontend/discourse/app/components/nested-view-header.gjs
@@ -0,0 +1,55 @@
+import { on } from "@ember/modifier";
+import { trustHTML } from "@ember/template";
+import PluginOutlet from "discourse/components/plugin-outlet";
+import TopicCategory from "discourse/components/topic-category";
+import TopicMetadata from "discourse/components/topic-metadata";
+import TopicTitleEditor from "discourse/components/topic-title-editor";
+import icon from "discourse/helpers/d-icon";
+import lazyHash from "discourse/helpers/lazy-hash";
+
+<template>
+ <div class="nested-view__header">
+ {{#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">
+ <a
+ href={{@topic.url}}
+ {{on "click" @startEditingTopic}}
+ class="fancy-title"
+ >
+ {{trustHTML @topic.fancyTitle~}}
+ {{~#if @topic.details.can_edit~}}
+ <span class="edit-topic__wrapper">
+ {{icon "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-view.gjs b/frontend/discourse/app/components/nested-view.gjs
new file mode 100644
index 00000000000..55f3dccf109
--- /dev/null
+++ b/frontend/discourse/app/components/nested-view.gjs
@@ -0,0 +1,185 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";
+import DButton from "discourse/components/d-button";
+import LoadMore from "discourse/components/load-more";
+import PluginOutlet from "discourse/components/plugin-outlet";
+import TopicMap from "discourse/components/topic-map";
+import lazyHash from "discourse/helpers/lazy-hash";
+import getURL from "discourse/lib/get-url";
+import PostStreamViewportTracker from "discourse/modifiers/post-stream-viewport-tracker";
+import { gt, includes } from "discourse/truth-helpers";
+import { i18n } from "discourse-i18n";
+import NestedFloatingActions from "./nested-floating-actions";
+import NestedOp from "./nested-op";
+import NestedPost from "./nested-post";
+import NestedSortSelector from "./nested-sort-selector";
+import NestedViewHeader from "./nested-view-header";
+
+export default class NestedView extends Component {
+ @service currentUser;
+ @service header;
+ @service screenTrack;
+
+ @tracked cloakAbove = 0;
+ @tracked cloakBelow = 0;
+ viewportTracker = new PostStreamViewportTracker();
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.viewportTracker.destroy();
+ }
+
+ get flatViewUrl() {
+ return getURL(`/t/${this.args.topic.slug}/${this.args.topic.id}?flat=1`);
+ }
+
+ @action
+ setCloakingBoundaries(above, below) {
+ this.cloakAbove = above;
+ this.cloakBelow = below;
+ }
+
+ <template>
+ <div
+ class="nested-view"
+ {{this.viewportTracker.setup
+ eyeline=false
+ headerOffset=this.header.headerOffset
+ screenTrack=this.screenTrack
+ setCloakingBoundaries=this.setCloakingBoundaries
+ }}
+ >
+ <NestedViewHeader
+ @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}}
+ @showPostMenu={{true}}
+ @registerPost={{this.viewportTracker.registerPost}}
+ />
+
+ <div class="nested-view__topic-map topic-map">
+ <TopicMap
+ @model={{@topic}}
+ @topicDetails={{@topic.details}}
+ @showPMMap={{@topic.isPrivateMessage}}
+ />
+ </div>
+
+ <div class="nested-view__controls">
+ <NestedSortSelector @current={{@sort}} @onChange={{@changeSort}} />
+ {{#if this.currentUser.can_toggle_nested_mode}}
+ <a href={{this.flatViewUrl}} class="nested-view__flat-link">{{i18n
+ "nested_replies.view_as_flat"
+ }}</a>
+ {{/if}}
+ </div>
+
+ {{#if (gt @newRootPostCount 0)}}
+ <div class="nested-view__new-replies">
+ <DButton
+ class="btn-primary nested-view__new-replies-btn"
+ @action={{@loadNewRoots}}
+ @translatedLabel={{i18n
+ "nested_replies.new_replies"
+ count=@newRootPostCount
+ }}
+ />
+ </div>
+ {{/if}}
+
+ <div class="nested-view__roots">
+ {{#each @rootNodes key="post.id" as |node|}}
+ <NestedPost
+ @post={{node.post}}
+ @children={{node.children}}
+ @topic={{@topic}}
+ @depth={{0}}
+ @sort={{@sort}}
+ @isPinned={{includes @pinnedPostIds node.post.id}}
+ @replyToPost={{@replyToPost}}
+ @editPost={{@editPost}}
+ @deletePost={{@deletePost}}
+ @recoverPost={{@recoverPost}}
+ @showFlags={{@showFlags}}
+ @showHistory={{@showHistory}}
+ @expansionState={{@expansionState}}
+ @fetchedChildrenCache={{@fetchedChildrenCache}}
+ @scrollAnchor={{@scrollAnchor}}
+ @registerPost={{this.viewportTracker.registerPost}}
+ @getCloakingData={{this.viewportTracker.getCloakingData}}
+ @cloakAbove={{this.cloakAbove}}
+ @cloakBelow={{this.cloakBelow}}
+ />
+ {{else}}
+ <div class="nested-view__empty">
+ {{i18n "nested_replies.no_replies"}}
+ </div>
+ {{/each}}
+ </div>
+
+ <ConditionalLoadingSpinner @condition={{@loadingMore}} />
+
+ <LoadMore
+ @action={{@loadMoreRoots}}
+ @enabled={{@hasMoreRoots}}
+ @isLoading={{@loadingMore}}
+ />
+
+ <PluginOutlet
+ @name="topic-above-footer-buttons"
+ @connectorTagName="div"
+ @outletArgs={{lazyHash model=@topic}}
+ />
+
+ <PluginOutlet
+ @name="topic-area-bottom"
+ @connectorTagName="div"
+ @outletArgs={{lazyHash model=@topic}}
+ />
+
+ <PluginOutlet
+ @name="topic-above-suggested"
+ @connectorTagName="div"
+ @outletArgs={{lazyHash model=@topic}}
+ />
+
+ <PluginOutlet
+ @name="topic-navigation-bottom"
+ @connectorTagName="div"
+ @outletArgs={{lazyHash model=@topic}}
+ />
+
+ <NestedFloatingActions
+ @topic={{@topic}}
+ @replyAction={{fn @replyToPost @opPost 0}}
+ />
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/app/components/post/menu/buttons/replies.gjs b/frontend/discourse/app/components/post/menu/buttons/replies.gjs
index 61ed82f6a18..c4104c48f16 100644
--- a/frontend/discourse/app/components/post/menu/buttons/replies.gjs
+++ b/frontend/discourse/app/components/post/menu/buttons/replies.gjs
@@ -8,7 +8,14 @@ import { i18n } from "discourse-i18n";
export default class PostMenuRepliesButton extends Component {
static extraControls = true;
- static shouldRender(args) {
+ static shouldRender(args, _context, owner) {
+ if (owner) {
+ const router = owner.lookup("service:router");
+ if (router?.currentRouteName?.startsWith("nested")) {
+ return false;
+ }
+ }
+
const replyCount = args.post.reply_count;
if (!replyCount) {
diff --git a/frontend/discourse/app/components/topic-admin-menu.gjs b/frontend/discourse/app/components/topic-admin-menu.gjs
index e9b7be346f6..9e3b0399534 100644
--- a/frontend/discourse/app/components/topic-admin-menu.gjs
+++ b/frontend/discourse/app/components/topic-admin-menu.gjs
@@ -7,12 +7,16 @@ import DropdownMenu from "discourse/components/dropdown-menu";
import DMenu from "discourse/float-kit/components/d-menu";
import concatClass from "discourse/helpers/concat-class";
import icon from "discourse/helpers/d-icon";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
import getURL from "discourse/lib/get-url";
+import DiscourseURL from "discourse/lib/url";
import { and, not, or } from "discourse/truth-helpers";
export default class TopicAdminMenu extends Component {
@service adminTopicMenuButtons;
@service currentUser;
+ @service siteSettings;
@action
onRegisterApi(api) {
@@ -82,6 +86,45 @@ export default class TopicAdminMenu extends Component {
);
}
+ get showNestedRepliesToggle() {
+ return (
+ this.siteSettings.nested_replies_enabled &&
+ !this.siteSettings.nested_replies_default &&
+ this.currentUser?.staff
+ );
+ }
+
+ get nestedRepliesToggleLabel() {
+ return this.args.topic.get("is_nested_view")
+ ? "nested_replies.topic_admin_menu.disable_nested_replies"
+ : "nested_replies.topic_admin_menu.enable_nested_replies";
+ }
+
+ @action
+ async toggleNestedReplies() {
+ await this.dMenu.close();
+ const topic = this.args.topic;
+ const newValue = !topic.get("is_nested_view");
+ const topicId = topic.get("id");
+ const slug = topic.get("slug");
+
+ try {
+ await ajax(`/n/${slug}/${topicId}/toggle`, {
+ type: "PUT",
+ data: { enabled: newValue },
+ });
+ topic.set("is_nested_view", newValue);
+
+ if (newValue) {
+ DiscourseURL.routeTo(`/n/${slug}/${topicId}`);
+ } else {
+ DiscourseURL.routeTo(`/t/${slug}/${topicId}`);
+ }
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
<template>
{{#if this.showAdminButton}}
<DMenu
@@ -266,7 +309,13 @@ export default class TopicAdminMenu extends Component {
</dropdown.item>
{{/if}}
- {{#if (or this.currentUser.staff this.extraButtons.length)}}
+ {{#if
+ (or
+ this.currentUser.staff
+ this.showNestedRepliesToggle
+ this.extraButtons.length
+ )
+ }}
<dropdown.divider />
{{#if this.currentUser.staff}}
@@ -279,6 +328,16 @@ export default class TopicAdminMenu extends Component {
</dropdown.item>
{{/if}}
+ {{#if this.showNestedRepliesToggle}}
+ <dropdown.item class="topic-admin-nested-replies">
+ <DButton
+ @label={{this.nestedRepliesToggleLabel}}
+ @action={{this.toggleNestedReplies}}
+ @icon="nested-thread"
+ />
+ </dropdown.item>
+ {{/if}}
+
{{#each this.extraButtons as |button|}}
<dropdown.item>
<DButton
diff --git a/frontend/discourse/app/components/topic-map/topic-map-summary.gjs b/frontend/discourse/app/components/topic-map/topic-map-summary.gjs
index 1583850cfe5..75a07ac11e2 100644
--- a/frontend/discourse/app/components/topic-map/topic-map-summary.gjs
+++ b/frontend/discourse/app/components/topic-map/topic-map-summary.gjs
@@ -68,7 +68,7 @@ export default class TopicMapSummary extends Component {
}
get topRepliesSummaryEnabled() {
- return this.args.postStream.summary;
+ return this.args.postStream?.summary;
}
get topRepliesTitle() {
@@ -148,13 +148,13 @@ export default class TopicMapSummary extends Component {
@action
showTopReplies() {
- this.args.postStream.showTopReplies();
+ this.args.postStream?.showTopReplies();
}
@action
cancelFilter() {
- this.args.postStream.cancelFilter();
- this.args.postStream.refresh();
+ this.args.postStream?.cancelFilter();
+ this.args.postStream?.refresh();
}
@action
diff --git a/frontend/discourse/app/connectors/category-custom-settings/nested-replies-settings-upsert.gjs b/frontend/discourse/app/connectors/category-custom-settings/nested-replies-settings-upsert.gjs
new file mode 100644
index 00000000000..8b06115a4d1
--- /dev/null
+++ b/frontend/discourse/app/connectors/category-custom-settings/nested-replies-settings-upsert.gjs
@@ -0,0 +1,44 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import { i18n } from "discourse-i18n";
+
+export default class NestedRepliesSettingsUpsert extends Component {
+ static shouldRender(args, context) {
+ return (
+ context.siteSettings.nested_replies_enabled &&
+ context.siteSettings.enable_simplified_category_creation
+ );
+ }
+
+ get enabled() {
+ const value =
+ this.args.outletArgs.transientData?.category_setting
+ ?.nested_replies_default;
+ return !!value;
+ }
+
+ @action
+ async onToggle(_, { set, name }) {
+ await set(name, !this.enabled);
+ }
+
+ <template>
+ {{#let @outletArgs.form as |form|}}
+ <form.Section @title={{i18n "nested_replies.nested_view"}}>
+ <form.Object @name="category_setting" as |categorySetting|>
+ <categorySetting.Field
+ @type="checkbox"
+ @name="nested_replies_default"
+ @title={{i18n
+ "nested_replies.category_settings.default_nested_view"
+ }}
+ @onSet={{this.onToggle}}
+ as |field|
+ >
+ <field.Control />
+ </categorySetting.Field>
+ </form.Object>
+ </form.Section>
+ {{/let}}
+ </template>
+}
diff --git a/frontend/discourse/app/connectors/category-custom-settings/nested-replies-settings.gjs b/frontend/discourse/app/connectors/category-custom-settings/nested-replies-settings.gjs
new file mode 100644
index 00000000000..e768acec0a3
--- /dev/null
+++ b/frontend/discourse/app/connectors/category-custom-settings/nested-replies-settings.gjs
@@ -0,0 +1,27 @@
+import Component from "@glimmer/component";
+import { Input } from "@ember/component";
+import { i18n } from "discourse-i18n";
+
+export default class NestedRepliesSettings extends Component {
+ static shouldRender(args, context) {
+ return (
+ context.siteSettings.nested_replies_enabled &&
+ !context.siteSettings.enable_simplified_category_creation
+ );
+ }
+
+ <template>
+ <section class="field">
+ <h3>{{i18n "nested_replies.nested_view"}}</h3>
+ <div class="enable-nested-replies-default">
+ <label class="checkbox-label">
+ <Input
+ @type="checkbox"
+ @checked={{@outletArgs.category.category_setting.nested_replies_default}}
+ />
+ {{i18n "nested_replies.category_settings.default_nested_view"}}
+ </label>
+ </div>
+ </section>
+ </template>
+}
diff --git a/frontend/discourse/app/connectors/topic-navigation/nested-view-link.gjs b/frontend/discourse/app/connectors/topic-navigation/nested-view-link.gjs
new file mode 100644
index 00000000000..77376ebf2ba
--- /dev/null
+++ b/frontend/discourse/app/connectors/topic-navigation/nested-view-link.gjs
@@ -0,0 +1,24 @@
+import Component from "@glimmer/component";
+import getURL from "discourse/lib/get-url";
+import { i18n } from "discourse-i18n";
+
+export default class NestedViewLink extends Component {
+ static shouldRender(args, context) {
+ return (
+ context.siteSettings.nested_replies_enabled &&
+ args.topic?.is_nested_view &&
+ context.currentUser?.can_toggle_nested_mode
+ );
+ }
+
+ get nestedUrl() {
+ const topic = this.args.outletArgs.topic;
+ return getURL(`/n/${topic.slug}/${topic.id}`);
+ }
+
+ <template>
+ <a href={{this.nestedUrl}} class="nested-view-link">{{i18n
+ "nested_replies.view_as_nested"
+ }}</a>
+ </template>
+}
diff --git a/frontend/discourse/app/controllers/nested.js b/frontend/discourse/app/controllers/nested.js
new file mode 100644
index 00000000000..8f412e23dba
--- /dev/null
+++ b/frontend/discourse/app/controllers/nested.js
@@ -0,0 +1,543 @@
+import { tracked } from "@glimmer/tracking";
+import Controller from "@ember/controller";
+import { action } from "@ember/object";
+import { getOwner } from "@ember/owner";
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { bind } from "discourse/lib/decorators";
+import QuoteState from "discourse/lib/quote-state";
+import Composer from "discourse/models/composer";
+import { i18n } from "discourse-i18n";
+import processNode from "../lib/process-node";
+
+export default class NestedController extends Controller {
+ @service appEvents;
+ @service composer;
+ @service store;
+ @service dialog;
+ @service currentUser;
+ @service messageBus;
+ @service nestedViewCache;
+ @service router;
+
+ @tracked topic;
+ @tracked opPost;
+ @tracked rootNodes = [];
+ @tracked page = 0;
+ @tracked hasMoreRoots = false;
+ @tracked loadingMore = false;
+ @tracked sort;
+ @tracked messageBusLastId;
+ @tracked postNumber;
+ @tracked contextMode = false;
+ @tracked contextChain = null;
+ @tracked targetPostNumber = null;
+ @tracked contextNoAncestors = false;
+ @tracked ancestorsTruncated = false;
+ @tracked topAncestorPostNumber = null;
+ @tracked newRootPostIds = [];
+ @tracked editingTopic = false;
+ @tracked pinnedPostIds = [];
+ queryParams = ["sort", "context"];
+
+ // Externalized expansion state: postNumber → { expanded, collapsed }
+ // Components read on construction, write on toggle.
+ // Persisted across back/forward navigations via NestedViewCache.
+ expansionState = new Map();
+
+ // Cache of dynamically loaded children: postNumber → { childNodes, page, hasMore, fetchedFromServer }
+ // Populated by NestedPostChildren on every mutation, read on restoration.
+ fetchedChildrenCache = new Map();
+
+ // Scroll anchor for cache restoration: { postNumber, offsetFromTop }
+ scrollAnchor = null;
+
+ quoteState = new QuoteState();
+
+ // Flat registry of all rendered posts by post_number.
+ // Populated by NestedPost components via appEvents so that readPosts
+ // can find posts at any depth, not just those in the preloaded tree.
+ postRegistry = new Map();
+ #postEventsSubscribed = false;
+ #messageBusChannel = null;
+ #pendingPostIds = new Set();
+
+ // The topic controller/route are hydrated in setupController so we can
+ // delegate shared actions and read shared state instead of duplicating
+ // core logic.
+ get #topicController() {
+ return getOwner(this).lookup("controller:topic");
+ }
+
+ get #topicRoute() {
+ return getOwner(this).lookup("route:topic");
+ }
+
+ get buffered() {
+ return this.#topicController.buffered;
+ }
+
+ get showCategoryChooser() {
+ return this.#topicController.showCategoryChooser;
+ }
+
+ get canEditTags() {
+ return this.#topicController.canEditTags;
+ }
+
+ get minimumRequiredTags() {
+ return this.#topicController.minimumRequiredTags;
+ }
+
+ @action
+ async loadMoreRoots() {
+ if (this.loadingMore || !this.hasMoreRoots) {
+ return;
+ }
+
+ this.loadingMore = true;
+ try {
+ const nextPage = this.page + 1;
+ const data = await ajax(
+ `/n/${this.topic.slug}/${this.topic.id}.json?page=${nextPage}&sort=${this.sort}`
+ );
+
+ const newNodes = (data.roots || []).map((root) =>
+ this.#processNode(root)
+ );
+
+ this.rootNodes = [...this.rootNodes, ...newNodes];
+ this.page = data.page;
+ this.hasMoreRoots = data.has_more_roots || false;
+ } catch (e) {
+ popupAjaxError(e);
+ } finally {
+ this.loadingMore = false;
+ }
+ }
+
+ @action
+ changeSort(newSort) {
+ this.router.transitionTo({ queryParams: { sort: newSort } });
+ }
+
+ @action
+ viewFullThread() {
+ this.nestedViewCache.useNextTransition();
+ this.router.transitionTo("nested", this.topic.slug, this.topic.id, {
+ queryParams: { sort: this.sort, context: null },
+ });
+ }
+
+ @action
+ viewParentContext() {
+ if (this.ancestorsTruncated && this.topAncestorPostNumber) {
+ this.router.transitionTo(
+ "nestedPost",
+ this.topic.slug,
+ this.topic.id,
+ this.topAncestorPostNumber,
+ { queryParams: { sort: this.sort } }
+ );
+ } else {
+ this.router.transitionTo(
+ "nestedPost",
+ this.topic.slug,
+ this.topic.id,
+ this.targetPostNumber,
+ { queryParams: { sort: this.sort, context: null } }
+ );
+ }
+ }
+
+ @action
+ replyToPost(post) {
+ const topic = this.topic;
+ if (!topic.details?.can_create_post) {
+ return;
+ }
+
+ let replyTarget = post;
+
+ const opts = {
+ action: Composer.REPLY,
+ draftKey: topic.draft_key,
+ draftSequence: topic.draft_sequence || 0,
+ skipJumpOnSave: true,
+ };
+
+ if (replyTarget && replyTarget.post_number !== 1) {
+ opts.post = replyTarget;
+ } else {
+ opts.topic = topic;
+ }
+
+ this.composer.open(opts);
+ }
+
+ @action
+ editPost(post) {
+ this.#topicController.editPost(post);
+ this.composer.set("skipJumpOnSave", true);
+ }
+
+ @action
+ deletePost(post) {
+ if (!post.can_delete) {
+ return;
+ }
+
+ this.dialog.yesNoConfirm({
+ message: i18n("post.confirm_delete"),
+ didConfirm: () => {
+ post
+ .destroy(this.currentUser)
+ .then(() => this.#markPostDeletedLocally(post.id))
+ .catch(popupAjaxError);
+ },
+ });
+ }
+
+ @action
+ recoverPost(post) {
+ this.#topicController.recoverPost(post);
+ }
+
+ @action
+ async togglePinPost(post) {
+ if (!this.currentUser?.staff) {
+ return;
+ }
+
+ try {
+ const result = await ajax(
+ `/n/${this.topic.slug}/${this.topic.id}/pin.json`,
+ {
+ type: "PUT",
+ data: { post_id: post.id },
+ }
+ );
+
+ this.pinnedPostIds = result.pinned_post_ids || [];
+
+ if (this.pinnedPostIds.includes(post.id)) {
+ // Move newly pinned post to front of rootNodes
+ const idx = this.rootNodes.findIndex((n) => n.post.id === post.id);
+ if (idx > 0) {
+ const pinned = this.rootNodes[idx];
+ const rest = this.rootNodes.filter((_, i) => i !== idx);
+ this.rootNodes = [pinned, ...rest];
+ }
+ }
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ @action
+ selectText() {
+ const tc = this.#topicController;
+ const { postId, buffer, opts } = this.quoteState;
+ this.#ensurePostInStream(postId);
+ tc.quoteState.selected(postId, buffer, opts);
+ return tc.selectText();
+ }
+
+ @action
+ buildQuoteMarkdown() {
+ const tc = this.#topicController;
+ const { postId, buffer, opts } = this.quoteState;
+ this.#ensurePostInStream(postId);
+ tc.quoteState.selected(postId, buffer, opts);
+ return tc.buildQuoteMarkdown();
+ }
+
+ #ensurePostInStream(postId) {
+ const postStream = this.topic?.postStream;
+ if (!postStream) {
+ return;
+ }
+
+ const id = parseInt(postId, 10);
+ if (!postStream.findLoadedPost(id)) {
+ for (const post of this.postRegistry.values()) {
+ if (post.id === id) {
+ postStream.storePost(post);
+ break;
+ }
+ }
+ }
+ }
+
+ @action
+ showHistory(post) {
+ this.#topicRoute.showHistory(post);
+ }
+
+ @action
+ showFlags(post) {
+ this.#topicRoute.showFlags(post);
+ }
+
+ // editingTopic is @tracked locally because the topic controller's
+ // editingTopic is a classic property (not @tracked) — a plain getter
+ // aliasing it won't trigger Glimmer re-renders. We sync the flag to
+ // the topic controller so its finishedEditingTopic save logic works.
+ @action
+ startEditingTopic(event) {
+ event?.preventDefault();
+ if (!this.topic?.details?.can_edit) {
+ return;
+ }
+ this.editingTopic = true;
+ this.#topicController.set("editingTopic", true);
+ }
+
+ @action
+ cancelEditingTopic() {
+ this.#topicController.cancelEditingTopic();
+ this.editingTopic = false;
+ }
+
+ @action
+ finishedEditingTopic() {
+ this.#topicController.finishedEditingTopic();
+ this.editingTopic = false;
+ }
+
+ @action
+ topicCategoryChanged(categoryId) {
+ this.#topicController.topicCategoryChanged(categoryId);
+ }
+
+ @action
+ topicTagsChanged(value) {
+ this.#topicController.topicTagsChanged(value);
+ }
+
+ subscribe() {
+ this.unsubscribe();
+
+ this.appEvents.on(
+ "nested-replies:post-registered",
+ this,
+ this.#onPostRegistered
+ );
+ this.appEvents.on(
+ "nested-replies:post-unregistered",
+ this,
+ this.#onPostUnregistered
+ );
+ this.#postEventsSubscribed = true;
+
+ // Register the OP post directly since it's not rendered by NestedPost
+ if (this.opPost) {
+ this.postRegistry.set(this.opPost.post_number, this.opPost);
+ }
+
+ if (this.topic?.id && this.messageBusLastId != null) {
+ this.#messageBusChannel = `/topic/${this.topic.id}`;
+ this.messageBus.subscribe(
+ this.#messageBusChannel,
+ this._onMessage,
+ this.messageBusLastId
+ );
+ }
+ }
+
+ unsubscribe() {
+ if (this.#postEventsSubscribed) {
+ this.appEvents.off(
+ "nested-replies:post-registered",
+ this,
+ this.#onPostRegistered
+ );
+ this.appEvents.off(
+ "nested-replies:post-unregistered",
+ this,
+ this.#onPostUnregistered
+ );
+ this.#postEventsSubscribed = false;
+ }
+ if (this.#messageBusChannel) {
+ this.messageBus.unsubscribe(this.#messageBusChannel, this._onMessage);
+ this.#messageBusChannel = null;
+ }
+ this.postRegistry.clear();
+ }
+
+ #onPostRegistered(post) {
+ if (post?.post_number != null) {
+ this.postRegistry.set(post.post_number, post);
+ }
+ }
+
+ #onPostUnregistered(post) {
+ if (post?.post_number != null) {
+ this.postRegistry.delete(post.post_number);
+ }
+ }
+
+ @bind
+ _onMessage(data, globalId, messageId) {
+ if (messageId != null) {
+ this.messageBusLastId = messageId;
+ }
+
+ switch (data.type) {
+ case "created":
+ this.#handleCreated(data);
+ break;
+ case "revised":
+ case "rebaked":
+ case "deleted":
+ case "recovered":
+ case "acted":
+ this.#handlePostChanged(data);
+ break;
+ }
+ }
+
+ async #handleCreated(data) {
+ // Skip if this post is already known (e.g. cache restore replaying
+ // messages that were already processed before navigating away)
+ if (this.#isPostKnown(data.id) || this.#pendingPostIds.has(data.id)) {
+ return;
+ }
+
+ this.#pendingPostIds.add(data.id);
+ const topicId = this.topic?.id;
+ try {
+ const postData = await ajax(`/posts/${data.id}.json`);
+ if (this.topic?.id !== topicId) {
+ return;
+ }
+
+ const post = this.store.createRecord("post", postData);
+ post.topic = this.topic;
+
+ const replyTo = postData.reply_to_post_number;
+ const isRoot = !replyTo || replyTo === 1;
+
+ if (isRoot) {
+ if (data.user_id === this.currentUser?.id) {
+ this.rootNodes = [{ post, children: [] }, ...this.rootNodes];
+ } else {
+ this.newRootPostIds = [...this.newRootPostIds, data.id];
+ }
+ } else {
+ this.appEvents.trigger("nested-replies:child-created", {
+ post,
+ parentPostNumber: replyTo,
+ isOwnPost: data.user_id === this.currentUser?.id,
+ });
+ }
+ } catch {
+ // Post may not be visible to this user
+ } finally {
+ this.#pendingPostIds.delete(data.id);
+ }
+ }
+
+ #isPostKnown(postId) {
+ if (this.rootNodes.some((n) => n.post.id === postId)) {
+ return true;
+ }
+ if (this.newRootPostIds.includes(postId)) {
+ return true;
+ }
+ for (const post of this.postRegistry.values()) {
+ if (post.id === postId) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ async #handlePostChanged(data) {
+ if (data.type === "deleted") {
+ this.#markPostDeletedLocally(data.id);
+ return;
+ }
+
+ const topicId = this.topic?.id;
+ try {
+ const postData = await ajax(`/posts/${data.id}.json`);
+ if (this.topic?.id !== topicId) {
+ return;
+ }
+
+ const existing = [...this.postRegistry.values()].find(
+ (p) => p.id === data.id
+ );
+ if (existing) {
+ existing.setProperties(postData);
+ if (!postData.deleted_at) {
+ existing.set("deleted_post_placeholder", false);
+ }
+ }
+ } catch {
+ // Post may not be visible
+ }
+ }
+
+ #markPostDeletedLocally(postId) {
+ for (const post of this.postRegistry.values()) {
+ if (post.id === postId) {
+ post.set("deleted_at", new Date());
+ post.set("deleted_post_placeholder", true);
+ if (!this.currentUser?.staff) {
+ post.set("cooked", "");
+ }
+ break;
+ }
+ }
+ }
+
+ @action
+ async loadNewRoots() {
+ const ids = [...this.newRootPostIds];
+ this.newRootPostIds = [];
+
+ const topicId = this.topic?.id;
+ const results = await Promise.allSettled(
+ ids.map((id) => ajax(`/posts/${id}.json`))
+ );
+
+ if (this.topic?.id !== topicId) {
+ return;
+ }
+
+ const newNodes = [];
+ for (const result of results) {
+ if (result.status === "fulfilled") {
+ const postData = result.value;
+ const post = this.store.createRecord("post", postData);
+ post.topic = this.topic;
+ newNodes.push({ post, children: [] });
+ }
+ }
+
+ if (newNodes.length > 0) {
+ this.rootNodes = [...newNodes, ...this.rootNodes];
+ }
+ }
+
+ readPosts(topicId, postNumbers) {
+ if (this.topic?.id !== topicId) {
+ return;
+ }
+
+ for (const postNumber of postNumbers) {
+ const post = this.postRegistry.get(postNumber);
+ if (post && !post.read) {
+ post.set("read", true);
+ }
+ }
+ }
+
+ #processNode(nodeData) {
+ return processNode(this.store, this.topic, nodeData);
+ }
+}
diff --git a/frontend/discourse/app/controllers/topic.js b/frontend/discourse/app/controllers/topic.js
index 2a3c46c1cc9..b7dc26df836 100644
--- a/frontend/discourse/app/controllers/topic.js
+++ b/frontend/discourse/app/controllers/topic.js
@@ -93,7 +93,12 @@ export default class TopicController extends Controller {
@autoTrackedArray bookmarks = [];
@autoTrackedArray selectedPostIds = [];
- queryParams = ["filter", "username_filters", "replies_to_post_number"];
+ queryParams = [
+ "filter",
+ "username_filters",
+ "replies_to_post_number",
+ "flat",
+ ];
editingTopic = false;
enteredAt = null;
@@ -103,6 +108,7 @@ export default class TopicController extends Controller {
username_filters = null;
replies_to_post_number = null;
filter = null;
+ flat = null;
quoteState = new QuoteState();
currentPostId = null;
userLastReadPostNumber = null;
diff --git a/frontend/discourse/app/lib/nested-post-url.js b/frontend/discourse/app/lib/nested-post-url.js
new file mode 100644
index 00000000000..853df673302
--- /dev/null
+++ b/frontend/discourse/app/lib/nested-post-url.js
@@ -0,0 +1,5 @@
+import getURL from "discourse/lib/get-url";
+
+export default function nestedPostUrl(topic, postNumber) {
+ return getURL(`/n/${topic.slug}/${topic.id}/${postNumber}`);
+}
diff --git a/frontend/discourse/app/lib/process-node.js b/frontend/discourse/app/lib/process-node.js
new file mode 100644
index 00000000000..6ec1dd4aebf
--- /dev/null
+++ b/frontend/discourse/app/lib/process-node.js
@@ -0,0 +1,8 @@
+export default function processNode(store, topic, nodeData) {
+ const post = store.createRecord("post", nodeData);
+ post.topic = topic;
+ const children = (nodeData.children || []).map((child) =>
+ processNode(store, topic, child)
+ );
+ return { post, children };
+}
diff --git a/frontend/discourse/app/lib/registry/transformers.js b/frontend/discourse/app/lib/registry/transformers.js
index c532a0c2a02..80759a31a33 100644
--- a/frontend/discourse/app/lib/registry/transformers.js
+++ b/frontend/discourse/app/lib/registry/transformers.js
@@ -92,7 +92,6 @@ export const VALUE_TRANSFORMERS = Object.freeze([
"post-meta-data-infos",
"post-meta-data-poster-name-suppress-similar-name",
"post-notice-component",
- "post-share-url",
"post-show-topic-map",
"post-small-action-class",
"post-small-action-custom-component",
@@ -102,7 +101,6 @@ export const VALUE_TRANSFORMERS = Object.freeze([
"poster-name-user-title",
"preferences-save-attributes",
"quote-params",
- "route-to-url",
"small-user-attrs",
"tag-separator",
"topic-list-class",
@@ -112,7 +110,6 @@ export const VALUE_TRANSFORMERS = Object.freeze([
"topic-list-item-expand-pinned",
"topic-list-item-mobile-layout",
"topic-list-item-style",
- "topic-url-for-post-number",
"user-field-components",
"user-menu-notification-item-acting-user-avatar",
"user-notes-modal-subtitle",
diff --git a/frontend/discourse/app/lib/url.js b/frontend/discourse/app/lib/url.js
index 1e5a4d7a34f..8a86e0d1bd4 100644
--- a/frontend/discourse/app/lib/url.js
+++ b/frontend/discourse/app/lib/url.js
@@ -9,7 +9,6 @@ import { isTesting } from "discourse/lib/environment";
import getURL, { withoutPrefix } from "discourse/lib/get-url";
import LockOn from "discourse/lib/lock-on";
import offsetCalculator from "discourse/lib/offset-calculator";
-import { applyValueTransformer } from "discourse/lib/transformer";
import { defaultHomepage } from "discourse/lib/utilities";
import Category from "discourse/models/category";
import Session from "discourse/models/session";
@@ -230,11 +229,6 @@ class DiscourseURL extends EmberObject {
return;
}
- path = applyValueTransformer("route-to-url", path, { opts });
- if (isEmpty(path)) {
- return;
- }
-
// In embed mode, open all navigation in new tabs except same-topic navigation
if (EmbedMode.enabled) {
const currentTopicMatch = TOPIC_URL_REGEXP.exec(window.location.pathname);
@@ -370,7 +364,7 @@ class DiscourseURL extends EmberObject {
const internalPath = url.replace(this.origin, "");
- return internalPath.startsWith("/t/");
+ return internalPath.startsWith("/t/") || internalPath.startsWith("/n/");
}
/**
diff --git a/frontend/discourse/app/models/post.js b/frontend/discourse/app/models/post.js
index 2d7964f3cdb..ff23a435d6d 100644
--- a/frontend/discourse/app/models/post.js
+++ b/frontend/discourse/app/models/post.js
@@ -7,6 +7,7 @@ import { Promise } from "rsvp";
import { resolveShareUrl } from "discourse/helpers/share-url";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
+import getURL from "discourse/lib/get-url";
import { deepEqual } from "discourse/lib/object";
import { cook } from "discourse/lib/text";
import { fancyTitle } from "discourse/lib/topic-fancy-title";
@@ -14,7 +15,6 @@ import {
defineTrackedProperty,
enumerateTrackedKeys,
} from "discourse/lib/tracked-tools";
-import { applyValueTransformer } from "discourse/lib/transformer";
import { userPath } from "discourse/lib/url";
import { postUrl } from "discourse/lib/utilities";
import ActionSummary from "discourse/models/action-summary";
@@ -155,6 +155,7 @@ export default class Post extends RestModel {
@tracked customShare = null;
@tracked deleted_at;
@tracked deleted_by;
+ @tracked deleted_post_placeholder;
@tracked excerpt;
@tracked expandedExcerpt;
@tracked group_moderator;
@@ -267,8 +268,7 @@ export default class Post extends RestModel {
}
get shareUrl() {
- const url = this.customShare || resolveShareUrl(this.url, this.currentUser);
- return applyValueTransformer("post-share-url", url, { post: this });
+ return this.customShare || resolveShareUrl(this.url, this.currentUser);
}
@computed("name", "username")
@@ -288,8 +288,19 @@ export default class Post extends RestModel {
return this.firstPost ? this.topic?.deleted_at : this.deleted_at;
}
- @computed("post_number", "topic_id", "topic.slug")
+ @computed(
+ "post_number",
+ "topic_id",
+ "topic.slug",
+ "topic.is_nested_view",
+ "topic._forcedFlat"
+ )
get url() {
+ if (this.topic?.is_nested_view && !this.topic?._forcedFlat) {
+ const slug = this.topic.slug || "topic";
+ const topicId = this.topic_id || this.topic.id;
+ return getURL(`/n/${slug}/${topicId}/${this.post_number}`);
+ }
return postUrl(
this.topic?.slug || this.topic_slug,
this.topic_id || this.get("topic.id"),
diff --git a/frontend/discourse/app/models/topic.js b/frontend/discourse/app/models/topic.js
index cd0eb3519f5..587e7b31933 100644
--- a/frontend/discourse/app/models/topic.js
+++ b/frontend/discourse/app/models/topic.js
@@ -22,7 +22,6 @@ import {
autoTrackedArray,
defineTrackedProperty,
} from "discourse/lib/tracked-tools";
-import { applyValueTransformer } from "discourse/lib/transformer";
import DiscourseURL, { userPath } from "discourse/lib/url";
import ActionSummary from "discourse/models/action-summary";
import Bookmark from "discourse/models/bookmark";
@@ -115,7 +114,7 @@ export default class Topic extends RestModel {
if (opts.fastEdit) {
data.keep_existing_draft = true;
}
- return ajax(topic.get("url"), {
+ return ajax(topic.get("updateUrl") || topic.get("url"), {
type: "PUT",
data: JSON.stringify(data),
contentType: "application/json",
@@ -634,24 +633,32 @@ export default class Topic extends RestModel {
}
@computed("id", "slug")
+ get updateUrl() {
+ let slug = this.slug || "";
+ if (slug.trim().length === 0) {
+ slug = "topic";
+ }
+ return `${getURL("/t/")}${slug}/${this.id}`;
+ }
+
+ @computed("id", "slug", "is_nested_view", "_forcedFlat")
get url() {
let slug = this.slug || "";
if (slug.trim().length === 0) {
slug = "topic";
}
+ if (this.is_nested_view && !this._forcedFlat) {
+ return `${getURL("/n/")}${slug}/${this.id}`;
+ }
return `${getURL("/t/")}${slug}/${this.id}`;
}
- // Helper to build a Url with a post number
urlForPostNumber(postNumber) {
let url = this.url;
if (postNumber > 0) {
url += `/${postNumber}`;
}
- return applyValueTransformer("topic-url-for-post-number", url, {
- topic: this,
- postNumber,
- });
+ return url;
}
@computed("unread_posts", "new_posts")
@@ -671,13 +678,26 @@ export default class Topic extends RestModel {
return this.unread_posts || this.new_posts;
}
- @computed("last_read_post_number", "url")
+ @computed("last_read_post_number", "url", "is_nested_view", "_forcedFlat")
get lastReadUrl() {
+ if (this.is_nested_view && !this._forcedFlat) {
+ return this.url;
+ }
return this.urlForPostNumber(this.last_read_post_number);
}
- @computed("last_read_post_number", "highest_post_number", "url")
+ @computed(
+ "last_read_post_number",
+ "highest_post_number",
+ "url",
+ "is_nested_view",
+ "_forcedFlat"
+ )
get lastUnreadUrl() {
+ if (this.is_nested_view && !this._forcedFlat) {
+ return this.url;
+ }
+
let customUrl = null;
_customLastUnreadUrlCallbacks.some((cb) => {
const result = cb(this);
@@ -706,8 +726,11 @@ export default class Topic extends RestModel {
return this.urlForPostNumber(postNumber);
}
- @computed("highest_post_number", "url")
+ @computed("highest_post_number", "url", "is_nested_view", "_forcedFlat")
get lastPostUrl() {
+ if (this.is_nested_view && !this._forcedFlat) {
+ return this.url;
+ }
return this.urlForPostNumber(this.highest_post_number);
}
@@ -757,7 +780,7 @@ export default class Topic extends RestModel {
if (property === "closed") {
this.incrementProperty("posts_count");
}
- return ajax(`${this.url}/status`, {
+ return ajax(`${this.updateUrl}/status`, {
type: "PUT",
data: {
status: property,
diff --git a/frontend/discourse/app/modifiers/post-stream-viewport-tracker.js b/frontend/discourse/app/modifiers/post-stream-viewport-tracker.js
index 8817659ac6b..5eb764a40d0 100644
--- a/frontend/discourse/app/modifiers/post-stream-viewport-tracker.js
+++ b/frontend/discourse/app/modifiers/post-stream-viewport-tracker.js
@@ -150,6 +150,14 @@ export default class PostStreamViewportTracker {
*/
#currentPostElement;
+ /**
+ * Whether eyeline tracking (current post, scroll position, URL updates) is enabled.
+ * When false, only cloaking and screen tracking are active.
+ * @type {boolean}
+ * @private
+ */
+ #eyeline = true;
+
/**
* Callback function to notify when the scroll position within the current post changes
* @type {Function|null}
@@ -179,6 +187,14 @@ export default class PostStreamViewportTracker {
*/
#observedPostElements = new Set();
+ /**
+ * Subset of #observedPostElements that are viewport-only (trackOnly=true).
+ * These elements are NOT registered with the cloaking observer.
+ * @type {Set<HTMLElement>}
+ * @private
+ */
+ #trackOnlyElements = new Set();
+
/**
* Map of post numbers to their post models and DOM elements that are currently on screen
* Used to track which posts are visible in the viewport for eyeline calculations and screen tracking
@@ -261,15 +277,24 @@ export default class PostStreamViewportTracker {
* @type {Modifier}
* @param {HTMLElement} element - The post element to register
* @param {Array} [post] - Array containing the post model associated with the element
+ * @param {Object} [options] - Named arguments
+ * @param {boolean} [options.trackOnly=false] - When true, only register with the
+ * viewport observer for screen-time tracking. Skip the cloaking observer so this
+ * element's height is not used for cloaking decisions. Useful for child post
+ * articles inside a subtree whose root wrapper already handles cloaking.
* @returns {Function} Cleanup function that removes observers when the element is destroyed
* @private
*/
- #registerPost = modifier((element, [post]) => {
+ #registerPost = modifier((element, [post], { trackOnly = false } = {}) => {
elementsToPost.set(element, post);
if (!this.#observedPostElements.has(element)) {
this.#observedPostElements.add(element);
- this.#cloakingObserver?.observe(element);
+ if (trackOnly) {
+ this.#trackOnlyElements.add(element);
+ } else {
+ this.#cloakingObserver?.observe(element);
+ }
this.#viewportObserver?.observe(element);
}
@@ -279,7 +304,10 @@ export default class PostStreamViewportTracker {
if (this.#observedPostElements.has(element)) {
this.#observedPostElements.delete(element);
- this.#cloakingObserver?.unobserve(element);
+ this.#trackOnlyElements.delete(element);
+ if (!trackOnly) {
+ this.#cloakingObserver?.unobserve(element);
+ }
this.#viewportObserver?.unobserve(element);
}
};
@@ -310,6 +338,7 @@ export default class PostStreamViewportTracker {
{
currentPostChanged,
currentPostScrolled,
+ eyeline = true,
headerOffset,
screenTrack,
setCloakingBoundaries,
@@ -318,20 +347,30 @@ export default class PostStreamViewportTracker {
}
) => {
this.#wrapperElement = element;
+ this.#eyeline = eyeline;
- this.#currentPostChanged = currentPostChanged;
- this.#currentPostScrolled = currentPostScrolled;
this.#headerOffset = headerOffset;
this.#screenTrackService = screenTrack;
this.#setCloakingBoundaries = setCloakingBoundaries;
+ if (this.#eyeline) {
+ this.#currentPostChanged = currentPostChanged;
+ this.#currentPostScrolled = currentPostScrolled;
+ }
+
this.#updateCloakOffset();
- this.#setupEventListeners();
// intersection observers
this.#resetViewportObservers();
- // eyeline
- this.#setupEyelineDebugElement();
+
+ if (this.#eyeline) {
+ this.#setupEventListeners();
+ this.#setupEyelineDebugElement();
+
+ schedule("afterRender", () => {
+ this.#scrollTriggered(true);
+ });
+ }
// clear the list of posts with cloaking prevented when the topic changes
if (cloakingPrevented.topicId !== topicId) {
@@ -343,21 +382,16 @@ export default class PostStreamViewportTracker {
// https://github.com/emberjs/ember.js/issues/19277
trackedArgs && Object.values(trackedArgs);
- schedule("afterRender", () => {
- // forces updates performed when the scroll is triggered to be performed after the initial rendering
- this.#scrollTriggered(true);
- });
-
// cleanup
return () => {
// clear observers
this.#cloakingObserver?.disconnect();
this.#viewportObserver?.disconnect();
- // clear event listeners
- this.#setupEventListeners(false);
- // remove the eyeline debug element
- this.#setupEyelineDebugElement(false);
+ if (this.#eyeline) {
+ this.#setupEventListeners(false);
+ this.#setupEyelineDebugElement(false);
+ }
// clear collections
this.#cloakedPostsStyle = {};
@@ -387,6 +421,7 @@ export default class PostStreamViewportTracker {
// clear DOM references
this.#observedPostElements.clear();
+ this.#trackOnlyElements.clear();
// clear the set of posts with cloaking prevented
cloakingPrevented.topicId = null;
@@ -557,8 +592,9 @@ export default class PostStreamViewportTracker {
)
);
- // forces updates performed when the scroll is triggered
- this.#scrollTriggered();
+ if (this.#eyeline) {
+ this.#scrollTriggered();
+ }
}
/**
@@ -813,7 +849,9 @@ export default class PostStreamViewportTracker {
});
for (const element of this.#observedPostElements) {
- this.#cloakingObserver.observe(element);
+ if (!this.#trackOnlyElements.has(element)) {
+ this.#cloakingObserver.observe(element);
+ }
this.#viewportObserver.observe(element);
}
}
diff --git a/frontend/discourse/app/routes/app-route-map.js b/frontend/discourse/app/routes/app-route-map.js
index 357611872ce..f99c3565ec1 100644
--- a/frontend/discourse/app/routes/app-route-map.js
+++ b/frontend/discourse/app/routes/app-route-map.js
@@ -20,6 +20,10 @@ export default function () {
this.route("topicBySlugOrId", { path: "/t/:slug_or_id" });
+ // Nested replies routes
+ this.route("nested", { path: "/n/:slug/:topic_id" });
+ this.route("nestedPost", { path: "/n/:slug/:topic_id/:post_number" });
+
this.route("discovery", { path: "/" }, function () {
// top by periods - legacy route
Site.currentProp("periods").forEach((period) => {
diff --git a/frontend/discourse/app/routes/nested-post.js b/frontend/discourse/app/routes/nested-post.js
new file mode 100644
index 00000000000..f63d9bbd918
--- /dev/null
+++ b/frontend/discourse/app/routes/nested-post.js
@@ -0,0 +1,11 @@
+import NestedRoute from "discourse/routes/nested";
+
+export default class NestedPostRoute extends NestedRoute {
+ controllerName = "nested";
+ templateName = "nested";
+
+ queryParams = {
+ sort: { refreshModel: true },
+ context: { refreshModel: true },
+ };
+}
diff --git a/frontend/discourse/app/routes/nested.js b/frontend/discourse/app/routes/nested.js
new file mode 100644
index 00000000000..e9b0114334d
--- /dev/null
+++ b/frontend/discourse/app/routes/nested.js
@@ -0,0 +1,253 @@
+import { getOwner } from "@ember/owner";
+import Route from "@ember/routing/route";
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import PreloadStore from "discourse/lib/preload-store";
+import processNode from "../lib/process-node";
+
+export default class NestedRoute extends Route {
+ @service nestedViewCache;
+ @service screenTrack;
+ @service siteSettings;
+ @service store;
+
+ queryParams = {
+ sort: { refreshModel: true },
+ context: { refreshModel: true },
+ };
+
+ buildRouteInfoMetadata() {
+ return { scrollOnTransition: false };
+ }
+
+ async model(params) {
+ const { topic_id, slug, post_number } = params;
+ const sort =
+ params.sort || this.siteSettings.nested_replies_default_sort || "top";
+
+ const cacheKey = this.nestedViewCache.buildKey(topic_id, {
+ ...params,
+ sort,
+ });
+ if (this.nestedViewCache.consumeTraversal()) {
+ const cached = this.nestedViewCache.get(cacheKey);
+ if (cached) {
+ this._restoringFromCache = cached;
+ return cached.modelData;
+ }
+ }
+ this._restoringFromCache = null;
+
+ if (post_number) {
+ const queryParts = [`sort=${sort}`, "track_visit=true"];
+ if (params.context !== undefined && params.context !== null) {
+ queryParts.push(`context=${params.context}`);
+ }
+ const contextQuery = `?${queryParts.join("&")}`;
+ const data = await PreloadStore.getAndRemove(
+ `nested_topic_${topic_id}`,
+ () =>
+ ajax(
+ `/n/${slug}/${topic_id}/context/${post_number}.json${contextQuery}`
+ )
+ );
+ return this._processContextResponse(data, params, sort);
+ }
+
+ const data = await PreloadStore.getAndRemove(
+ `nested_topic_${topic_id}`,
+ () => ajax(`/n/${slug}/${topic_id}.json?sort=${sort}&track_visit=true`)
+ );
+ return this._processResponse(data, params);
+ }
+
+ setupController(controller, model) {
+ if (this._restoringFromCache) {
+ controller.expansionState = this._restoringFromCache.expansionState;
+ controller.fetchedChildrenCache =
+ this._restoringFromCache.fetchedChildrenCache;
+ controller.scrollAnchor = this._restoringFromCache.scrollAnchor;
+ this._restoringFromCache = null;
+ } else {
+ controller.expansionState = new Map();
+ controller.fetchedChildrenCache = new Map();
+ controller.scrollAnchor = null;
+ }
+
+ controller.setProperties(model);
+ controller.subscribe();
+
+ // Hydrate the topic controller so core components that do
+ // lookup("controller:topic") (e.g. share modal) find valid state.
+ this.controllerFor("topic").set("model", model.topic);
+
+ // Set the topic route's currentModel so route actions that call
+ // this.modelFor("topic") (e.g. showFeatureTopic, showTopicTimerModal)
+ // find the topic instead of undefined.
+ getOwner(this).lookup("route:topic").currentModel = model.topic;
+
+ // The Topic details setter replaces _details without preserving the
+ // back-reference to the parent topic. Restore it so that
+ // topic.details.updateNotifications() can construct the correct URL.
+ model.topic.details.set("topic", model.topic);
+
+ // Store the OP in the postStream so core components that call
+ // postStream.findLoadedPost() (e.g. share modal's "reply as new topic")
+ // find a valid post instead of undefined.
+ if (model.opPost && model.topic.postStream) {
+ model.topic.postStream.storePost(model.opPost);
+ }
+
+ this.screenTrack.start(model.topic.id, controller);
+ }
+
+ deactivate() {
+ super.deactivate(...arguments);
+
+ const controller = this.controller;
+ this._saveToCache(controller);
+
+ controller.unsubscribe();
+ this.screenTrack.stop();
+ }
+
+ _saveToCache(controller) {
+ if (!controller.topic) {
+ return;
+ }
+
+ const cacheKey = this.nestedViewCache.buildKey(controller.topic.id, {
+ sort: controller.sort,
+ post_number: controller.postNumber,
+ context: controller.contextNoAncestors ? 0 : undefined,
+ });
+
+ this.nestedViewCache.save(cacheKey, {
+ modelData: {
+ topic: controller.topic,
+ opPost: controller.opPost,
+ rootNodes: controller.rootNodes,
+ page: controller.page,
+ hasMoreRoots: controller.hasMoreRoots,
+ sort: controller.sort,
+ messageBusLastId: controller.messageBusLastId,
+ pinnedPostIds: controller.pinnedPostIds,
+ postNumber: controller.postNumber,
+ contextMode: controller.contextMode,
+ contextChain: controller.contextChain,
+ targetPostNumber: controller.targetPostNumber,
+ contextNoAncestors: controller.contextNoAncestors,
+ ancestorsTruncated: controller.ancestorsTruncated,
+ topAncestorPostNumber: controller.topAncestorPostNumber,
+ },
+ expansionState: new Map(controller.expansionState),
+ fetchedChildrenCache: new Map(controller.fetchedChildrenCache),
+ scrollAnchor: this._findScrollAnchor(),
+ });
+ }
+
+ _findScrollAnchor() {
+ const articles = document.querySelectorAll(
+ ".nested-post [data-post-number]"
+ );
+ let best = null;
+ let bestDistance = Infinity;
+
+ for (const el of articles) {
+ const rect = el.getBoundingClientRect();
+ const distance = Math.abs(rect.top);
+ if (distance < bestDistance) {
+ bestDistance = distance;
+ best = {
+ postNumber: Number(el.dataset.postNumber),
+ offsetFromTop: rect.top,
+ };
+ }
+ }
+ return best;
+ }
+
+ _processResponse(data, params) {
+ const topic = this.store.createRecord("topic", data.topic);
+ topic.set("is_nested_view", true);
+
+ const assignTopic = (postData) => {
+ const post = this.store.createRecord("post", postData);
+ post.topic = topic;
+ return post;
+ };
+
+ const opPost = data.op_post ? assignTopic(data.op_post) : null;
+
+ const rootNodes = (data.roots || []).map((root) =>
+ processNode(this.store, topic, root)
+ );
+
+ return {
+ topic,
+ opPost,
+ rootNodes,
+ page: data.page || 0,
+ hasMoreRoots: data.has_more_roots || false,
+ sort: data.sort || this.siteSettings.nested_replies_default_sort || "top",
+ messageBusLastId: data.message_bus_last_id,
+ pinnedPostIds: data.pinned_post_ids || [],
+ postNumber: params.post_number ? Number(params.post_number) : null,
+ contextMode: false,
+ contextChain: null,
+ targetPostNumber: null,
+ contextNoAncestors: false,
+ ancestorsTruncated: false,
+ topAncestorPostNumber: null,
+ newRootPostIds: [],
+ editingTopic: false,
+ };
+ }
+
+ _processContextResponse(data, params, sort) {
+ const topic = this.store.createRecord("topic", data.topic);
+ topic.set("is_nested_view", true);
+
+ const assignTopic = (postData) => {
+ const post = this.store.createRecord("post", postData);
+ post.topic = topic;
+ return post;
+ };
+
+ const opPost = data.op_post ? assignTopic(data.op_post) : null;
+
+ const targetNode = processNode(this.store, topic, data.target_post);
+ const ancestors = (data.ancestor_chain || []).map((a) => assignTopic(a));
+ const targetReplyTo = targetNode.post.reply_to_post_number;
+ const hasParentContext = targetReplyTo && targetReplyTo !== 1;
+ const noAncestors = ancestors.length === 0 && hasParentContext;
+
+ // Build nested chain: ancestor[0] -> ancestor[1] -> ... -> target
+ // When context=0 (no ancestors), target becomes the chain root at depth 0.
+ let chainTip = targetNode;
+ for (let i = ancestors.length - 1; i >= 0; i--) {
+ chainTip = { post: ancestors[i], children: [chainTip] };
+ }
+
+ return {
+ topic,
+ opPost,
+ sort,
+ pinnedPostIds: [],
+ messageBusLastId: data.message_bus_last_id,
+ postNumber: Number(params.post_number),
+ contextMode: true,
+ contextChain: chainTip,
+ targetPostNumber: Number(params.post_number),
+ contextNoAncestors: noAncestors,
+ ancestorsTruncated: data.ancestors_truncated || false,
+ topAncestorPostNumber:
+ ancestors.length > 0 ? ancestors[0].post_number : null,
+ rootNodes: [],
+ page: 0,
+ hasMoreRoots: false,
+ newRootPostIds: [],
+ editingTopic: false,
+ };
+ }
+}
diff --git a/frontend/discourse/app/routes/topic.js b/frontend/discourse/app/routes/topic.js
index 2e599ab369a..12531fc6d5d 100644
--- a/frontend/discourse/app/routes/topic.js
+++ b/frontend/discourse/app/routes/topic.js
@@ -40,6 +40,7 @@ export default class TopicRoute extends DiscourseRoute {
queryParams = {
filter: { replace: true },
username_filters: { replace: true },
+ flat: { replace: true },
};
buildRouteInfoMetadata() {
diff --git a/frontend/discourse/app/routes/topic/from-params.js b/frontend/discourse/app/routes/topic/from-params.js
index 956064ab940..699ffdc402a 100644
--- a/frontend/discourse/app/routes/topic/from-params.js
+++ b/frontend/discourse/app/routes/topic/from-params.js
@@ -16,11 +16,21 @@ export default class TopicFromParams extends DiscourseRoute {
@service router;
// Avoid default model hook
- model(params) {
+ model(params, transition) {
params = params || {};
params.track_visit = true;
const topic = this.modelFor("topic");
+
+ // Skip the full post-stream load when we know afterModel will redirect
+ // to the nested route. The nested route handles its own visit tracking.
+ const flatParam =
+ transition?.to?.queryParams?.flat ||
+ transition?.to?.parent?.queryParams?.flat;
+ if (topic.is_nested_view && !flatParam && !topic._forcedFlat) {
+ return params;
+ }
+
const postStream = topic.postStream;
// I sincerely hope no topic gets this many posts
@@ -42,9 +52,31 @@ export default class TopicFromParams extends DiscourseRoute {
});
}
- afterModel(model) {
+ afterModel(model, transition) {
const topic = this.modelFor("topic");
+ if (topic.is_nested_view) {
+ const flatParam =
+ transition?.to?.queryParams?.flat ||
+ transition?.to?.parent?.queryParams?.flat;
+ if (flatParam || topic._forcedFlat) {
+ topic.set("_forcedFlat", true);
+ } else {
+ const postNumber = model.nearPost;
+ if (postNumber && postNumber > 1) {
+ this.router.replaceWith(
+ "nestedPost",
+ topic.slug,
+ topic.id,
+ postNumber
+ );
+ } else {
+ this.router.replaceWith("nested", topic.slug, topic.id);
+ }
+ return;
+ }
+ }
+
const isLoadingFirstPost =
topic.postStream.firstPostPresent &&
!(model.nearPost && model.nearPost > 1);
diff --git a/frontend/discourse/app/services/nested-view-cache.js b/frontend/discourse/app/services/nested-view-cache.js
new file mode 100644
index 00000000000..69210544a05
--- /dev/null
+++ b/frontend/discourse/app/services/nested-view-cache.js
@@ -0,0 +1,123 @@
+import Service from "@ember/service";
+
+const MAX_ENTRIES = 15;
+const TTL_MS = 10 * 60 * 1000; // 10 minutes
+
+export default class NestedViewCacheService extends Service {
+ #cache = new Map();
+ #lastNavigationType = null;
+ #popstateTime = null;
+ #forceUseCache = false;
+ #onNavigate = null;
+ #onPopstate = null;
+
+ constructor() {
+ super(...arguments);
+
+ if (window.navigation) {
+ this.#onNavigate = (e) => {
+ this.#lastNavigationType = e.navigationType;
+ };
+ window.navigation.addEventListener("navigate", this.#onNavigate);
+ }
+
+ // Always listen for popstate as a fallback — the Navigation API's
+ // navigate event may not fire in all environments (e.g. Playwright CDP).
+ this.#onPopstate = () => {
+ this.#popstateTime = Date.now();
+ };
+ window.addEventListener("popstate", this.#onPopstate);
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ if (this.#onNavigate) {
+ window.navigation?.removeEventListener("navigate", this.#onNavigate);
+ }
+ window.removeEventListener("popstate", this.#onPopstate);
+ }
+
+ useNextTransition() {
+ this.#forceUseCache = true;
+ }
+
+ consumeTraversal() {
+ if (this.#forceUseCache) {
+ this.#forceUseCache = false;
+ this.#lastNavigationType = null;
+ this.#popstateTime = null;
+ return true;
+ }
+
+ // Prefer Navigation API (explicit traversal type) when available
+ if (this.#lastNavigationType != null) {
+ const result = this.#lastNavigationType === "traverse";
+ this.#lastNavigationType = null;
+ this.#popstateTime = null;
+ return result;
+ }
+
+ // Fallback: popstate fires for back/forward in all browsers
+ if (this.#popstateTime && Date.now() - this.#popstateTime < 1000) {
+ this.#popstateTime = null;
+ return true;
+ }
+ this.#popstateTime = null;
+ return false;
+ }
+
+ save(key, entry) {
+ entry.timestamp = Date.now();
+ this.#cache.set(key, entry);
+ this.#evict();
+ }
+
+ get(key) {
+ const entry = this.#cache.get(key);
+ if (!entry) {
+ return null;
+ }
+ if (Date.now() - entry.timestamp > TTL_MS) {
+ this.#cache.delete(key);
+ return null;
+ }
+ return entry;
+ }
+
+ remove(key) {
+ this.#cache.delete(key);
+ }
+
+ #evict() {
+ const now = Date.now();
+ for (const [k, v] of this.#cache) {
+ if (now - v.timestamp > TTL_MS) {
+ this.#cache.delete(k);
+ }
+ }
+
+ if (this.#cache.size > MAX_ENTRIES) {
+ const entries = [...this.#cache.entries()].sort(
+ (a, b) => a[1].timestamp - b[1].timestamp
+ );
+ const toRemove = entries.length - MAX_ENTRIES;
+ for (let i = 0; i < toRemove; i++) {
+ this.#cache.delete(entries[i][0]);
+ }
+ }
+ }
+
+ buildKey(topicId, params) {
+ const parts = [topicId];
+ if (params.sort) {
+ parts.push(`s=${params.sort}`);
+ }
+ if (params.post_number) {
+ parts.push(`p=${params.post_number}`);
+ }
+ if (params.context != null) {
+ parts.push(`c=${params.context}`);
+ }
+ return parts.join(":");
+ }
+}
diff --git a/frontend/discourse/app/templates/nested-loading.gjs b/frontend/discourse/app/templates/nested-loading.gjs
new file mode 100644
index 00000000000..a897c9a3a30
--- /dev/null
+++ b/frontend/discourse/app/templates/nested-loading.gjs
@@ -0,0 +1,7 @@
+import hideApplicationFooter from "discourse/helpers/hide-application-footer";
+import loadingSpinner from "discourse/helpers/loading-spinner";
+
+export default <template>
+ {{loadingSpinner}}
+ {{hideApplicationFooter}}
+</template>
diff --git a/frontend/discourse/app/templates/nested.gjs b/frontend/discourse/app/templates/nested.gjs
new file mode 100644
index 00000000000..1d2a99f38b3
--- /dev/null
+++ b/frontend/discourse/app/templates/nested.gjs
@@ -0,0 +1,81 @@
+import NestedContextView from "discourse/components/nested-context-view";
+import NestedView from "discourse/components/nested-view";
+import PostTextSelection from "discourse/components/post-text-selection";
+
+export default <template>
+ <PostTextSelection
+ @quoteState={{@controller.quoteState}}
+ @selectText={{@controller.selectText}}
+ @buildQuoteMarkdown={{@controller.buildQuoteMarkdown}}
+ @editPost={{@controller.editPost}}
+ @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}}
+ @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}}
+ />
+ {{else}}
+ <NestedView
+ @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}}
+ @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}}
+ />
+ {{/if}}
+</template>
diff --git a/frontend/discourse/tests/acceptance/transformers/post-share-url-test.js b/frontend/discourse/tests/acceptance/transformers/post-share-url-test.js
deleted file mode 100644
index 0e1d840c1da..00000000000
--- a/frontend/discourse/tests/acceptance/transformers/post-share-url-test.js
+++ /dev/null
@@ -1,51 +0,0 @@
-import { getOwner } from "@ember/owner";
-import { visit } from "@ember/test-helpers";
-import { test } from "qunit";
-import { withPluginApi } from "discourse/lib/plugin-api";
-import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-
-acceptance("post-share-url transformer", function (needs) {
- needs.user();
-
- test("applying a value transformation", async function (assert) {
- withPluginApi((api) => {
- api.registerValueTransformer("post-share-url", ({ value }) => {
- return "/custom" + value;
- });
- });
-
- await visit("/t/internationalization-localization/280");
-
- const topicController = getOwner(this).lookup("controller:topic");
- const post = topicController.model.postStream.posts[0];
-
- assert.true(
- post.shareUrl.startsWith("/custom"),
- "it transforms the share url"
- );
- });
-
- test("transformer receives the post in context", async function (assert) {
- let receivedPost;
-
- withPluginApi((api) => {
- api.registerValueTransformer("post-share-url", ({ value, context }) => {
- receivedPost = context.post;
- return value;
- });
- });
-
- await visit("/t/internationalization-localization/280");
-
- const topicController = getOwner(this).lookup("controller:topic");
- const post = topicController.model.postStream.posts[0];
- // access shareUrl to trigger the transformer
- post.shareUrl;
-
- assert.strictEqual(
- receivedPost.post_number,
- 1,
- "transformer receives the correct post in context"
- );
- });
-});
diff --git a/frontend/discourse/tests/acceptance/transformers/topic-url-for-post-number-test.js b/frontend/discourse/tests/acceptance/transformers/topic-url-for-post-number-test.js
deleted file mode 100644
index 1005361835c..00000000000
--- a/frontend/discourse/tests/acceptance/transformers/topic-url-for-post-number-test.js
+++ /dev/null
@@ -1,58 +0,0 @@
-import { getOwner } from "@ember/owner";
-import { visit } from "@ember/test-helpers";
-import { test } from "qunit";
-import { withPluginApi } from "discourse/lib/plugin-api";
-import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-
-acceptance("topic-url-for-post-number transformer", function (needs) {
- needs.user();
-
- test("applying a value transformation", async function (assert) {
- withPluginApi((api) => {
- api.registerValueTransformer("topic-url-for-post-number", ({ value }) => {
- return "/custom" + value;
- });
- });
-
- await visit("/t/internationalization-localization/280");
-
- const topicController = getOwner(this).lookup("controller:topic");
- const topic = topicController.model;
-
- assert.true(
- topic.urlForPostNumber(1).startsWith("/custom"),
- "it transforms the topic url for post number"
- );
- });
-
- test("transformer receives the topic and postNumber in context", async function (assert) {
- let receivedContext;
-
- withPluginApi((api) => {
- api.registerValueTransformer(
- "topic-url-for-post-number",
- ({ value, context }) => {
- receivedContext = context;
- return value;
- }
- );
- });
-
- await visit("/t/internationalization-localization/280");
-
- const topicController = getOwner(this).lookup("controller:topic");
- const topic = topicController.model;
- topic.urlForPostNumber(3);
-
- assert.strictEqual(
- receivedContext.topic,
- topic,
- "transformer receives the topic in context"
- );
- assert.strictEqual(
- receivedContext.postNumber,
- 3,
- "transformer receives the postNumber in context"
- );
- });
-});
diff --git a/frontend/discourse/tests/unit/controllers/nested-controller-read-posts-test.js b/frontend/discourse/tests/unit/controllers/nested-controller-read-posts-test.js
new file mode 100644
index 00000000000..d477beab921
--- /dev/null
+++ b/frontend/discourse/tests/unit/controllers/nested-controller-read-posts-test.js
@@ -0,0 +1,108 @@
+import { module, test } from "qunit";
+
+module("Unit | Controller | nested – readPosts with postRegistry", function () {
+ function makePost(postNumber, read = false) {
+ let _read = read;
+ return {
+ post_number: postNumber,
+ get read() {
+ return _read;
+ },
+ set(key, value) {
+ if (key === "read") {
+ _read = value;
+ }
+ },
+ };
+ }
+
+ function buildReadPosts(topicId, registry) {
+ return function readPosts(calledTopicId, postNumbers) {
+ if (topicId !== calledTopicId) {
+ return;
+ }
+ for (const postNumber of postNumbers) {
+ const post = registry.get(postNumber);
+ if (post && !post.read) {
+ post.set("read", true);
+ }
+ }
+ };
+ }
+
+ test("marks a post as read", function (assert) {
+ const registry = new Map();
+ const post = makePost(2);
+ registry.set(2, post);
+ const readPosts = buildReadPosts(42, registry);
+
+ readPosts(42, [2]);
+
+ assert.true(post.read);
+ });
+
+ test("marks multiple posts as read in a single call", function (assert) {
+ const registry = new Map();
+ const posts = [
+ makePost(2),
+ makePost(3),
+ makePost(4),
+ makePost(5),
+ makePost(6),
+ ];
+ for (const post of posts) {
+ registry.set(post.post_number, post);
+ }
+ const readPosts = buildReadPosts(42, registry);
+
+ readPosts(42, [2, 3, 4, 5, 6]);
+
+ for (const post of posts) {
+ assert.true(
+ post.read,
+ `post_number ${post.post_number} should be marked read`
+ );
+ }
+ });
+
+ test("does not mark already-read posts again", function (assert) {
+ const registry = new Map();
+ const post = makePost(2, true);
+ let setCalled = false;
+ const originalSet = post.set.bind(post);
+ post.set = (key, value) => {
+ setCalled = true;
+ originalSet(key, value);
+ };
+ registry.set(2, post);
+ const readPosts = buildReadPosts(42, registry);
+
+ readPosts(42, [2]);
+
+ assert.false(setCalled);
+ assert.true(post.read);
+ });
+
+ test("ignores post numbers not in the registry", function (assert) {
+ const registry = new Map();
+ const post = makePost(2);
+ registry.set(2, post);
+ const readPosts = buildReadPosts(42, registry);
+
+ readPosts(42, [2, 99]);
+
+ assert.true(post.read);
+ assert.strictEqual(registry.size, 1);
+ });
+
+ test("ignores calls for wrong topic id", function (assert) {
+ const registry = new Map();
+ const post = makePost(2);
+ registry.set(2, post);
+ const readPosts = buildReadPosts(42, registry);
+
+ readPosts(999, [2]);
+
+ assert.false(post.read);
+ });
+});
diff --git a/frontend/discourse/tests/unit/lib/nested-post-url-test.js b/frontend/discourse/tests/unit/lib/nested-post-url-test.js
new file mode 100644
index 00000000000..8bdc54a3af0
--- /dev/null
+++ b/frontend/discourse/tests/unit/lib/nested-post-url-test.js
@@ -0,0 +1,19 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import nestedPostUrl from "discourse/lib/nested-post-url";
+
+module("Unit | Lib | nested-post-url", function (hooks) {
+ setupTest(hooks);
+
+ test("builds a nested URL with topic slug, id and post number", function (assert) {
+ const topic = { slug: "test-topic", id: 42 };
+
+ assert.strictEqual(nestedPostUrl(topic, 5), "/n/test-topic/42/5");
+ });
+
+ test("always produces a URL without context param", function (assert) {
+ const topic = { slug: "my-topic", id: 99 };
+
+ assert.strictEqual(nestedPostUrl(topic, 7), "/n/my-topic/99/7");
+ });
+});
diff --git a/frontend/discourse/tests/unit/lib/process-node-test.js b/frontend/discourse/tests/unit/lib/process-node-test.js
new file mode 100644
index 00000000000..4e49fd05336
--- /dev/null
+++ b/frontend/discourse/tests/unit/lib/process-node-test.js
@@ -0,0 +1,75 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import processNode from "discourse/lib/process-node";
+
+module("Unit | Lib | process-node", function (hooks) {
+ setupTest(hooks);
+
+ function getStore(context) {
+ return context.owner.lookup("service:store");
+ }
+
+ test("creates a post record from node data", function (assert) {
+ const store = getStore(this);
+ const topic = { id: 42, slug: "test" };
+ const nodeData = {
+ id: 100,
+ post_number: 2,
+ cooked: "<p>Hello</p>",
+ };
+
+ const result = processNode(store, topic, nodeData);
+
+ assert.strictEqual(result.post.id, 100);
+ assert.strictEqual(result.post.post_number, 2);
+ assert.strictEqual(result.post.topic, topic);
+ });
+
+ test("returns empty children when node has no children", function (assert) {
+ const store = getStore(this);
+ const topic = { id: 42, slug: "test" };
+ const nodeData = { id: 100, post_number: 2 };
+
+ const result = processNode(store, topic, nodeData);
+
+ assert.deepEqual(result.children, []);
+ });
+
+ test("returns empty children when children array is empty", function (assert) {
+ const store = getStore(this);
+ const topic = { id: 42, slug: "test" };
+ const nodeData = { id: 100, post_number: 2, children: [] };
+
+ const result = processNode(store, topic, nodeData);
+
+ assert.deepEqual(result.children, []);
+ });
+
+ test("recursively processes children", function (assert) {
+ const store = getStore(this);
+ const topic = { id: 42, slug: "test" };
+ const nodeData = {
+ id: 100,
+ post_number: 2,
+ children: [
+ {
+ id: 101,
+ post_number: 3,
+ children: [{ id: 102, post_number: 4 }],
+ },
+ { id: 103, post_number: 5 },
+ ],
+ };
+
+ const result = processNode(store, topic, nodeData);
+
+ assert.strictEqual(result.children.length, 2);
+ assert.strictEqual(result.children[0].post.id, 101);
+ assert.strictEqual(result.children[0].post.topic, topic);
+ assert.strictEqual(result.children[0].children.length, 1);
+ assert.strictEqual(result.children[0].children[0].post.id, 102);
+ assert.strictEqual(result.children[0].children[0].post.topic, topic);
+ assert.strictEqual(result.children[1].post.id, 103);
+ assert.strictEqual(result.children[1].children.length, 0);
+ });
+});
diff --git a/frontend/discourse/tests/unit/lib/url-test.js b/frontend/discourse/tests/unit/lib/url-test.js
index a0e96f375b9..dc3ac128130 100644
--- a/frontend/discourse/tests/unit/lib/url-test.js
+++ b/frontend/discourse/tests/unit/lib/url-test.js
@@ -2,7 +2,6 @@ import { setupTest } from "ember-qunit";
import { module, test } from "qunit";
import sinon from "sinon";
import { setPrefix } from "discourse/lib/get-url";
-import { withPluginApi } from "discourse/lib/plugin-api";
import DiscourseURL, {
getCanonicalUrl,
getCategoryAndTagUrl,
@@ -91,6 +90,7 @@ module("Unit | Utility | url", function (hooks) {
test("isInternalTopic", function (assert) {
sinon.stub(DiscourseURL, "origin").get(() => "https://eviltrout.com");
assert.true(DiscourseURL.isInternalTopic("https://eviltrout.com/t/123"));
+ assert.true(DiscourseURL.isInternalTopic("https://eviltrout.com/n/123"));
assert.false(DiscourseURL.isInternalTopic("https://eviltrout.com/admin"));
assert.false(DiscourseURL.isInternalTopic("https://eviltrout.com/u/test"));
assert.false(DiscourseURL.isInternalTopic("https://eviltrout.com/tamales"));
@@ -105,6 +105,9 @@ module("Unit | Utility | url", function (hooks) {
assert.true(
DiscourseURL.isInternalTopic("https://eviltrout.com/forum/t/123")
);
+ assert.true(
+ DiscourseURL.isInternalTopic("https://eviltrout.com/forum/n/123")
+ );
assert.false(
DiscourseURL.isInternalTopic("https://eviltrout.com/forum/admin")
);
@@ -193,75 +196,6 @@ module("Unit | Utility | url", function (hooks) {
);
});
- test("routeTo applies route-to-url value transformer", async function (assert) {
- sinon.stub(DiscourseURL, "origin").get(() => "http://example.com");
- sinon.stub(DiscourseURL, "handleURL");
- sinon.stub(DiscourseURL, "router").get(() => {
- return { currentURL: "/bar" };
- });
-
- withPluginApi((api) => {
- api.registerValueTransformer("route-to-url", ({ value }) => {
- if (value === "/t/some-topic/123") {
- return "/nested/some-topic/123";
- }
- return value;
- });
- });
-
- DiscourseURL.routeTo("/t/some-topic/123");
- assert.true(
- DiscourseURL.handleURL.calledWith("/nested/some-topic/123"),
- "the transformed URL is used for routing"
- );
- });
-
- test("routeTo passes untransformed URLs through", async function (assert) {
- sinon.stub(DiscourseURL, "origin").get(() => "http://example.com");
- sinon.stub(DiscourseURL, "handleURL");
- sinon.stub(DiscourseURL, "router").get(() => {
- return { currentURL: "/bar" };
- });
-
- withPluginApi((api) => {
- api.registerValueTransformer("route-to-url", ({ value }) => {
- if (value.startsWith("/t/redirect-me")) {
- return "/other/path";
- }
- return value;
- });
- });
-
- DiscourseURL.routeTo("/some/other/path");
- assert.true(
- DiscourseURL.handleURL.calledWith("/some/other/path"),
- "non-matching URLs pass through unchanged"
- );
- });
-
- test("routeTo aborts when transformer returns null", async function (assert) {
- sinon.stub(DiscourseURL, "origin").get(() => "http://example.com");
- sinon.stub(DiscourseURL, "handleURL");
- sinon.stub(DiscourseURL, "redirectTo");
- sinon.stub(DiscourseURL, "router").get(() => {
- return { currentURL: "/bar" };
- });
-
- withPluginApi((api) => {
- api.registerValueTransformer("route-to-url", () => null);
- });
-
- DiscourseURL.routeTo("/t/some-topic/123");
- assert.false(
- DiscourseURL.handleURL.called,
- "handleURL is not called when transformer returns null"
- );
- assert.false(
- DiscourseURL.redirectTo.called,
- "redirectTo is not called when transformer returns null"
- );
- });
-
test("prefixProtocol", async function (assert) {
assert.strictEqual(
prefixProtocol("mailto:[email protected]"),
diff --git a/frontend/discourse/tests/unit/models/topic-test.js b/frontend/discourse/tests/unit/models/topic-test.js
index dc7cb58fd48..2baabc96b89 100644
--- a/frontend/discourse/tests/unit/models/topic-test.js
+++ b/frontend/discourse/tests/unit/models/topic-test.js
@@ -106,6 +106,20 @@ module("Unit | Model | topic", function (hooks) {
assert.strictEqual(topic.lastUnreadUrl, "/t/hello/101/6");
});
+ test("nested view URLs omit post number", function (assert) {
+ const topic = this.store.createRecord("topic", {
+ id: 101,
+ highest_post_number: 10,
+ last_read_post_number: 5,
+ slug: "hello",
+ is_nested_view: true,
+ });
+
+ assert.strictEqual(topic.lastUnreadUrl, "/n/hello/101");
+ assert.strictEqual(topic.lastReadUrl, "/n/hello/101");
+ assert.strictEqual(topic.lastPostUrl, "/n/hello/101");
+ });
+
test("has details", function (assert) {
const topic = this.store.createRecord("topic", { id: 1234 });
const topicDetails = topic.details;
diff --git a/frontend/discourse/tests/unit/services/nested-view-cache-test.js b/frontend/discourse/tests/unit/services/nested-view-cache-test.js
new file mode 100644
index 00000000000..98a914a93cd
--- /dev/null
+++ b/frontend/discourse/tests/unit/services/nested-view-cache-test.js
@@ -0,0 +1,173 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import sinon from "sinon";
+
+module("Unit | Service | nested-view-cache", function (hooks) {
+ setupTest(hooks);
+
+ let clock;
+
+ hooks.afterEach(function () {
+ clock?.restore();
+ });
+
+ function getService(context) {
+ return context.owner.lookup("service:nested-view-cache");
+ }
+
+ test("save and get basic entry", function (assert) {
+ const cache = getService(this);
+ cache.save("key1", { data: "hello" });
+
+ const entry = cache.get("key1");
+ assert.strictEqual(entry.data, "hello");
+ assert.true(entry.timestamp > 0, "timestamp is set on save");
+ });
+
+ test("get returns null for missing key", function (assert) {
+ const cache = getService(this);
+ assert.strictEqual(cache.get("nonexistent"), null);
+ });
+
+ test("remove deletes an entry", function (assert) {
+ const cache = getService(this);
+ cache.save("key1", { data: "hello" });
+ cache.remove("key1");
+ assert.strictEqual(cache.get("key1"), null);
+ });
+
+ test("TTL expiration evicts stale entries on get", function (assert) {
+ clock = sinon.useFakeTimers({ now: Date.now(), shouldAdvanceTime: false });
+
+ const cache = getService(this);
+ cache.save("old", { data: "stale" });
+
+ clock.tick(11 * 60 * 1000);
+
+ assert.strictEqual(cache.get("old"), null);
+ });
+
+ test("entries within TTL are returned", function (assert) {
+ clock = sinon.useFakeTimers({ now: Date.now(), shouldAdvanceTime: false });
+
+ const cache = getService(this);
+ cache.save("fresh", { data: "valid" });
+
+ clock.tick(5 * 60 * 1000);
+
+ const entry = cache.get("fresh");
+ assert.strictEqual(entry.data, "valid");
+ });
+
+ test("evicts oldest entries when exceeding MAX_ENTRIES (15)", function (assert) {
+ clock = sinon.useFakeTimers({ now: Date.now(), shouldAdvanceTime: false });
+
+ const cache = getService(this);
+
+ for (let i = 0; i < 16; i++) {
+ cache.save(`key${i}`, { data: i });
+ clock.tick(1000);
+ }
+
+ assert.strictEqual(cache.get("key0"), null, "oldest entry is evicted");
+ assert.notStrictEqual(cache.get("key15"), null, "newest entry is kept");
+ });
+
+ test("evicts TTL-expired entries before size check", function (assert) {
+ clock = sinon.useFakeTimers({ now: Date.now(), shouldAdvanceTime: false });
+
+ const cache = getService(this);
+
+ for (let i = 0; i < 14; i++) {
+ cache.save(`expired${i}`, { data: i });
+ }
+
+ clock.tick(11 * 60 * 1000);
+
+ cache.save("fresh1", { data: "a" });
+ cache.save("fresh2", { data: "b" });
+
+ assert.notStrictEqual(cache.get("fresh1"), null, "fresh entries survive");
+ assert.notStrictEqual(cache.get("fresh2"), null, "fresh entries survive");
+
+ for (let i = 0; i < 14; i++) {
+ assert.strictEqual(
+ cache.get(`expired${i}`),
+ null,
+ `expired entry ${i} was evicted`
+ );
+ }
+ });
+
+ test("buildKey with topic ID only", function (assert) {
+ const cache = getService(this);
+ assert.strictEqual(cache.buildKey(42, {}), "42");
+ });
+
+ test("buildKey with sort param", function (assert) {
+ const cache = getService(this);
+ assert.strictEqual(cache.buildKey(42, { sort: "new" }), "42:s=new");
+ });
+
+ test("buildKey with post_number param", function (assert) {
+ const cache = getService(this);
+ assert.strictEqual(cache.buildKey(42, { post_number: 5 }), "42:p=5");
+ });
+
+ test("buildKey with all params", function (assert) {
+ const cache = getService(this);
+ assert.strictEqual(
+ cache.buildKey(42, { sort: "top", post_number: 5, context: 0 }),
+ "42:s=top:p=5:c=0"
+ );
+ });
+
+ test("buildKey includes context=0 (falsy but not null)", function (assert) {
+ const cache = getService(this);
+ assert.strictEqual(cache.buildKey(42, { context: 0 }), "42:c=0");
+ });
+
+ test("consumeTraversal returns true when useNextTransition was called", function (assert) {
+ const cache = getService(this);
+ cache.useNextTransition();
+ assert.true(cache.consumeTraversal());
+ });
+
+ test("consumeTraversal resets forceUseCache after consumption", function (assert) {
+ const cache = getService(this);
+ cache.useNextTransition();
+ cache.consumeTraversal();
+ assert.false(cache.consumeTraversal());
+ });
+
+ test("consumeTraversal returns true for popstate within 1s window", function (assert) {
+ const cache = getService(this);
+ window.dispatchEvent(new PopStateEvent("popstate"));
+ assert.true(cache.consumeTraversal());
+ });
+
+ test("consumeTraversal returns false for popstate older than 1s", function (assert) {
+ clock = sinon.useFakeTimers({ now: Date.now(), shouldAdvanceTime: false });
+
+ const cache = getService(this);
+ window.dispatchEvent(new PopStateEvent("popstate"));
+
+ clock.tick(1500);
+
+ assert.false(cache.consumeTraversal());
+ });
+
+ test("consumeTraversal returns false with no signals", function (assert) {
+ const cache = getService(this);
+ assert.false(cache.consumeTraversal());
+ });
+
+ test("consumeTraversal prefers forceUseCache over navigation type", function (assert) {
+ const cache = getService(this);
+ cache.useNextTransition();
+ assert.true(
+ cache.consumeTraversal(),
+ "forceUseCache wins even when nav type is push"
+ );
+ });
+});
diff --git a/lib/nested_replies.rb b/lib/nested_replies.rb
new file mode 100644
index 00000000000..79412d9d03f
--- /dev/null
+++ b/lib/nested_replies.rb
@@ -0,0 +1,10 @@
+# frozen_string_literal: true
+
+module NestedReplies
+end
+
+require_relative "nested_replies/ancestor_walker"
+require_relative "nested_replies/sort"
+require_relative "nested_replies/tree_loader"
+require_relative "nested_replies/post_preloader"
+require_relative "nested_replies/post_tree_serializer"
diff --git a/lib/nested_replies/ancestor_walker.rb b/lib/nested_replies/ancestor_walker.rb
new file mode 100644
index 00000000000..249397874f1
--- /dev/null
+++ b/lib/nested_replies/ancestor_walker.rb
@@ -0,0 +1,38 @@
+# frozen_string_literal: true
+
+module NestedReplies
+ # Walks the reply_to_post_number chain from `start_post_number` toward root
+ # in a single recursive CTE. Returns an array of result objects, each with
+ # .id, .post_number, .reply_to_post_number, and .depth (1 = start post).
+ def self.walk_ancestors(
+ topic_id:,
+ start_post_number:,
+ limit: 100,
+ exclude_deleted: true,
+ stop_at_op: false
+ )
+ deleted_seed = exclude_deleted ? "AND deleted_at IS NULL" : ""
+ deleted_recurse = exclude_deleted ? "AND p.deleted_at IS NULL" : ""
+ op_stop = stop_at_op ? "AND a.reply_to_post_number != 1" : ""
+
+ DB.query(<<~SQL, topic_id: topic_id, start: start_post_number, limit: limit)
+ WITH RECURSIVE ancestors AS (
+ SELECT id, post_number, reply_to_post_number, deleted_at, 1 AS depth
+ FROM posts
+ WHERE topic_id = :topic_id
+ AND post_number = :start
+ #{deleted_seed}
+ UNION ALL
+ SELECT p.id, p.post_number, p.reply_to_post_number, p.deleted_at, a.depth + 1
+ FROM posts p
+ JOIN ancestors a ON p.post_number = a.reply_to_post_number
+ WHERE p.topic_id = :topic_id
+ #{deleted_recurse}
+ AND a.reply_to_post_number IS NOT NULL
+ #{op_stop}
+ AND a.depth < :limit
+ )
+ SELECT id, post_number, reply_to_post_number, depth, deleted_at FROM ancestors
+ SQL
+ end
+end
diff --git a/lib/nested_replies/post_preloader.rb b/lib/nested_replies/post_preloader.rb
new file mode 100644
index 00000000000..ccf28450b83
--- /dev/null
+++ b/lib/nested_replies/post_preloader.rb
@@ -0,0 +1,105 @@
+# frozen_string_literal: true
+
+module NestedReplies
+ class PostPreloader
+ def initialize(topic_view:, topic:, current_user:, guardian:)
+ @topic_view = topic_view
+ @topic = topic
+ @current_user = current_user
+ @guardian = guardian
+ end
+
+ def prepare(posts)
+ user_ids = posts.map(&:user_id).compact.uniq
+
+ @topic_view.reset_post_collection(posts: PostsArray.new(posts))
+
+ allowed_post_fields = TopicView.allowed_post_custom_fields(@current_user, @topic)
+ @topic_view.post_custom_fields =
+ if allowed_post_fields.present?
+ Post.custom_fields_for_ids(posts.map(&:id).uniq, allowed_post_fields)
+ else
+ {}
+ end
+
+ allowed_user_fields = User.allowed_user_custom_fields(@guardian)
+ @topic_view.user_custom_fields =
+ if allowed_user_fields.present?
+ User.custom_fields_for_ids(user_ids, allowed_user_fields)
+ else
+ {}
+ end
+
+ TopicView.preload(@topic_view)
+ end
+
+ private
+
+ # Array subclass that handles ActiveRecord-style methods called by plugins'
+ # TopicView.on_preload hooks. The posts are already loaded with associations
+ # by TreeLoader, so we avoid re-querying. Explicitly handles the methods
+ # plugins actually use; unknown AR methods fall back to a real relation.
+ class PostsArray < Array
+ def includes(*associations)
+ ActiveRecord::Associations::Preloader.new(records: self, associations: associations).call
+ self
+ end
+
+ def pluck(*columns)
+ if columns.one?
+ map(&columns.first)
+ else
+ map { |record| columns.map { |col| record.public_send(col) } }
+ end
+ end
+
+ def where(conditions = nil, *rest)
+ return self if conditions.nil?
+ if conditions.is_a?(Hash) && rest.empty?
+ PostsArray.new(
+ select do |record|
+ conditions.all? do |k, v|
+ val = record.public_send(k)
+ v.is_a?(Array) ? v.include?(val) : val == v
+ end
+ end,
+ )
+ else
+ Post.where(id: map(&:id)).where(conditions, *rest)
+ end
+ end
+
+ def not(conditions = {})
+ if conditions.is_a?(Hash)
+ PostsArray.new(
+ reject do |record|
+ conditions.all? do |k, v|
+ val = record.public_send(k)
+ v.is_a?(Array) ? v.include?(val) : val == v
+ end
+ end,
+ )
+ else
+ Post.where(id: map(&:id)).where.not(conditions)
+ end
+ end
+
+ def respond_to_missing?(name, include_private = false)
+ Post.none.respond_to?(name, include_private) || super
+ end
+
+ def method_missing(name, *args, **kwargs, &block)
+ relation = Post.none
+ if relation.respond_to?(name)
+ Rails.logger.warn(
+ "NestedReplies::PostsArray falling back to DB query for .#{name} — " \
+ "consider adding an explicit handler",
+ )
+ Post.where(id: map(&:id)).public_send(name, *args, **kwargs, &block)
+ else
+ super
+ end
+ end
+ end
+ end
+end
diff --git a/lib/nested_replies/post_tree_serializer.rb b/lib/nested_replies/post_tree_serializer.rb
new file mode 100644
index 00000000000..9f141dfb94e
--- /dev/null
+++ b/lib/nested_replies/post_tree_serializer.rb
@@ -0,0 +1,61 @@
+# frozen_string_literal: true
+
+module NestedReplies
+ class PostTreeSerializer
+ def initialize(topic:, topic_view:, guardian:)
+ @topic = topic
+ @topic_view = topic_view
+ @guardian = guardian
+ end
+
+ def serialize_topic
+ serializer = TopicViewSerializer.new(@topic_view, scope: @guardian, root: false)
+ json = serializer.as_json
+ json.except(:post_stream, :timeline_lookup, :user_badges)
+ end
+
+ def serialize_post(post, reply_counts, descendant_counts = {})
+ # Assign the already-loaded topic to avoid an N+1 query per post
+ # in PostSerializer#topic, which reads object.topic.
+ post.topic = @topic
+ serializer = PostSerializer.new(post, scope: @guardian, root: false)
+ serializer.topic_view = @topic_view
+ json = serializer.as_json
+
+ json[:direct_reply_count] = reply_counts[post.post_number] || 0
+ json[:total_descendant_count] = descendant_counts[post.id] || 0
+
+ if post.deleted_at.present?
+ json[:deleted_post_placeholder] = true
+ unless @guardian.is_staff?
+ json[:cooked] = ""
+ json[:raw] = nil
+ json[:actions_summary] = []
+ json =
+ json.slice(
+ :id,
+ :post_number,
+ :reply_to_post_number,
+ :deleted_post_placeholder,
+ :cooked,
+ :raw,
+ :actions_summary,
+ :direct_reply_count,
+ :total_descendant_count,
+ )
+ end
+ end
+
+ json
+ end
+
+ def serialize_tree(post, children_map, reply_counts, descendant_counts = {})
+ node = serialize_post(post, reply_counts, descendant_counts)
+ children = children_map[post.post_number] || []
+ node[:children] = children.map do |child|
+ serialize_tree(child, children_map, reply_counts, descendant_counts)
+ end
+ node
+ end
+ end
+end
diff --git a/lib/nested_replies/sort.rb b/lib/nested_replies/sort.rb
new file mode 100644
index 00000000000..a6d7634c124
--- /dev/null
+++ b/lib/nested_replies/sort.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+module NestedReplies
+ module Sort
+ ALGORITHMS = %w[top new old].freeze
+
+ def self.sql_order_expression(algorithm)
+ raise ArgumentError, "Invalid sort algorithm: #{algorithm}" unless valid?(algorithm)
+
+ case algorithm
+ when "top"
+ "like_count DESC, post_number ASC"
+ when "new"
+ "created_at DESC"
+ when "old"
+ "post_number ASC"
+ end
+ end
+
+ def self.apply(scope, algorithm)
+ scope.order(Arel.sql(sql_order_expression(algorithm)))
+ end
+
+ def self.sort_in_memory(posts, algorithm)
+ raise ArgumentError, "Invalid sort algorithm: #{algorithm}" unless valid?(algorithm)
+
+ case algorithm
+ when "top"
+ posts.sort_by { |p| [-p.like_count, p.post_number] }
+ when "new"
+ posts.sort_by { |p| -p.created_at.to_i }
+ when "old"
+ posts.sort_by(&:post_number)
+ end
+ end
+
+ def self.valid?(algorithm)
+ ALGORITHMS.include?(algorithm)
+ end
+ end
+end
diff --git a/lib/nested_replies/tree_loader.rb b/lib/nested_replies/tree_loader.rb
new file mode 100644
index 00000000000..4f0eb7b6037
--- /dev/null
+++ b/lib/nested_replies/tree_loader.rb
@@ -0,0 +1,269 @@
+# frozen_string_literal: true
+
+module NestedReplies
+ class TreeLoader
+ PRELOAD_DEPTH = 3
+ ROOTS_PER_PAGE = 20
+ CHILDREN_PER_PAGE = 50
+ PRELOAD_CHILDREN_PER_PARENT = 3
+ SIBLINGS_PER_ANCESTOR = 5
+
+ POST_INCLUDES = [
+ { user: %i[primary_group flair_group] },
+ :reply_to_user,
+ :deleted_by,
+ :incoming_email,
+ :image_upload,
+ ].freeze
+
+ attr_reader :topic, :guardian
+
+ def initialize(topic:, guardian:)
+ @topic = topic
+ @guardian = guardian
+ end
+
+ def visible_post_types
+ @visible_post_types ||=
+ begin
+ types = [Post.types[:regular], Post.types[:moderator_action]]
+ types << Post.types[:whisper] if guardian.user&.whisperer?
+ types
+ end
+ end
+
+ def op_post
+ @op_post ||= load_posts_for_tree(topic.posts.where(post_number: 1)).first
+ end
+
+ def root_posts_scope(sort)
+ scope =
+ topic
+ .posts
+ .where("reply_to_post_number IS NULL OR reply_to_post_number = 1")
+ .where(post_number: 2..) # exclude OP itself
+ scope = apply_visibility(scope)
+ NestedReplies::Sort.apply(scope, sort)
+ end
+
+ def promote_pinned_roots(roots, pinned_post_ids)
+ return roots if pinned_post_ids.blank?
+
+ pinned_in_page = []
+ pinned_missing_ids = []
+
+ pinned_post_ids.each do |pid|
+ idx = roots.index { |p| p.id == pid }
+ if idx
+ pinned_in_page << roots.delete_at(idx) if roots[idx].deleted_at.nil?
+ else
+ pinned_missing_ids << pid
+ end
+ end
+
+ if pinned_missing_ids.present?
+ fetched =
+ load_posts_for_tree(apply_visibility(topic.posts.where(id: pinned_missing_ids))).index_by(
+ &:id
+ )
+ pinned_missing_ids.each do |pid|
+ post = fetched[pid]
+ pinned_in_page << post if post && post.deleted_at.nil?
+ end
+ end
+
+ pinned_in_page + roots
+ end
+
+ def load_posts_for_tree(scope)
+ scope = scope.includes(*POST_INCLUDES)
+ scope = scope.includes(:localizations) if SiteSetting.content_localization_enabled
+ scope = scope.includes({ user: :user_status }) if SiteSetting.enable_user_status
+ scope
+ end
+
+ def apply_visibility(scope)
+ scope = scope.unscope(where: :deleted_at)
+ scope = scope.where(post_type: visible_post_types)
+ scope
+ end
+
+ def batch_preload_tree(starting_posts, sort, max_depth:)
+ all_posts = starting_posts.dup
+ children_map = {}
+
+ current_level = starting_posts
+ max_depth.times do |depth|
+ break if current_level.empty?
+
+ parent_numbers = current_level.map(&:post_number)
+ last_level = (depth + 1 >= max_depth) || (depth + 1 >= configured_max_depth)
+
+ order_expr = NestedReplies::Sort.sql_order_expression(sort)
+ child_ids =
+ DB.query_single(
+ <<~SQL,
+ SELECT id FROM (
+ SELECT id,
+ ROW_NUMBER() OVER (PARTITION BY reply_to_post_number ORDER BY #{order_expr}) AS rn
+ FROM posts
+ WHERE topic_id = :topic_id
+ AND reply_to_post_number IN (:parent_numbers)
+ AND post_type IN (:post_types)
+ AND post_number > 1
+ ) ranked
+ WHERE rn <= :limit
+ SQL
+ topic_id: topic.id,
+ parent_numbers: parent_numbers,
+ limit: PRELOAD_CHILDREN_PER_PARENT,
+ post_types: visible_post_types,
+ )
+
+ break if child_ids.empty?
+
+ all_children = load_posts_for_tree(topic.posts.with_deleted.where(id: child_ids)).to_a
+
+ next_level = []
+ all_children
+ .group_by(&:reply_to_post_number)
+ .each do |parent_number, child_posts|
+ sorted = NestedReplies::Sort.sort_in_memory(child_posts, sort)
+ children_map[parent_number] = sorted
+ all_posts.concat(sorted)
+ next_level.concat(sorted) unless last_level
+ end
+
+ current_level = next_level
+ end
+
+ { children_map: children_map, all_posts: all_posts }
+ end
+
+ def batch_load_siblings(ancestors, sort)
+ root_ancestors, child_ancestors = ancestors.partition { |a| a.reply_to_post_number.nil? }
+
+ siblings_map = {}
+
+ if child_ancestors.present?
+ parent_numbers = child_ancestors.map(&:reply_to_post_number).uniq
+
+ order_expr = NestedReplies::Sort.sql_order_expression(sort)
+
+ visibility_conditions = +"post_type IN (:post_types) AND post_number > 1"
+ sql_params = {
+ topic_id: topic.id,
+ parent_numbers: parent_numbers,
+ limit: SIBLINGS_PER_ANCESTOR,
+ post_types: visible_post_types,
+ }
+
+ sibling_ids = DB.query_single(<<~SQL, **sql_params)
+ SELECT id FROM (
+ SELECT id, reply_to_post_number,
+ ROW_NUMBER() OVER (PARTITION BY reply_to_post_number ORDER BY #{order_expr}) AS rn
+ FROM posts
+ WHERE topic_id = :topic_id
+ AND reply_to_post_number IN (:parent_numbers)
+ AND #{visibility_conditions}
+ ) ranked
+ WHERE rn <= :limit
+ SQL
+
+ if sibling_ids.present?
+ loaded_siblings =
+ load_posts_for_tree(topic.posts.with_deleted.where(id: sibling_ids)).to_a
+ grouped = loaded_siblings.group_by(&:reply_to_post_number)
+
+ grouped.transform_values! { |posts| NestedReplies::Sort.sort_in_memory(posts, sort) }
+
+ child_ancestors.each do |ancestor|
+ siblings_map[ancestor.post_number] = grouped[ancestor.reply_to_post_number] || []
+ end
+ end
+ end
+
+ if root_ancestors.present?
+ root_siblings =
+ load_posts_for_tree(root_posts_scope(sort).limit(SIBLINGS_PER_ANCESTOR)).to_a
+ root_ancestors.each { |ancestor| siblings_map[ancestor.post_number] = root_siblings }
+ end
+
+ siblings_map
+ end
+
+ def flat_descendants_scope(parent_post_number, sort:, offset: 0, limit: CHILDREN_PER_PAGE)
+ post_types = visible_post_types
+ order_expr = NestedReplies::Sort.sql_order_expression(sort)
+
+ descendant_post_numbers =
+ DB.query_single(
+ <<~SQL,
+ WITH RECURSIVE descendants AS (
+ SELECT post_number, 1 AS depth
+ FROM posts
+ WHERE topic_id = :topic_id
+ AND reply_to_post_number = :parent_number
+ AND post_number > 1
+ UNION ALL
+ SELECT p.post_number, d.depth + 1
+ FROM posts p
+ JOIN descendants d ON p.reply_to_post_number = d.post_number
+ WHERE p.topic_id = :topic_id
+ AND p.post_number > 1
+ AND d.depth < :max_cte_depth
+ )
+ SELECT d.post_number
+ FROM descendants d
+ JOIN posts p ON p.post_number = d.post_number AND p.topic_id = :topic_id
+ WHERE p.post_type IN (:post_types)
+ ORDER BY #{order_expr}
+ OFFSET :offset
+ LIMIT :limit
+ SQL
+ topic_id: topic.id,
+ parent_number: parent_post_number,
+ post_types: post_types,
+ offset: offset,
+ limit: limit,
+ max_cte_depth: 500,
+ )
+
+ scope =
+ topic.posts.with_deleted.where(post_number: descendant_post_numbers).where(post_number: 2..)
+ NestedReplies::Sort.apply(scope, sort)
+ end
+
+ def configured_max_depth
+ SiteSetting.nested_replies_max_depth
+ end
+
+ def direct_reply_counts(post_numbers)
+ return {} if post_numbers.empty?
+
+ Post
+ .with_deleted
+ .where(topic_id: topic.id)
+ .where(reply_to_post_number: post_numbers)
+ .where(post_type: visible_post_types)
+ .group(:reply_to_post_number)
+ .count
+ end
+
+ def total_descendant_counts(post_ids)
+ return {} if post_ids.empty?
+
+ if guardian.user&.whisperer?
+ NestedViewPostStat
+ .where(post_id: post_ids.uniq)
+ .pluck(:post_id, :total_descendant_count)
+ .to_h
+ else
+ NestedViewPostStat
+ .where(post_id: post_ids.uniq)
+ .pluck(:post_id, Arel.sql("total_descendant_count - whisper_total_descendant_count"))
+ .to_h
+ end
+ end
+ end
+end
diff --git a/lib/svg_sprite.rb b/lib/svg_sprite.rb
index 8c6a8dffa99..13ad7c8f08b 100644
--- a/lib/svg_sprite.rb
+++ b/lib/svg_sprite.rb
@@ -213,6 +213,9 @@ module SvgSprite
minus
mobile-screen-button
moon
+ nested-circle-minus
+ nested-circle-plus
+ nested-thread
paintbrush
palette
paper-plane
diff --git a/lib/topic_query.rb b/lib/topic_query.rb
index e06cc7e24f6..b8c81e8adf3 100644
--- a/lib/topic_query.rb
+++ b/lib/topic_query.rb
@@ -819,6 +819,7 @@ class TopicQuery
# Start with a list of all topics
result = Topic.includes(:category)
+ result = result.includes(:nested_topic) if SiteSetting.nested_replies_enabled
if @user
result =
diff --git a/lib/topic_view.rb b/lib/topic_view.rb
index 42bb282c783..8a8f2dd74ed 100644
--- a/lib/topic_view.rb
+++ b/lib/topic_view.rb
@@ -17,6 +17,7 @@ class TopicView
memoize_for_posts :primary_group_names, :@group_names
memoize_for_posts :post_user_badges
memoize_for_posts :last_post
+ memoize_for_posts :preloaded_post_data_store
def self.on_preload(&blk)
(@preload ||= Set.new) << blk
@@ -60,6 +61,18 @@ class TopicView
:include_related,
)
+ # Generic store for plugins to stash per-post preloaded data (keyed by post_id)
+ # on the TopicView rather than on Post objects. Cleared automatically when the
+ # post collection changes via reset_post_collection.
+ def preloaded_post_data(namespace)
+ @preloaded_post_data_store&.dig(namespace)
+ end
+
+ def set_preloaded_post_data(namespace, data)
+ @preloaded_post_data_store ||= {}
+ @preloaded_post_data_store[namespace] = data
+ end
+
delegate :category, to: :topic, allow_nil: true, private: true
def self.print_chunk_size
@@ -530,11 +543,8 @@ class TopicView
end
def topic_user
- @topic_user ||=
- begin
- return nil if @user.blank?
- @topic.topic_users.find_by(user_id: @user.id)
- end
+ return @topic_user if instance_variable_defined?(:@topic_user)
+ @topic_user = @user.present? ? @topic.topic_users.find_by(user_id: @user.id) : nil
end
def has_bookmarks?
@@ -893,21 +903,17 @@ class TopicView
protected
def read_posts_set
- @read_posts_set ||=
- begin
- result = Set.new
- return result if @user.blank?
- return result if topic_user.blank?
-
- post_numbers =
- PostTiming
- .where(topic_id: @topic.id, user_id: @user.id)
- .where(post_number: @posts.pluck(:post_number))
- .pluck(:post_number)
-
- post_numbers.each { |pn| result << pn }
- result
- end
+ return @read_posts_set if instance_variable_defined?(:@read_posts_set)
+ result = Set.new
+ if @user.present? && topic_user.present?
+ post_numbers =
+ PostTiming
+ .where(topic_id: @topic.id, user_id: @user.id)
+ .where(post_number: @posts.pluck(:post_number))
+ .pluck(:post_number)
+ post_numbers.each { |pn| result << pn }
+ end
+ @read_posts_set = result
end
private
@@ -992,7 +998,11 @@ class TopicView
elsif SiteSetting.tagging_enabled
:tags
end
- Topic.with_deleted.includes(:category, tags_include).find_by(id: topic_or_topic_id)
+ nested_topic_include = :nested_topic if SiteSetting.nested_replies_enabled
+ Topic
+ .with_deleted
+ .includes(:category, nested_topic_include, tags_include)
+ .find_by(id: topic_or_topic_id)
end
def find_post_replies_ids(post_id)
diff --git a/plugins/discourse-reactions/lib/discourse_reactions/post_extension.rb b/plugins/discourse-reactions/lib/discourse_reactions/post_extension.rb
index 7d1f9d07579..6dd2923ff26 100644
--- a/plugins/discourse-reactions/lib/discourse_reactions/post_extension.rb
+++ b/plugins/discourse-reactions/lib/discourse_reactions/post_extension.rb
@@ -6,7 +6,7 @@ module DiscourseReactions::PostExtension
def self.prepended(base)
base.has_many :reactions, class_name: "DiscourseReactions::Reaction"
base.has_many :reactions_user, class_name: "DiscourseReactions::ReactionUser"
- base.attr_accessor :user_positively_reacted, :reaction_users_count
+ base.attr_accessor :user_positively_reacted, :reaction_users_count, :precomputed_reactions
end
def emoji_reactions
diff --git a/plugins/discourse-reactions/lib/discourse_reactions/posts_reaction_loader.rb b/plugins/discourse-reactions/lib/discourse_reactions/posts_reaction_loader.rb
index 79e88daebf4..39cae78f951 100644
--- a/plugins/discourse-reactions/lib/discourse_reactions/posts_reaction_loader.rb
+++ b/plugins/discourse-reactions/lib/discourse_reactions/posts_reaction_loader.rb
@@ -3,6 +3,8 @@
module DiscourseReactions::PostsReactionLoader
def posts_with_reactions
if SiteSetting.discourse_reactions_enabled
+ return if object.preloaded_post_data(:reactions)
+
posts = object.posts
ActiveRecord::Associations::Preloader.new(
diff --git a/plugins/discourse-reactions/plugin.rb b/plugins/discourse-reactions/plugin.rb
index ec694d4ef2a..9aa6a0df735 100644
--- a/plugins/discourse-reactions/plugin.rb
+++ b/plugins/discourse-reactions/plugin.rb
@@ -62,6 +62,103 @@ after_initialize do
Discourse::Application.routes.append { mount DiscourseReactions::Engine, at: "/" }
+ TopicView.on_preload do |topic_view|
+ next unless SiteSetting.discourse_reactions_enabled
+
+ posts = topic_view.posts
+ next if posts.blank?
+
+ ActiveRecord::Associations::Preloader.new(
+ records: posts,
+ associations: [:post_actions, { reactions: { reaction_users: :user } }],
+ ).call
+
+ post_ids = posts.map(&:id).uniq
+
+ reaction_users_count_map = TopicViewSerializer.posts_reaction_users_count(post_ids)
+ post_actions_with_reaction_users =
+ DiscourseReactions::TopicViewSerializerExtension.load_post_action_reaction_users_for_posts(
+ post_ids,
+ )
+
+ main_reaction = DiscourseReactions::Reaction.main_reaction_id
+ excluded = DiscourseReactions::Reaction.reactions_excluded_from_like
+
+ excluded_filter =
+ if excluded.present?
+ "AND dr.reaction_value NOT IN (:excluded)"
+ else
+ ""
+ end
+
+ sql_params = {
+ post_ids: post_ids,
+ like_type: PostActionType::LIKE_POST_ACTION_ID,
+ main_reaction: main_reaction,
+ }
+ sql_params[:excluded] = excluded if excluded.present?
+
+ likes_rows = DB.query(<<~SQL, **sql_params)
+ SELECT pa.post_id, COUNT(*) as likes_count
+ FROM post_actions pa
+ WHERE pa.deleted_at IS NULL
+ AND pa.post_id IN (:post_ids)
+ AND pa.post_action_type_id = :like_type
+ AND NOT EXISTS (
+ SELECT 1 FROM discourse_reactions_reaction_users dru
+ JOIN discourse_reactions_reactions dr ON dr.id = dru.reaction_id
+ WHERE dr.post_id = pa.post_id
+ AND dru.user_id = pa.user_id
+ AND dr.reaction_value != :main_reaction
+ #{excluded_filter}
+ )
+ AND NOT EXISTS (
+ SELECT 1 FROM discourse_reactions_reaction_users dru
+ JOIN discourse_reactions_reactions dr ON dr.id = dru.reaction_id
+ WHERE dr.post_id = pa.post_id
+ AND dru.user_id = pa.user_id
+ AND dr.reaction_value = :main_reaction
+ )
+ GROUP BY pa.post_id
+ SQL
+
+ likes_map = likes_rows.each_with_object({}) { |row, h| h[row.post_id] = row.likes_count }
+
+ precomputed_reactions_map = {}
+
+ posts.each do |post|
+ post.reaction_users_count = reaction_users_count_map[post.id].to_i
+ post.post_actions_with_reaction_users = post_actions_with_reaction_users[post.id] || {}
+
+ emoji_reactions = post.emoji_reactions.select { |r| r.reaction_users_count.to_i > 0 }
+
+ reactions =
+ emoji_reactions.map do |reaction|
+ {
+ id: reaction.reaction_value,
+ type: reaction.reaction_type.to_sym,
+ count: reaction.reaction_users_count,
+ }
+ end
+
+ likes = likes_map[post.id] || 0
+
+ if likes > 0
+ reaction_likes, reactions = reactions.partition { |r| r[:id] == main_reaction }
+ reactions << {
+ id: main_reaction,
+ type: :emoji,
+ count: likes + reaction_likes.sum { |r| r[:count] },
+ }
+ end
+
+ precomputed_reactions_map[post.id] = reactions.sort_by { |r| [-r[:count].to_i, r[:id]] }
+ end
+
+ topic_view.set_preloaded_post_data(:reactions, precomputed_reactions_map)
+ topic_view.set_preloaded_post_data(:reaction_users_count, reaction_users_count_map)
+ end
+
# Helper module for shared reactions serialization logic
module ReactionsSerializerHelpers
def self.reactions_for_post(post)
@@ -240,14 +337,26 @@ after_initialize do
end
end
- add_to_serializer(:post, :reactions) { ReactionsSerializerHelpers.reactions_for_post(object) }
+ add_to_serializer(:post, :reactions) do
+ map = topic_view&.preloaded_post_data(:reactions)
+ if map && map.key?(object.id)
+ map[object.id]
+ else
+ ReactionsSerializerHelpers.reactions_for_post(object)
+ end
+ end
add_to_serializer(:post, :current_user_reaction) do
ReactionsSerializerHelpers.current_user_reaction_for_post(object, scope)
end
add_to_serializer(:post, :reaction_users_count) do
- ReactionsSerializerHelpers.reaction_users_count_for_post(object)
+ map = topic_view&.preloaded_post_data(:reaction_users_count)
+ if map && map.key?(object.id)
+ map[object.id].to_i
+ else
+ ReactionsSerializerHelpers.reaction_users_count_for_post(object)
+ end
end
add_to_serializer(:post, :current_user_used_main_reaction) do
diff --git a/spec/fabricators/nested_topic_fabricator.rb b/spec/fabricators/nested_topic_fabricator.rb
new file mode 100644
index 00000000000..ca2b5c92dc7
--- /dev/null
+++ b/spec/fabricators/nested_topic_fabricator.rb
@@ -0,0 +1,3 @@
+# frozen_string_literal: true
+
+Fabricator(:nested_topic) { topic }
diff --git a/spec/jobs/scheduled/backfill_nested_reply_stats_spec.rb b/spec/jobs/scheduled/backfill_nested_reply_stats_spec.rb
new file mode 100644
index 00000000000..96d116a5bad
--- /dev/null
+++ b/spec/jobs/scheduled/backfill_nested_reply_stats_spec.rb
@@ -0,0 +1,192 @@
+# frozen_string_literal: true
+
+RSpec.describe Jobs::BackfillNestedReplyStats do
+ fab!(:topic)
+ fab!(:op) { Fabricate(:post, topic: topic, post_number: 1) }
+ fab!(:nested_topic) { Fabricate(:nested_topic, topic: topic) }
+
+ before { SiteSetting.nested_replies_enabled = true }
+
+ def execute
+ described_class.new.execute(nil)
+ end
+
+ it "does nothing when feature is disabled" do
+ SiteSetting.nested_replies_enabled = false
+ Fabricate(:post, topic: topic, reply_to_post_number: 1)
+
+ execute
+
+ expect(NestedViewPostStat.count).to eq(0)
+ end
+
+ it "computes direct_reply_count for a parent with replies" do
+ parent = Fabricate(:post, topic: topic, reply_to_post_number: 1)
+ 3.times { Fabricate(:post, topic: topic, reply_to_post_number: parent.post_number) }
+
+ NestedViewPostStat.delete_all
+ execute
+
+ stat = NestedViewPostStat.find_by(post_id: parent.id)
+ expect(stat.direct_reply_count).to eq(3)
+ end
+
+ it "computes total_descendant_count across multiple depths" do
+ root = Fabricate(:post, topic: topic, reply_to_post_number: 1)
+ child = Fabricate(:post, topic: topic, reply_to_post_number: root.post_number)
+ Fabricate(:post, topic: topic, reply_to_post_number: child.post_number)
+
+ NestedViewPostStat.delete_all
+ execute
+
+ stat = NestedViewPostStat.find_by(post_id: root.id)
+ expect(stat.direct_reply_count).to eq(1)
+ expect(stat.total_descendant_count).to eq(2)
+ end
+
+ it "tracks whisper counts separately" do
+ parent = Fabricate(:post, topic: topic, reply_to_post_number: 1)
+ Fabricate(:post, topic: topic, reply_to_post_number: parent.post_number)
+ Fabricate(
+ :post,
+ topic: topic,
+ reply_to_post_number: parent.post_number,
+ post_type: Post.types[:whisper],
+ )
+
+ NestedViewPostStat.delete_all
+ execute
+
+ stat = NestedViewPostStat.find_by(post_id: parent.id)
+ expect(stat.direct_reply_count).to eq(2)
+ expect(stat.whisper_direct_reply_count).to eq(1)
+ expect(stat.total_descendant_count).to eq(2)
+ expect(stat.whisper_total_descendant_count).to eq(1)
+ end
+
+ it "includes soft-deleted posts in stats" do
+ parent = Fabricate(:post, topic: topic, reply_to_post_number: 1)
+ Fabricate(:post, topic: topic, reply_to_post_number: parent.post_number)
+ Fabricate(
+ :post,
+ topic: topic,
+ reply_to_post_number: parent.post_number,
+ deleted_at: Time.current,
+ )
+
+ NestedViewPostStat.delete_all
+ execute
+
+ stat = NestedViewPostStat.find_by(post_id: parent.id)
+ expect(stat.direct_reply_count).to eq(2)
+ end
+
+ it "preserves higher live-incremented stats over backfill-computed values" do
+ parent = Fabricate(:post, topic: topic, reply_to_post_number: 1)
+ Fabricate(:post, topic: topic, reply_to_post_number: parent.post_number)
+
+ NestedViewPostStat.delete_all
+ NestedViewPostStat.create!(
+ post_id: parent.id,
+ direct_reply_count: 999,
+ total_descendant_count: 999,
+ whisper_direct_reply_count: 50,
+ whisper_total_descendant_count: 50,
+ )
+
+ execute
+
+ stat = NestedViewPostStat.find_by(post_id: parent.id)
+ expect(stat.direct_reply_count).to eq(999)
+ expect(stat.total_descendant_count).to eq(999)
+ expect(stat.whisper_direct_reply_count).to eq(50)
+ expect(stat.whisper_total_descendant_count).to eq(50)
+ end
+
+ it "updates stats when backfill computes higher values than existing" do
+ parent = Fabricate(:post, topic: topic, reply_to_post_number: 1)
+ 3.times { Fabricate(:post, topic: topic, reply_to_post_number: parent.post_number) }
+
+ NestedViewPostStat.delete_all
+ NestedViewPostStat.create!(post_id: parent.id, direct_reply_count: 1, total_descendant_count: 1)
+
+ execute
+
+ stat = NestedViewPostStat.find_by(post_id: parent.id)
+ expect(stat.direct_reply_count).to eq(3)
+ expect(stat.total_descendant_count).to eq(3)
+ end
+
+ it "processes multiple topics" do
+ other_topic = Fabricate(:topic)
+ Fabricate(:nested_topic, topic: other_topic)
+ other_op = Fabricate(:post, topic: other_topic, post_number: 1)
+ Fabricate(:post, topic: other_topic, reply_to_post_number: 1)
+
+ parent = Fabricate(:post, topic: topic, reply_to_post_number: 1)
+ Fabricate(:post, topic: topic, reply_to_post_number: parent.post_number)
+
+ NestedViewPostStat.delete_all
+ execute
+
+ expect(NestedViewPostStat.find_by(post_id: other_op.id).direct_reply_count).to eq(1)
+ expect(NestedViewPostStat.find_by(post_id: parent.id).direct_reply_count).to eq(1)
+ end
+
+ it "skips topics without a nested_topic record" do
+ non_nested_topic = Fabricate(:topic)
+ non_nested_op = Fabricate(:post, topic: non_nested_topic, post_number: 1)
+ Fabricate(:post, topic: non_nested_topic, reply_to_post_number: 1)
+
+ NestedViewPostStat.delete_all
+ execute
+
+ expect(NestedViewPostStat.find_by(post_id: non_nested_op.id)).to be_nil
+ end
+
+ it "inserts a zero-count sentinel row for the OP of a topic with no replies" do
+ NestedViewPostStat.delete_all
+
+ execute
+
+ stat = NestedViewPostStat.find_by(post_id: op.id)
+ expect(stat).to be_present
+ expect(stat.direct_reply_count).to eq(0)
+ expect(stat.total_descendant_count).to eq(0)
+ expect(stat.whisper_direct_reply_count).to eq(0)
+ expect(stat.whisper_total_descendant_count).to eq(0)
+ end
+
+ it "does not re-pick reply-less topics on subsequent runs" do
+ NestedViewPostStat.delete_all
+
+ execute
+ initial_updated_at = NestedViewPostStat.find_by(post_id: op.id).updated_at
+
+ freeze_time 1.hour.from_now
+ execute
+ expect(NestedViewPostStat.find_by(post_id: op.id).updated_at).to eq_time(initial_updated_at)
+ end
+
+ it "lets a later reply increment the sentinel row via ON CONFLICT" do
+ NestedViewPostStat.delete_all
+ execute
+
+ Fabricate(:post, topic: topic, reply_to_post_number: 1)
+
+ stat = NestedViewPostStat.find_by(post_id: op.id)
+ expect(stat.direct_reply_count).to eq(1)
+ expect(stat.total_descendant_count).to eq(1)
+ end
+
+ it "only picks up topics with missing stats" do
+ Fabricate(:post, topic: topic, reply_to_post_number: 1)
+
+ execute
+ initial_updated_at = NestedViewPostStat.find_by(post_id: op.id).updated_at
+
+ freeze_time 1.hour.from_now
+ execute
+ expect(NestedViewPostStat.find_by(post_id: op.id).updated_at).to eq_time(initial_updated_at)
+ end
+end
diff --git a/spec/lib/nested_replies/ancestor_walker_spec.rb b/spec/lib/nested_replies/ancestor_walker_spec.rb
new file mode 100644
index 00000000000..4278837e6af
--- /dev/null
+++ b/spec/lib/nested_replies/ancestor_walker_spec.rb
@@ -0,0 +1,132 @@
+# frozen_string_literal: true
+
+RSpec.describe NestedReplies do
+ fab!(:user)
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+
+ before { SiteSetting.nested_replies_enabled = true }
+
+ def build_chain(depth)
+ posts = [op]
+ depth.times do |i|
+ reply_to = posts.last.post_number
+ reply_to = nil if reply_to == 1
+ posts << Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ reply_to_post_number: reply_to,
+ )
+ end
+ posts
+ end
+
+ describe "basic walking" do
+ it "returns ancestors from start_post_number to root" do
+ chain = build_chain(4)
+ results =
+ NestedReplies.walk_ancestors(
+ topic_id: topic.id,
+ start_post_number: chain[4].reply_to_post_number,
+ )
+ expect(results).to be_an(Array)
+ expect(results.length).to be >= 1
+ expect(results.first.depth).to eq(1)
+ end
+
+ it "returns empty array when start post does not exist" do
+ results = NestedReplies.walk_ancestors(topic_id: topic.id, start_post_number: 99_999)
+ expect(results).to be_empty
+ end
+
+ it "respects the limit parameter" do
+ chain = build_chain(5)
+ results =
+ NestedReplies.walk_ancestors(
+ topic_id: topic.id,
+ start_post_number: chain.last.reply_to_post_number,
+ limit: 2,
+ )
+ expect(results.length).to be <= 2
+ end
+ end
+
+ describe "exclude_deleted option" do
+ it "skips deleted posts when exclude_deleted: true" do
+ chain = build_chain(3)
+ chain[2].update!(deleted_at: Time.current)
+
+ results =
+ NestedReplies.walk_ancestors(
+ topic_id: topic.id,
+ start_post_number: chain[3].reply_to_post_number,
+ exclude_deleted: true,
+ )
+ post_numbers = results.map(&:post_number)
+ expect(post_numbers).not_to include(chain[2].post_number)
+ end
+
+ it "includes deleted posts when exclude_deleted: false" do
+ chain = build_chain(3)
+ chain[2].update!(deleted_at: Time.current)
+
+ results =
+ NestedReplies.walk_ancestors(
+ topic_id: topic.id,
+ start_post_number: chain[3].reply_to_post_number,
+ exclude_deleted: false,
+ )
+ post_numbers = results.map(&:post_number)
+ expect(post_numbers).to include(chain[2].post_number)
+ end
+ end
+
+ describe "stop_at_op option" do
+ it "stops before OP when stop_at_op: true" do
+ reply_to_op = Fabricate(:post, topic: topic, user: user, reply_to_post_number: 1)
+ child =
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: reply_to_op.post_number)
+
+ results =
+ NestedReplies.walk_ancestors(
+ topic_id: topic.id,
+ start_post_number: child.reply_to_post_number,
+ stop_at_op: true,
+ )
+ post_numbers = results.map(&:post_number)
+ expect(post_numbers).to include(reply_to_op.post_number)
+ expect(post_numbers).not_to include(1)
+ end
+
+ it "includes OP when stop_at_op: false" do
+ reply_to_op = Fabricate(:post, topic: topic, user: user, reply_to_post_number: 1)
+ child =
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: reply_to_op.post_number)
+
+ results =
+ NestedReplies.walk_ancestors(
+ topic_id: topic.id,
+ start_post_number: child.reply_to_post_number,
+ stop_at_op: false,
+ )
+ post_numbers = results.map(&:post_number)
+ expect(post_numbers).to include(1)
+ end
+ end
+
+ describe "depth tracking" do
+ it "assigns correct depth values" do
+ chain = build_chain(3)
+ results =
+ NestedReplies.walk_ancestors(
+ topic_id: topic.id,
+ start_post_number: chain[3].reply_to_post_number,
+ )
+ expect(results.length).to eq(2)
+ result_by_depth = results.index_by(&:depth)
+ expect(result_by_depth[1].post_number).to eq(chain[2].post_number)
+ expect(result_by_depth[2].post_number).to eq(chain[1].post_number)
+ end
+ end
+end
diff --git a/spec/lib/nested_replies/nested_replies_n_plus_one_spec.rb b/spec/lib/nested_replies/nested_replies_n_plus_one_spec.rb
new file mode 100644
index 00000000000..7fd8602d1e9
--- /dev/null
+++ b/spec/lib/nested_replies/nested_replies_n_plus_one_spec.rb
@@ -0,0 +1,326 @@
+# frozen_string_literal: true
+
+RSpec.describe "Nested replies N+1 elimination", type: :request do
+ include NestedRepliesHelpers
+
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+
+ before { SiteSetting.nested_replies_enabled = true }
+
+ describe "no re-parenting on create" do
+ before do
+ SiteSetting.nested_replies_cap_nesting_depth = true
+ SiteSetting.nested_replies_max_depth = 3
+ end
+
+ it "preserves reply_to_post_number even at max depth" do
+ chain = create_reply_chain(depth: 4)
+ deep_reply =
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: chain.last.post_number)
+ expect(deep_reply.reply_to_post_number).to eq(chain.last.post_number)
+ end
+
+ it "preserves reply_to_post_number under max depth" do
+ SiteSetting.nested_replies_max_depth = 10
+ chain = create_reply_chain(depth: 3)
+ reply =
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: chain.last.post_number)
+ expect(reply.reply_to_post_number).to eq(chain.last.post_number)
+ end
+ end
+
+ describe "after_create stats increment" do
+ it "uses constant queries regardless of chain depth" do
+ chain_3 = create_reply_chain(depth: 3)
+ queries_3 =
+ track_sql_queries do
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: chain_3.last.post_number)
+ end
+
+ topic2 = Fabricate(:topic, user: user)
+ Fabricate(:post, topic: topic2, user: user, post_number: 1)
+ chain_10 = create_reply_chain(depth: 10, in_topic: topic2)
+ queries_10 =
+ track_sql_queries do
+ Fabricate(
+ :post,
+ topic: topic2,
+ user: user,
+ reply_to_post_number: chain_10.last.post_number,
+ )
+ end
+
+ stats_queries_3 = queries_3.count { |q| q.include?("nested_view_post_stats") }
+ stats_queries_10 = queries_10.count { |q| q.include?("nested_view_post_stats") }
+ expect(stats_queries_3).to eq(stats_queries_10)
+ end
+
+ it "increments direct_reply_count on parent only and total_descendant_count on all ancestors" do
+ chain = create_reply_chain(depth: 3)
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: chain.last.post_number)
+
+ chain.each(&:reload)
+
+ parent_stat = NestedViewPostStat.find_by(post_id: chain.last.id)
+ expect(parent_stat.direct_reply_count).to eq(1)
+ expect(parent_stat.total_descendant_count).to eq(1)
+
+ chain[0..-2].each do |ancestor|
+ stat = NestedViewPostStat.find_by(post_id: ancestor.id)
+ expect(stat).to be_present
+ expect(stat.direct_reply_count).to eq(0).or eq(1)
+ expect(stat.total_descendant_count).to be >= 1
+ end
+ end
+
+ it "tracks whisper counts separately from regular counts" do
+ chain = create_reply_chain(depth: 2)
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ reply_to_post_number: chain.last.post_number,
+ post_type: Post.types[:whisper],
+ )
+
+ parent_stat = NestedViewPostStat.find_by(post_id: chain.last.id)
+ expect(parent_stat.direct_reply_count).to eq(1)
+ expect(parent_stat.whisper_direct_reply_count).to eq(1)
+ expect(parent_stat.total_descendant_count).to eq(1)
+ expect(parent_stat.whisper_total_descendant_count).to eq(1)
+ end
+
+ it "does not increment whisper counts for regular posts" do
+ chain = create_reply_chain(depth: 2)
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: chain.last.post_number)
+
+ parent_stat = NestedViewPostStat.find_by(post_id: chain.last.id)
+ expect(parent_stat.direct_reply_count).to eq(1)
+ expect(parent_stat.whisper_direct_reply_count).to eq(0)
+ expect(parent_stat.total_descendant_count).to eq(1)
+ expect(parent_stat.whisper_total_descendant_count).to eq(0)
+ end
+
+ it "increments whisper counts on all ancestors" do
+ chain = create_reply_chain(depth: 3)
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ reply_to_post_number: chain.last.post_number,
+ post_type: Post.types[:whisper],
+ )
+
+ chain.each do |ancestor|
+ stat = NestedViewPostStat.find_by(post_id: ancestor.id)
+ next unless stat
+ expect(stat.whisper_total_descendant_count).to be >= 1
+ end
+ end
+ end
+
+ describe "after_destroy stats decrement" do
+ it "uses constant queries regardless of chain depth" do
+ chain_3 = create_reply_chain(depth: 3)
+ leaf_3 =
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: chain_3.last.post_number)
+ queries_3 = track_sql_queries { leaf_3.destroy! }
+
+ topic2 = Fabricate(:topic, user: user)
+ Fabricate(:post, topic: topic2, user: user, post_number: 1)
+ chain_10 = create_reply_chain(depth: 10, in_topic: topic2)
+ leaf_10 =
+ Fabricate(:post, topic: topic2, user: user, reply_to_post_number: chain_10.last.post_number)
+ queries_10 = track_sql_queries { leaf_10.destroy! }
+
+ stats_queries_3 = queries_3.count { |q| q.include?("nested_view_post_stats") }
+ stats_queries_10 = queries_10.count { |q| q.include?("nested_view_post_stats") }
+ expect(stats_queries_3).to eq(stats_queries_10)
+ end
+
+ it "clamps stats at zero" do
+ chain = create_reply_chain(depth: 2)
+ leaf =
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: chain.last.post_number)
+ leaf.destroy!
+
+ chain.each do |post|
+ stat = NestedViewPostStat.find_by(post_id: post.id)
+ next unless stat
+ expect(stat.total_descendant_count).to be >= 0
+ expect(stat.direct_reply_count).to be >= 0
+ end
+ end
+
+ it "cleans up the destroyed post's own stat row" do
+ chain = create_reply_chain(depth: 2)
+ leaf =
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: chain.last.post_number)
+ leaf_id = leaf.id
+ leaf.destroy!
+ expect(NestedViewPostStat.find_by(post_id: leaf_id)).to be_nil
+ end
+
+ it "decrements whisper counts when a whisper is destroyed" do
+ chain = create_reply_chain(depth: 2)
+ whisper =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ reply_to_post_number: chain.last.post_number,
+ post_type: Post.types[:whisper],
+ )
+
+ parent_stat = NestedViewPostStat.find_by(post_id: chain.last.id)
+ expect(parent_stat.whisper_direct_reply_count).to eq(1)
+ expect(parent_stat.whisper_total_descendant_count).to eq(1)
+
+ whisper.destroy!
+
+ parent_stat.reload
+ expect(parent_stat.direct_reply_count).to eq(0)
+ expect(parent_stat.whisper_direct_reply_count).to eq(0)
+ expect(parent_stat.total_descendant_count).to eq(0)
+ expect(parent_stat.whisper_total_descendant_count).to eq(0)
+ end
+
+ it "does not decrement whisper counts when a regular post is destroyed" do
+ chain = create_reply_chain(depth: 2)
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ reply_to_post_number: chain.last.post_number,
+ post_type: Post.types[:whisper],
+ )
+ regular =
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: chain.last.post_number)
+
+ regular.destroy!
+
+ parent_stat = NestedViewPostStat.find_by(post_id: chain.last.id)
+ expect(parent_stat.direct_reply_count).to eq(1)
+ expect(parent_stat.whisper_direct_reply_count).to eq(1)
+ end
+ end
+
+ describe "context endpoint" do
+ fab!(:admin)
+
+ def context_url(topic, post_number, context_depth: nil)
+ url = "/n/#{topic.slug}/#{topic.id}/context/#{post_number}.json"
+ url += "?context=#{context_depth}" if context_depth
+ url
+ end
+
+ it "uses constant queries regardless of ancestor depth" do
+ chain_3 = create_reply_chain(depth: 3)
+
+ sign_in(admin)
+
+ # Warm up
+ get context_url(topic, chain_3.last.post_number)
+ expect(response.status).to eq(200)
+
+ queries_3 = track_sql_queries { get context_url(topic, chain_3.last.post_number) }
+
+ topic2 = Fabricate(:topic, user: user)
+ Fabricate(:post, topic: topic2, user: user, post_number: 1)
+ chain_10 = create_reply_chain(depth: 10, in_topic: topic2)
+
+ # Warm up
+ get context_url(topic2, chain_10.last.post_number)
+
+ queries_10 = track_sql_queries { get context_url(topic2, chain_10.last.post_number) }
+
+ ancestor_queries_3 = queries_3.count { |q| q.include?("WITH RECURSIVE ancestors") }
+ ancestor_queries_10 = queries_10.count { |q| q.include?("WITH RECURSIVE ancestors") }
+ expect(ancestor_queries_3).to eq(ancestor_queries_10)
+ expect(ancestor_queries_3).to eq(1)
+ end
+
+ it "returns the correct ancestor chain" do
+ chain = create_reply_chain(depth: 5)
+ sign_in(admin)
+
+ get context_url(topic, chain.last.post_number)
+ expect(response.status).to eq(200)
+
+ json = response.parsed_body
+ ancestor_numbers = json["ancestor_chain"].map { |a| a["post_number"] }
+ expected = chain[0..-2].map(&:post_number)
+ expect(ancestor_numbers).to eq(expected)
+ end
+
+ it "respects context_depth parameter" do
+ chain = create_reply_chain(depth: 5)
+ sign_in(admin)
+
+ get context_url(topic, chain.last.post_number, context_depth: 2)
+ expect(response.status).to eq(200)
+
+ json = response.parsed_body
+ expect(json["ancestor_chain"].length).to eq(2)
+ end
+
+ it "preserves deleted ancestors as placeholders to keep chains intact" do
+ chain = create_reply_chain(depth: 4)
+ chain[1].update!(deleted_at: Time.current)
+
+ regular_user = Fabricate(:user)
+ sign_in(regular_user)
+ get context_url(topic, chain.last.post_number)
+ expect(response.status).to eq(200)
+
+ json = response.parsed_body
+ ancestor_numbers = json["ancestor_chain"].map { |a| a["post_number"] }
+ expect(ancestor_numbers).to include(chain[1].post_number)
+
+ deleted_ancestor =
+ json["ancestor_chain"].find { |a| a["post_number"] == chain[1].post_number }
+ expect(deleted_ancestor["deleted_post_placeholder"]).to eq(true)
+ end
+ end
+
+ describe "edge cases" do
+ it "handles reply to OP (no ancestors)" do
+ reply = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ expect(NestedViewPostStat.find_by(post_id: op.id)).to be_nil
+ end
+
+ it "handles reply to deleted parent gracefully" do
+ chain = create_reply_chain(depth: 2)
+ chain.last.update!(deleted_at: Time.current)
+
+ expect {
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: chain.last.post_number)
+ }.not_to raise_error
+ end
+
+ it "increments all ancestors including deleted intermediaries" do
+ chain = create_reply_chain(depth: 3)
+ grandparent = chain[0]
+ parent = chain[1]
+ child = chain[2]
+
+ grandparent_before =
+ NestedViewPostStat.find_by(post_id: grandparent.id).total_descendant_count
+ parent_before = NestedViewPostStat.find_by(post_id: parent.id).total_descendant_count
+
+ parent.update!(deleted_at: Time.current)
+
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: child.post_number)
+
+ expect(NestedViewPostStat.find_by(post_id: child.id).total_descendant_count).to eq(1)
+ expect(NestedViewPostStat.find_by(post_id: parent.id).total_descendant_count).to eq(
+ parent_before + 1,
+ )
+ expect(NestedViewPostStat.find_by(post_id: grandparent.id).total_descendant_count).to eq(
+ grandparent_before + 1,
+ )
+ end
+ end
+end
diff --git a/spec/lib/nested_replies/nested_replies_spec.rb b/spec/lib/nested_replies/nested_replies_spec.rb
new file mode 100644
index 00000000000..0e9eb9135fb
--- /dev/null
+++ b/spec/lib/nested_replies/nested_replies_spec.rb
@@ -0,0 +1,151 @@
+# frozen_string_literal: true
+
+RSpec.describe NestedReplies do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:category)
+ fab!(:nested_category) { Fabricate(:category, name: "Nested Category") }
+
+ before do
+ SiteSetting.nested_replies_enabled = true
+ nested_category.category_setting.update!(nested_replies_default: true)
+ end
+
+ describe "topic_created event" do
+ it "sets the nested field when category has nested default enabled" do
+ post =
+ PostCreator.create!(
+ user,
+ title: "Test nested topic in category",
+ raw: "This is a test topic in a nested category",
+ category: nested_category.id,
+ )
+
+ expect(post.topic.reload.nested_topic).to be_present
+ end
+
+ it "sets the nested field when global nested_replies_default is enabled" do
+ SiteSetting.nested_replies_default = true
+
+ post =
+ PostCreator.create!(
+ user,
+ title: "Test nested topic globally",
+ raw: "This is a test topic with global nested default",
+ category: category.id,
+ )
+
+ expect(post.topic.reload.nested_topic).to be_present
+ end
+
+ it "does not set the nested field for topics in regular categories" do
+ post =
+ PostCreator.create!(
+ user,
+ title: "Test normal topic",
+ raw: "This is a test topic in a regular category",
+ category: category.id,
+ )
+
+ expect(post.topic.reload.nested_topic).to be_nil
+ end
+
+ it "does not set the nested field when plugin is disabled" do
+ SiteSetting.nested_replies_enabled = false
+
+ post =
+ PostCreator.create!(
+ user,
+ title: "Test topic plugin disabled",
+ raw: "This is a test topic with plugin disabled",
+ category: nested_category.id,
+ )
+
+ expect(post.topic.reload.nested_topic).to be_nil
+ end
+
+ it "does not set the nested field for private messages" do
+ SiteSetting.nested_replies_default = true
+
+ post =
+ PostCreator.create!(
+ user,
+ title: "Test private message topic",
+ raw: "This is a private message that should not get nested",
+ archetype: Archetype.private_message,
+ target_usernames: [Fabricate(:user).username],
+ )
+
+ expect(post.topic.reload.nested_topic).to be_nil
+ end
+ end
+
+ describe "serialization" do
+ fab!(:topic) { Fabricate(:topic, user: user, category: nested_category) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+
+ before { Fabricate(:nested_topic, topic: topic) }
+
+ it "includes is_nested_view on TopicListItemSerializer" do
+ json = TopicListItemSerializer.new(topic, scope: Guardian.new(user), root: false).as_json
+
+ expect(json[:is_nested_view]).to eq(true)
+ end
+
+ it "includes is_nested_view on TopicViewSerializer" do
+ topic_view = TopicView.new(topic.id, user)
+ json = TopicViewSerializer.new(topic_view, scope: Guardian.new(user), root: false).as_json
+
+ expect(json[:is_nested_view]).to eq(true)
+ end
+
+ it "returns false for is_nested_view when not set" do
+ topic.nested_topic&.destroy!
+
+ topic_view = TopicView.new(topic.id, user)
+ json = TopicViewSerializer.new(topic_view, scope: Guardian.new(user), root: false).as_json
+
+ expect(json[:is_nested_view]).to eq(false)
+ end
+
+ context "when topic is a private message" do
+ fab!(:pm) { Fabricate(:private_message_topic, user: user) }
+ fab!(:pm_op) { Fabricate(:post, topic: pm, user: user, post_number: 1) }
+
+ before { Fabricate(:nested_topic, topic: pm) }
+
+ it "does not include is_nested_view on TopicViewSerializer" do
+ topic_view = TopicView.new(pm.id, user)
+ json = TopicViewSerializer.new(topic_view, scope: Guardian.new(user), root: false).as_json
+
+ expect(json).not_to have_key(:is_nested_view)
+ end
+
+ it "does not include is_nested_view on TopicListItemSerializer" do
+ json = TopicListItemSerializer.new(pm, scope: Guardian.new(user), root: false).as_json
+
+ expect(json).not_to have_key(:is_nested_view)
+ end
+ end
+
+ context "when nested_replies_default is enabled" do
+ before { SiteSetting.nested_replies_default = true }
+
+ it "returns true for is_nested_view even without a NestedTopic record" do
+ topic.nested_topic&.destroy!
+
+ topic_view = TopicView.new(topic.id, user)
+ json = TopicViewSerializer.new(topic_view, scope: Guardian.new(user), root: false).as_json
+
+ expect(json[:is_nested_view]).to eq(true)
+ end
+
+ it "returns true for is_nested_view on TopicListItemSerializer without a NestedTopic record" do
+ topic.nested_topic&.destroy!
+
+ json = TopicListItemSerializer.new(topic, scope: Guardian.new(user), root: false).as_json
+
+ expect(json[:is_nested_view]).to eq(true)
+ end
+ end
+ end
+end
diff --git a/spec/lib/nested_replies/sort_spec.rb b/spec/lib/nested_replies/sort_spec.rb
new file mode 100644
index 00000000000..e7ab9ee6ca3
--- /dev/null
+++ b/spec/lib/nested_replies/sort_spec.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+RSpec.describe NestedReplies::Sort do
+ describe ".valid?" do
+ it "accepts top, new, old" do
+ expect(described_class.valid?("top")).to eq(true)
+ expect(described_class.valid?("new")).to eq(true)
+ expect(described_class.valid?("old")).to eq(true)
+ end
+
+ it "rejects unknown algorithms" do
+ expect(described_class.valid?("random")).to eq(false)
+ expect(described_class.valid?("")).to eq(false)
+ end
+ end
+
+ describe ".sort_in_memory" do
+ let(:posts) do
+ [
+ Struct.new(:like_count, :post_number, :created_at).new(5, 2, 3.days.ago),
+ Struct.new(:like_count, :post_number, :created_at).new(1, 3, 1.day.ago),
+ Struct.new(:like_count, :post_number, :created_at).new(10, 4, 2.days.ago),
+ ]
+ end
+
+ it "sorts by top (like_count desc, post_number asc tiebreaker)" do
+ sorted = described_class.sort_in_memory(posts, "top")
+ expect(sorted.map(&:post_number)).to eq([4, 2, 3])
+ end
+
+ it "sorts by new (created_at desc)" do
+ sorted = described_class.sort_in_memory(posts, "new")
+ expect(sorted.map(&:post_number)).to eq([3, 4, 2])
+ end
+
+ it "sorts by old (post_number asc)" do
+ sorted = described_class.sort_in_memory(posts, "old")
+ expect(sorted.map(&:post_number)).to eq([2, 3, 4])
+ end
+
+ it "raises on invalid algorithm" do
+ expect { described_class.sort_in_memory(posts, "random") }.to raise_error(ArgumentError)
+ end
+ end
+
+ describe ".sql_order_expression" do
+ it "raises on invalid algorithm" do
+ expect { described_class.sql_order_expression("bogus") }.to raise_error(ArgumentError)
+ end
+ end
+end
diff --git a/spec/requests/api/schemas/json/category_create_response.json b/spec/requests/api/schemas/json/category_create_response.json
index af3b005330d..45730e1cf0e 100644
--- a/spec/requests/api/schemas/json/category_create_response.json
+++ b/spec/requests/api/schemas/json/category_create_response.json
@@ -218,6 +218,12 @@
"null"
]
},
+ "nested_replies_default": {
+ "type": [
+ "boolean",
+ "null"
+ ]
+ },
"topic_posting_review_mode": {
"type": "string"
},
diff --git a/spec/requests/api/schemas/json/category_update_response.json b/spec/requests/api/schemas/json/category_update_response.json
index ee54143f0d9..fb0955c0a09 100644
--- a/spec/requests/api/schemas/json/category_update_response.json
+++ b/spec/requests/api/schemas/json/category_update_response.json
@@ -221,6 +221,12 @@
"null"
]
},
+ "nested_replies_default": {
+ "type": [
+ "boolean",
+ "null"
+ ]
+ },
"topic_posting_review_mode": {
"type": "string"
},
diff --git a/spec/requests/nested_topics_controller_spec.rb b/spec/requests/nested_topics_controller_spec.rb
new file mode 100644
index 00000000000..dae8837bde1
--- /dev/null
+++ b/spec/requests/nested_topics_controller_spec.rb
@@ -0,0 +1,1127 @@
+# frozen_string_literal: true
+
+RSpec.describe NestedTopicsController, type: :request do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:admin)
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+
+ before { SiteSetting.nested_replies_enabled = true }
+
+ def show_url(topic, page: 0, sort: "top")
+ "/n/#{topic.slug}/#{topic.id}.json?page=#{page}&sort=#{sort}"
+ end
+
+ def children_url(topic, post_number, page: 0, sort: "top", depth: 1)
+ "/n/#{topic.slug}/#{topic.id}/children/#{post_number}.json?page=#{page}&sort=#{sort}&depth=#{depth}"
+ end
+
+ def context_url(topic, post_number, sort: "top", context: nil)
+ url = "/n/#{topic.slug}/#{topic.id}/context/#{post_number}.json?sort=#{sort}"
+ url += "&context=#{context}" if context
+ url
+ end
+
+ describe "GET respond" do
+ it "redirects crawlers to the flat topic view" do
+ get "/n/#{topic.slug}/#{topic.id}", headers: { "HTTP_USER_AGENT" => "Googlebot" }
+
+ expect(response).to redirect_to("/t/#{topic.slug}/#{topic.id}")
+ expect(response.status).to eq(301)
+ end
+
+ it "redirects crawlers to the flat topic view with post number" do
+ get "/n/#{topic.slug}/#{topic.id}/5", headers: { "HTTP_USER_AGENT" => "Googlebot" }
+
+ expect(response).to redirect_to("/t/#{topic.slug}/#{topic.id}/5")
+ expect(response.status).to eq(301)
+ end
+
+ it "returns 404 for anonymous users on private topics" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ private_topic = Fabricate(:topic, category: private_category)
+ Fabricate(:post, topic: private_topic, post_number: 1)
+
+ get "/n/#{private_topic.slug}/#{private_topic.id}"
+ expect(response.status).to eq(404)
+ end
+
+ it "redirects private messages to flat view" do
+ pm = Fabricate(:private_message_topic, user: user)
+ Fabricate(:post, topic: pm, user: user, post_number: 1)
+
+ sign_in(user)
+ get "/n/#{pm.slug}/#{pm.id}"
+
+ expect(response).to redirect_to("/t/#{pm.slug}/#{pm.id}")
+ expect(response.status).to eq(302)
+ end
+
+ it "redirects private messages to flat view with post number" do
+ pm = Fabricate(:private_message_topic, user: user)
+ Fabricate(:post, topic: pm, user: user, post_number: 1)
+
+ sign_in(user)
+ get "/n/#{pm.slug}/#{pm.id}/5"
+
+ expect(response).to redirect_to("/t/#{pm.slug}/#{pm.id}/5")
+ expect(response.status).to eq(302)
+ end
+ end
+
+ describe "GET show" do
+ it "returns 404 when plugin is disabled" do
+ SiteSetting.nested_replies_enabled = false
+ sign_in(user)
+ get show_url(topic)
+ expect(response.status).to eq(404)
+ end
+
+ it "redirects private messages to flat view" do
+ pm = Fabricate(:private_message_topic, user: user)
+ Fabricate(:post, topic: pm, user: user, post_number: 1)
+
+ sign_in(user)
+ get show_url(pm)
+
+ expect(response).to redirect_to("/t/#{pm.slug}/#{pm.id}")
+ end
+
+ it "returns 404 for anonymous users on private topics" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ private_topic = Fabricate(:topic, category: private_category)
+ Fabricate(:post, topic: private_topic, post_number: 1)
+ get show_url(private_topic)
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 for signed-in users who cannot see the topic" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ private_topic = Fabricate(:topic, category: private_category)
+ Fabricate(:post, topic: private_topic, post_number: 1)
+ sign_in(user)
+ get show_url(private_topic)
+ expect(response.status).to eq(404)
+ end
+
+ it "returns topic metadata and OP on initial load (page 0)" do
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ sign_in(user)
+
+ get show_url(topic, page: 0)
+ expect(response.status).to eq(200)
+
+ json = response.parsed_body
+ expect(json).to have_key("topic")
+ expect(json).to have_key("op_post")
+ expect(json).to have_key("sort")
+ expect(json).to have_key("message_bus_last_id")
+ expect(json["roots"].length).to eq(2)
+ expect(json["page"]).to eq(0)
+ end
+
+ it "does not include topic metadata on subsequent pages" do
+ 25.times { Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil) }
+ sign_in(user)
+
+ get show_url(topic, page: 1)
+ expect(response.status).to eq(200)
+
+ json = response.parsed_body
+ expect(json).not_to have_key("topic")
+ expect(json).not_to have_key("op_post")
+ expect(json["page"]).to eq(1)
+ end
+
+ it "paginates with has_more_roots" do
+ NestedReplies::TreeLoader::ROOTS_PER_PAGE.times do
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ end
+ sign_in(user)
+
+ get show_url(topic, page: 0)
+ json = response.parsed_body
+ expect(json["has_more_roots"]).to eq(true)
+ expect(json["roots"].length).to eq(NestedReplies::TreeLoader::ROOTS_PER_PAGE)
+ end
+
+ it "returns has_more_roots false on last page" do
+ 5.times { Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil) }
+ sign_in(user)
+
+ get show_url(topic, page: 0)
+ json = response.parsed_body
+ expect(json["has_more_roots"]).to eq(false)
+ end
+
+ it "validates sort parameter and falls back to default" do
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ sign_in(user)
+
+ get show_url(topic, sort: "invalid")
+ expect(response.status).to eq(200)
+ json = response.parsed_body
+ expect(json["sort"]).to eq(SiteSetting.nested_replies_default_sort)
+ end
+
+ it "uses site setting default when no sort param is provided" do
+ SiteSetting.nested_replies_default_sort = "old"
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ sign_in(user)
+
+ get "/n/#{topic.slug}/#{topic.id}.json"
+ json = response.parsed_body
+ expect(json["sort"]).to eq("old")
+ end
+
+ it "sorts by top (like_count desc)" do
+ low = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil, like_count: 1)
+ high = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil, like_count: 10)
+ sign_in(user)
+
+ get show_url(topic, sort: "top")
+ json = response.parsed_body
+ root_ids = json["roots"].map { |r| r["id"] }
+ expect(root_ids).to eq([high.id, low.id])
+ end
+
+ it "sorts by new (created_at desc)" do
+ old_post =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ reply_to_post_number: nil,
+ created_at: 2.days.ago,
+ )
+ new_post =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ reply_to_post_number: nil,
+ created_at: 1.hour.ago,
+ )
+ sign_in(user)
+
+ get show_url(topic, sort: "new")
+ json = response.parsed_body
+ root_ids = json["roots"].map { |r| r["id"] }
+ expect(root_ids).to eq([new_post.id, old_post.id])
+ end
+
+ it "sorts by old (post_number asc)" do
+ first = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ second = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ sign_in(user)
+
+ get show_url(topic, sort: "old")
+ json = response.parsed_body
+ root_ids = json["roots"].map { |r| r["id"] }
+ expect(root_ids).to eq([first.id, second.id])
+ end
+
+ it "preloads children in the response" do
+ root = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ child = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ sign_in(user)
+
+ get show_url(topic, sort: "top")
+ json = response.parsed_body
+ root_json = json["roots"].first
+ expect(root_json["children"]).to be_an(Array)
+ expect(root_json["children"].length).to eq(1)
+ expect(root_json["children"].first["id"]).to eq(child.id)
+ end
+
+ it "sorts preloaded children consistently with roots" do
+ root = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ low_child =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ reply_to_post_number: root.post_number,
+ like_count: 1,
+ )
+ high_child =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ reply_to_post_number: root.post_number,
+ like_count: 10,
+ )
+ sign_in(user)
+
+ get show_url(topic, sort: "top")
+ json = response.parsed_body
+ children_ids = json["roots"].first["children"].map { |c| c["id"] }
+ expect(children_ids).to eq([high_child.id, low_child.id])
+
+ get show_url(topic, sort: "old")
+ json = response.parsed_body
+ children_ids = json["roots"].first["children"].map { |c| c["id"] }
+ expect(children_ids).to eq([low_child.id, high_child.id])
+ end
+
+ it "includes direct_reply_count and total_descendant_count" do
+ root = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ sign_in(user)
+
+ get show_url(topic)
+ json = response.parsed_body
+ root_json = json["roots"].first
+ expect(root_json).to have_key("direct_reply_count")
+ expect(root_json["direct_reply_count"]).to eq(1)
+ end
+
+ describe "deleted post placeholders" do
+ it "shows deleted root as placeholder for non-staff" do
+ root = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ root.update!(deleted_at: Time.current)
+ sign_in(user)
+
+ get show_url(topic)
+ json = response.parsed_body
+ root_json = json["roots"].find { |r| r["id"] == root.id }
+ expect(root_json).to be_present
+ expect(root_json["deleted_post_placeholder"]).to eq(true)
+ expect(root_json["cooked"]).to eq("")
+ expect(root_json["raw"]).to be_nil
+ expect(root_json["actions_summary"]).to eq([])
+ end
+
+ it "preserves children under deleted root for non-staff" do
+ root = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ child = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ root.update!(deleted_at: Time.current)
+ sign_in(user)
+
+ get show_url(topic)
+ json = response.parsed_body
+ root_json = json["roots"].find { |r| r["id"] == root.id }
+ expect(root_json["children"]).to be_an(Array)
+ expect(root_json["children"].length).to eq(1)
+ expect(root_json["children"].first["id"]).to eq(child.id)
+ end
+
+ it "shows deleted root as placeholder for staff but preserves content" do
+ root = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ root.update!(deleted_at: Time.current)
+ sign_in(admin)
+
+ get show_url(topic)
+ json = response.parsed_body
+ root_json = json["roots"].find { |r| r["id"] == root.id }
+ expect(root_json).to be_present
+ expect(root_json["deleted_post_placeholder"]).to eq(true)
+ expect(root_json["cooked"]).to be_present
+ expect(root_json["cooked"]).not_to eq("")
+ end
+ end
+
+ describe "pinned replies" do
+ fab!(:low_post) do
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil, like_count: 1)
+ end
+ fab!(:high_post) do
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil, like_count: 10)
+ end
+
+ fab!(:nested_topic_record) { Fabricate(:nested_topic, topic: topic) }
+
+ def pin_posts(*posts)
+ nested_topic_record.update!(pinned_post_ids: posts.map(&:id))
+ end
+
+ it "places pinned replies first regardless of sort" do
+ pin_posts(low_post)
+ sign_in(user)
+
+ get show_url(topic, sort: "top")
+
+ json = response.parsed_body
+ root_ids = json["roots"].map { |r| r["id"] }
+ expect(root_ids.first).to eq(low_post.id)
+ expect(json["pinned_post_ids"]).to contain_exactly(low_post.id)
+ end
+
+ it "does not include pinned_post_ids when none are pinned" do
+ sign_in(user)
+
+ get show_url(topic, sort: "top")
+
+ json = response.parsed_body
+ expect(json).not_to have_key("pinned_post_ids")
+ end
+
+ it "fetches a pinned reply even when it would be on a later page" do
+ 19.times do
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil, like_count: 5)
+ end
+ pin_posts(low_post)
+ sign_in(user)
+
+ get show_url(topic, sort: "top")
+
+ json = response.parsed_body
+ root_ids = json["roots"].map { |r| r["id"] }
+ expect(root_ids.first).to eq(low_post.id)
+ end
+
+ it "does not promote a deleted post to pinned position" do
+ low_post.update!(deleted_at: Time.current)
+ pin_posts(low_post)
+ sign_in(user)
+
+ get show_url(topic, sort: "top")
+
+ json = response.parsed_body
+ root_ids = json["roots"].map { |r| r["id"] }
+ expect(root_ids.first).not_to eq(low_post.id)
+ end
+
+ it "ignores a pinned post_id that does not exist" do
+ nested_topic_record.update!(pinned_post_ids: [99_999])
+ sign_in(user)
+
+ get show_url(topic, sort: "top")
+
+ json = response.parsed_body
+ expect(response.status).to eq(200)
+ root_ids = json["roots"].map { |r| r["id"] }
+ expect(root_ids.first).to eq(high_post.id)
+ end
+
+ it "does not pin on subsequent pages" do
+ 25.times do
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil, like_count: 5)
+ end
+ pin_posts(low_post)
+ sign_in(user)
+
+ get show_url(topic, page: 1, sort: "top")
+
+ json = response.parsed_body
+ expect(json).not_to have_key("pinned_post_ids")
+ end
+
+ it "places multiple pinned replies first in pin order" do
+ pin_posts(low_post, high_post)
+ sign_in(user)
+
+ get show_url(topic, sort: "top")
+
+ json = response.parsed_body
+ root_ids = json["roots"].map { |r| r["id"] }
+ expect(root_ids[0]).to eq(low_post.id)
+ expect(root_ids[1]).to eq(high_post.id)
+ end
+ end
+ end
+
+ describe "PUT pin" do
+ fab!(:root_post) { Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil) }
+
+ before { Fabricate(:nested_topic, topic: topic) }
+
+ def pin_url(topic)
+ "/n/#{topic.slug}/#{topic.id}/pin.json"
+ end
+
+ it "returns 403 for non-staff users" do
+ sign_in(user)
+ put pin_url(topic), params: { post_id: root_post.id }
+ expect(response.status).to eq(403)
+ end
+
+ it "allows moderators to pin a post" do
+ sign_in(Fabricate(:moderator))
+ put pin_url(topic), params: { post_id: root_post.id }
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["pinned_post_ids"]).to contain_exactly(root_post.id)
+ end
+
+ it "allows staff to pin a post" do
+ sign_in(admin)
+ put pin_url(topic), params: { post_id: root_post.id }
+ expect(response.status).to eq(200)
+
+ json = response.parsed_body
+ expect(json["pinned_post_ids"]).to contain_exactly(root_post.id)
+
+ topic.reload
+ expect(topic.nested_topic.pinned_post_ids).to contain_exactly(root_post.id)
+ end
+
+ it "allows staff to unpin a post by toggling" do
+ topic.reload.nested_topic.update!(pinned_post_ids: [root_post.id])
+
+ sign_in(admin)
+ put pin_url(topic), params: { post_id: root_post.id }
+ expect(response.status).to eq(200)
+
+ json = response.parsed_body
+ expect(json["pinned_post_ids"]).to eq([])
+
+ topic.reload
+ expect(topic.nested_topic.pinned_post_ids).to eq([])
+ end
+
+ it "returns 404 for a nonexistent post_id" do
+ sign_in(admin)
+ put pin_url(topic), params: { post_id: 99_999 }
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 when no post_id is provided" do
+ sign_in(admin)
+ put pin_url(topic)
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 400 when pinning a non-root post" do
+ child_post =
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: root_post.post_number)
+
+ sign_in(admin)
+ put pin_url(topic), params: { post_id: child_post.id }
+ expect(response.status).to eq(400)
+ end
+
+ it "persists the pin so that roots returns it first" do
+ high_post =
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil, like_count: 10)
+
+ sign_in(admin)
+ put pin_url(topic), params: { post_id: root_post.id }
+ expect(response.status).to eq(200)
+
+ get show_url(topic, sort: "top")
+ json = response.parsed_body
+ root_ids = json["roots"].map { |r| r["id"] }
+ expect(root_ids.first).to eq(root_post.id)
+ expect(json["pinned_post_ids"]).to contain_exactly(root_post.id)
+ end
+
+ it "allows pinning multiple posts" do
+ second_root =
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil, like_count: 10)
+
+ sign_in(admin)
+ put pin_url(topic), params: { post_id: root_post.id }
+ expect(response.status).to eq(200)
+
+ put pin_url(topic), params: { post_id: second_root.id }
+ expect(response.status).to eq(200)
+
+ json = response.parsed_body
+ expect(json["pinned_post_ids"]).to contain_exactly(root_post.id, second_root.id)
+ end
+
+ it "rejects pinning when 10 posts are already pinned" do
+ posts = 10.times.map { Fabricate(:post, topic: topic, reply_to_post_number: nil) }
+ topic.nested_topic.update!(pinned_post_ids: posts.map(&:id))
+
+ extra = Fabricate(:post, topic: topic, reply_to_post_number: nil)
+ sign_in(admin)
+ put pin_url(topic), params: { post_id: extra.id }
+ expect(response.status).to eq(400)
+ end
+
+ it "lazily creates a NestedTopic record when nested_replies_default is on" do
+ topic.nested_topic.destroy!
+ SiteSetting.nested_replies_default = true
+
+ sign_in(admin)
+ put pin_url(topic), params: { post_id: root_post.id }
+ expect(response.status).to eq(200)
+
+ topic.reload
+ expect(topic.nested_topic).to be_present
+ expect(topic.nested_topic.pinned_post_ids).to contain_exactly(root_post.id)
+ end
+ end
+
+ describe "whisper visibility" do
+ before { SiteSetting.whispers_allowed_groups = "#{Group::AUTO_GROUPS[:staff]}" }
+
+ fab!(:whisper) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: admin,
+ reply_to_post_number: nil,
+ post_type: Post.types[:whisper],
+ )
+ end
+
+ it "excludes whispers for regular users" do
+ sign_in(user)
+ get show_url(topic)
+ json = response.parsed_body
+ root_ids = json["roots"].map { |r| r["id"] }
+ expect(root_ids).not_to include(whisper.id)
+ end
+
+ it "includes whispers for staff" do
+ sign_in(admin)
+ get show_url(topic)
+ json = response.parsed_body
+ root_ids = json["roots"].map { |r| r["id"] }
+ expect(root_ids).to include(whisper.id)
+ end
+
+ it "excludes whisper children for regular users" do
+ root = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ whisper_child =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: admin,
+ reply_to_post_number: root.post_number,
+ post_type: Post.types[:whisper],
+ )
+ sign_in(user)
+
+ get children_url(topic, root.post_number)
+ json = response.parsed_body
+ child_ids = json["children"].map { |c| c["id"] }
+ expect(child_ids).not_to include(whisper_child.id)
+ end
+
+ it "includes whisper children for staff" do
+ root = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ whisper_child =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: admin,
+ reply_to_post_number: root.post_number,
+ post_type: Post.types[:whisper],
+ )
+ sign_in(admin)
+
+ get children_url(topic, root.post_number)
+ json = response.parsed_body
+ child_ids = json["children"].map { |c| c["id"] }
+ expect(child_ids).to include(whisper_child.id)
+ end
+ end
+
+ describe "whisper reply count visibility" do
+ before { SiteSetting.whispers_allowed_groups = "#{Group::AUTO_GROUPS[:staff]}" }
+
+ it "excludes whisper from reply counts for regular users" do
+ root = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ Fabricate(
+ :post,
+ topic: topic,
+ user: admin,
+ reply_to_post_number: root.post_number,
+ post_type: Post.types[:whisper],
+ )
+ sign_in(user)
+
+ get show_url(topic)
+ json = response.parsed_body
+ root_json = json["roots"].find { |r| r["id"] == root.id }
+ expect(root_json["direct_reply_count"]).to eq(1)
+ expect(root_json["total_descendant_count"]).to eq(1)
+ end
+
+ it "includes whisper in reply counts for staff" do
+ root = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ Fabricate(
+ :post,
+ topic: topic,
+ user: admin,
+ reply_to_post_number: root.post_number,
+ post_type: Post.types[:whisper],
+ )
+ sign_in(admin)
+
+ get show_url(topic)
+ json = response.parsed_body
+ root_json = json["roots"].find { |r| r["id"] == root.id }
+ expect(root_json["direct_reply_count"]).to eq(2)
+ expect(root_json["total_descendant_count"]).to eq(2)
+ end
+ end
+
+ describe "GET children" do
+ fab!(:root) { Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil) }
+
+ it "returns children of a post" do
+ child1 = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ child2 = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ sign_in(user)
+
+ get children_url(topic, root.post_number)
+ expect(response.status).to eq(200)
+
+ json = response.parsed_body
+ expect(json["children"].length).to eq(2)
+ expect(json["page"]).to eq(0)
+ end
+
+ it "paginates children" do
+ 50.times do
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ end
+ sign_in(user)
+
+ get children_url(topic, root.post_number, page: 0)
+ json = response.parsed_body
+ expect(json["has_more"]).to eq(true)
+ expect(json["children"].length).to eq(50)
+ end
+
+ it "returns has_more false when fewer than page size" do
+ 3.times { Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number) }
+ sign_in(user)
+
+ get children_url(topic, root.post_number)
+ json = response.parsed_body
+ expect(json["has_more"]).to eq(false)
+ end
+
+ describe "sorting" do
+ it "sorts children by top (like_count desc)" do
+ low =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ reply_to_post_number: root.post_number,
+ like_count: 1,
+ )
+ high =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ reply_to_post_number: root.post_number,
+ like_count: 10,
+ )
+ sign_in(user)
+
+ get children_url(topic, root.post_number, sort: "top")
+ json = response.parsed_body
+ child_ids = json["children"].map { |c| c["id"] }
+ expect(child_ids).to eq([high.id, low.id])
+ end
+
+ it "sorts children by new (created_at desc)" do
+ old_child =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ reply_to_post_number: root.post_number,
+ created_at: 2.days.ago,
+ )
+ new_child =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ reply_to_post_number: root.post_number,
+ created_at: 1.hour.ago,
+ )
+ sign_in(user)
+
+ get children_url(topic, root.post_number, sort: "new")
+ json = response.parsed_body
+ child_ids = json["children"].map { |c| c["id"] }
+ expect(child_ids).to eq([new_child.id, old_child.id])
+ end
+
+ it "sorts children by old (post_number asc)" do
+ first = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ second = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ sign_in(user)
+
+ get children_url(topic, root.post_number, sort: "old")
+ json = response.parsed_body
+ child_ids = json["children"].map { |c| c["id"] }
+ expect(child_ids).to eq([first.id, second.id])
+ end
+
+ it "respects sort at max nesting depth" do
+ SiteSetting.nested_replies_max_depth = 2
+ child = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ low_grandchild =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ reply_to_post_number: child.post_number,
+ like_count: 1,
+ )
+ high_grandchild =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ reply_to_post_number: child.post_number,
+ like_count: 10,
+ )
+ sign_in(user)
+
+ get children_url(topic, child.post_number, sort: "top", depth: 2)
+ json = response.parsed_body
+ child_ids = json["children"].map { |c| c["id"] }
+ expect(child_ids).to eq([high_grandchild.id, low_grandchild.id])
+ end
+
+ it "sorts flattened descendants when cap is enabled" do
+ SiteSetting.nested_replies_cap_nesting_depth = true
+ SiteSetting.nested_replies_max_depth = 2
+ child = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ low_gc =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ reply_to_post_number: child.post_number,
+ like_count: 1,
+ )
+ high_gc =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ reply_to_post_number: child.post_number,
+ like_count: 10,
+ )
+ sign_in(user)
+
+ get children_url(topic, child.post_number, sort: "top", depth: 2)
+ json = response.parsed_body
+ child_ids = json["children"].map { |c| c["id"] }
+ expect(child_ids).to eq([high_gc.id, low_gc.id])
+ end
+ end
+
+ it "flattens descendants at max depth when cap is enabled" do
+ SiteSetting.nested_replies_cap_nesting_depth = true
+ SiteSetting.nested_replies_max_depth = 2
+ child = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ grandchild =
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: child.post_number)
+ sign_in(user)
+
+ get children_url(topic, child.post_number, depth: 2)
+ json = response.parsed_body
+ child_json = json["children"].find { |c| c["id"] == grandchild.id }
+ expect(child_json).to be_present
+ expect(child_json["children"]).to eq([])
+ end
+
+ it "paginates flattened descendants inside the CTE" do
+ SiteSetting.nested_replies_cap_nesting_depth = true
+ SiteSetting.nested_replies_max_depth = 2
+ child = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ grandchildren =
+ 3.times.map do
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: child.post_number)
+ end
+ sign_in(user)
+
+ stub_const(NestedReplies::TreeLoader, :CHILDREN_PER_PAGE, 2) do
+ get children_url(topic, child.post_number, depth: 2, page: 0)
+ page0 = response.parsed_body
+ expect(page0["children"].length).to eq(2)
+ expect(page0["has_more"]).to eq(true)
+
+ get children_url(topic, child.post_number, depth: 2, page: 1)
+ page1 = response.parsed_body
+ expect(page1["children"].length).to eq(1)
+
+ all_ids = page0["children"].map { |c| c["id"] } + page1["children"].map { |c| c["id"] }
+ expect(all_ids).to match_array(grandchildren.map(&:id))
+ end
+ end
+
+ describe "deleted post placeholders" do
+ it "shows deleted child as placeholder for non-staff" do
+ child = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ child.update!(deleted_at: Time.current)
+ sign_in(user)
+
+ get children_url(topic, root.post_number)
+ json = response.parsed_body
+ child_json = json["children"].find { |c| c["id"] == child.id }
+ expect(child_json).to be_present
+ expect(child_json["deleted_post_placeholder"]).to eq(true)
+ expect(child_json["cooked"]).to eq("")
+ expect(child_json["raw"]).to be_nil
+ expect(child_json["actions_summary"]).to eq([])
+ end
+
+ it "preserves children of a deleted post" do
+ child = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ grandchild =
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: child.post_number)
+ child.update!(deleted_at: Time.current)
+ sign_in(user)
+
+ get children_url(topic, root.post_number)
+ json = response.parsed_body
+ child_json = json["children"].find { |c| c["id"] == child.id }
+ expect(child_json).to be_present
+ expect(child_json["deleted_post_placeholder"]).to eq(true)
+ expect(child_json["children"]).to be_an(Array)
+ expect(child_json["children"].length).to eq(1)
+ expect(child_json["children"].first["id"]).to eq(grandchild.id)
+ end
+
+ it "shows deleted child as placeholder for staff but preserves content" do
+ child = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ child.update!(deleted_at: Time.current)
+ sign_in(admin)
+
+ get children_url(topic, root.post_number)
+ json = response.parsed_body
+ child_json = json["children"].find { |c| c["id"] == child.id }
+ expect(child_json).to be_present
+ expect(child_json["deleted_post_placeholder"]).to eq(true)
+ expect(child_json["cooked"]).to be_present
+ expect(child_json["cooked"]).not_to eq("")
+ end
+ end
+
+ it "returns 404 when plugin is disabled" do
+ SiteSetting.nested_replies_enabled = false
+ sign_in(user)
+ get children_url(topic, root.post_number)
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 for unauthorized topic" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ private_topic = Fabricate(:topic, category: private_category)
+ Fabricate(:post, topic: private_topic, post_number: 1)
+ private_root = Fabricate(:post, topic: private_topic, reply_to_post_number: nil)
+ sign_in(user)
+ get children_url(private_topic, private_root.post_number)
+ expect(response.status).to eq(404)
+ end
+ end
+
+ describe "GET context" do
+ it "returns ancestor chain, target post, and siblings" do
+ chain = [op]
+ 3.times do |i|
+ reply_to = i == 0 ? nil : chain.last.post_number
+ chain << Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ reply_to_post_number: reply_to,
+ )
+ end
+ target = chain.last
+ sign_in(user)
+
+ get context_url(topic, target.post_number)
+ expect(response.status).to eq(200)
+
+ json = response.parsed_body
+ expect(json).to have_key("topic")
+ expect(json).to have_key("op_post")
+ expect(json).to have_key("ancestor_chain")
+ expect(json).to have_key("siblings")
+ expect(json).to have_key("target_post")
+ expect(json).to have_key("message_bus_last_id")
+ end
+
+ it "returns empty ancestors when context=0" do
+ root = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ child = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ sign_in(user)
+
+ get context_url(topic, child.post_number, context: 0)
+ json = response.parsed_body
+ expect(json["ancestor_chain"]).to be_empty
+ end
+
+ it "returns 404 for nonexistent post_number" do
+ sign_in(user)
+ get context_url(topic, 99_999)
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 when plugin disabled" do
+ SiteSetting.nested_replies_enabled = false
+ root = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ sign_in(user)
+ get context_url(topic, root.post_number)
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 for unauthorized topic" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ private_topic = Fabricate(:topic, category: private_category)
+ Fabricate(:post, topic: private_topic, post_number: 1)
+ root = Fabricate(:post, topic: private_topic, reply_to_post_number: nil)
+ sign_in(user)
+ get context_url(private_topic, root.post_number)
+ expect(response.status).to eq(404)
+ end
+
+ it "includes target post children" do
+ root = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ child = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ sign_in(user)
+
+ get context_url(topic, root.post_number)
+ json = response.parsed_body
+ expect(json["target_post"]["children"]).to be_an(Array)
+ expect(json["target_post"]["children"].length).to eq(1)
+ end
+
+ describe "deleted post placeholders" do
+ it "shows deleted ancestor as placeholder for non-staff" do
+ root = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ child = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ grandchild =
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: child.post_number)
+ child.update!(deleted_at: Time.current)
+ sign_in(user)
+
+ get context_url(topic, grandchild.post_number)
+ json = response.parsed_body
+ ancestor = json["ancestor_chain"].find { |a| a["id"] == child.id }
+ expect(ancestor).to be_present
+ expect(ancestor["deleted_post_placeholder"]).to eq(true)
+ expect(ancestor["cooked"]).to eq("")
+ expect(ancestor["raw"]).to be_nil
+ expect(ancestor["actions_summary"]).to eq([])
+ end
+
+ it "preserves tree structure through deleted ancestors" do
+ root = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ child = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ grandchild =
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: child.post_number)
+ child.update!(deleted_at: Time.current)
+ sign_in(user)
+
+ get context_url(topic, grandchild.post_number)
+ json = response.parsed_body
+ expect(json["ancestor_chain"].map { |a| a["id"] }).to include(child.id)
+ expect(json["target_post"]["id"]).to eq(grandchild.id)
+ end
+
+ it "shows deleted ancestor as placeholder for staff but preserves content" do
+ root = Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
+ child = Fabricate(:post, topic: topic, user: user, reply_to_post_number: root.post_number)
+ grandchild =
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: child.post_number)
+ child.update!(deleted_at: Time.current)
+ sign_in(admin)
+
+ get context_url(topic, grandchild.post_number)
+ json = response.parsed_body
+ ancestor = json["ancestor_chain"].find { |a| a["id"] == child.id }
+ expect(ancestor).to be_present
+ expect(ancestor["deleted_post_placeholder"]).to eq(true)
+ expect(ancestor["cooked"]).to be_present
+ expect(ancestor["cooked"]).not_to eq("")
+ end
+ end
+ end
+
+ describe "PUT toggle" do
+ def toggle_url(topic)
+ "/n/#{topic.slug}/#{topic.id}/toggle.json"
+ end
+
+ it "returns 403 for non-staff users" do
+ sign_in(user)
+ put toggle_url(topic), params: { enabled: true }
+ expect(response.status).to eq(403)
+ end
+
+ it "allows moderators to toggle nested view" do
+ sign_in(Fabricate(:moderator))
+ put toggle_url(topic), params: { enabled: true }
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["is_nested_view"]).to eq(true)
+ end
+
+ it "allows staff to enable nested view" do
+ sign_in(admin)
+ put toggle_url(topic), params: { enabled: true }
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["is_nested_view"]).to eq(true)
+
+ topic.reload
+ expect(topic.reload.nested_topic).to be_present
+ end
+
+ it "allows staff to disable nested view" do
+ Fabricate(:nested_topic, topic: topic)
+
+ sign_in(admin)
+ put toggle_url(topic), params: { enabled: false }
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["is_nested_view"]).to eq(false)
+
+ topic.reload
+ expect(topic.reload.nested_topic).to be_nil
+ end
+
+ it "returns 404 for private messages" do
+ pm = Fabricate(:private_message_topic, user: admin)
+ Fabricate(:post, topic: pm, user: admin, post_number: 1)
+
+ sign_in(admin)
+ put toggle_url(pm), params: { enabled: true }
+ expect(response.status).to eq(404)
+ end
+ end
+
+ describe "visit tracking" do
+ fab!(:root_reply) { Fabricate(:post, topic: topic, user: user) }
+
+ it "tracks a visit on show" do
+ sign_in(user)
+ get show_url(topic), params: { track_visit: true }
+ expect(response.status).to eq(200)
+
+ Scheduler::Defer.do_all_work
+
+ expect(TopicUser.find_by(topic: topic, user: user).first_visited_at).to be_present
+ expect(TopicViewItem.exists?(topic_id: topic.id, user_id: user.id)).to eq(true)
+ end
+
+ it "tracks a visit on context" do
+ sign_in(user)
+ get context_url(topic, root_reply.post_number), params: { track_visit: true }
+ expect(response.status).to eq(200)
+
+ Scheduler::Defer.do_all_work
+
+ expect(TopicUser.find_by(topic: topic, user: user).first_visited_at).to be_present
+ expect(TopicViewItem.exists?(topic_id: topic.id, user_id: user.id)).to eq(true)
+ end
+
+ it "does not track a user visit for anonymous users" do
+ topic_user_count = TopicUser.count
+
+ get show_url(topic)
+ expect(response.status).to eq(200)
+ Scheduler::Defer.do_all_work
+
+ expect(TopicUser.count).to eq(topic_user_count)
+ end
+ end
+end
diff --git a/spec/requests/topics_controller_spec.rb b/spec/requests/topics_controller_spec.rb
index 5a2c1d8e3e5..e08e937a30e 100644
--- a/spec/requests/topics_controller_spec.rb
+++ b/spec/requests/topics_controller_spec.rb
@@ -2975,6 +2975,37 @@ RSpec.describe TopicsController do
expect(response).to redirect_to(topic.relative_url)
end
+ it "redirects to nested view when nested_replies_default is enabled" do
+ SiteSetting.nested_replies_enabled = true
+ SiteSetting.nested_replies_default = true
+
+ get "/t/#{topic.slug}/#{topic.id}"
+
+ expect(response).to redirect_to("/n/#{topic.slug}/#{topic.id}")
+ end
+
+ it "does not redirect crawlers to nested view" do
+ SiteSetting.nested_replies_enabled = true
+ SiteSetting.nested_replies_default = true
+
+ get "/t/#{topic.slug}/#{topic.id}", headers: { "HTTP_USER_AGENT" => "Googlebot" }
+
+ expect(response.status).to eq(200)
+ expect(response.body).to have_tag(:body, with: { class: "crawler" })
+ end
+
+ it "does not redirect private messages to nested view" do
+ SiteSetting.nested_replies_enabled = true
+ SiteSetting.nested_replies_default = true
+ pm = Fabricate(:private_message_topic, user: user)
+ Fabricate(:post, topic: pm, user: user)
+
+ sign_in(user)
+ get "/t/#{pm.slug}/#{pm.id}"
+
+ expect(response).not_to redirect_to("/n/#{pm.slug}/#{pm.id}")
+ end
+
it "returns 404 when an invalid slug is given and no id" do
get "/t/nope-nope.json"
diff --git a/spec/serializers/current_user_serializer_spec.rb b/spec/serializers/current_user_serializer_spec.rb
index 54cab2b2966..8e6b5df5519 100644
--- a/spec/serializers/current_user_serializer_spec.rb
+++ b/spec/serializers/current_user_serializer_spec.rb
@@ -459,4 +459,28 @@ RSpec.describe CurrentUserSerializer do
expect(payload).not_to have_key(:show_site_owner_onboarding)
end
end
+
+ describe "#can_toggle_nested_mode" do
+ it "is not included when nested replies is disabled" do
+ SiteSetting.nested_replies_enabled = false
+ expect(serializer.as_json).not_to have_key(:can_toggle_nested_mode)
+ end
+
+ context "when nested replies is enabled" do
+ before { SiteSetting.nested_replies_enabled = true }
+
+ it "is true when user is in an allowed group" do
+ SiteSetting.nested_replies_toggle_mode_groups = Group::AUTO_GROUPS[:staff].to_s
+ user.update!(admin: true)
+ Group.refresh_automatic_groups!
+ user.reload
+ expect(serializer.as_json[:can_toggle_nested_mode]).to eq(true)
+ end
+
+ it "is false when user is not in an allowed group" do
+ SiteSetting.nested_replies_toggle_mode_groups = Group::AUTO_GROUPS[:staff].to_s
+ expect(serializer.as_json[:can_toggle_nested_mode]).to eq(false)
+ end
+ end
+ end
end
diff --git a/spec/serializers/nested_replies_basic_category_serializer_spec.rb b/spec/serializers/nested_replies_basic_category_serializer_spec.rb
new file mode 100644
index 00000000000..e6ea4e3c9f7
--- /dev/null
+++ b/spec/serializers/nested_replies_basic_category_serializer_spec.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+RSpec.describe CategorySerializer do
+ fab!(:category)
+ fab!(:admin)
+
+ before { SiteSetting.nested_replies_enabled = true }
+
+ it "serializes nested_replies_default as true when category setting is set" do
+ category.category_setting.update!(nested_replies_default: true)
+ cat = Category.includes(:category_setting).find(category.id)
+
+ json = CategorySerializer.new(cat, scope: Guardian.new(admin), root: false).as_json
+
+ expect(json[:category_setting][:nested_replies_default]).to eq(true)
+ end
+
+ it "serializes nested_replies_default as false when not set" do
+ cat = Category.includes(:category_setting).find(category.id)
+
+ json = CategorySerializer.new(cat, scope: Guardian.new(admin), root: false).as_json
+
+ expect(json[:category_setting][:nested_replies_default]).to eq(false)
+ end
+end
diff --git a/spec/services/nested_topic/list_children_spec.rb b/spec/services/nested_topic/list_children_spec.rb
new file mode 100644
index 00000000000..484deaedf2c
--- /dev/null
+++ b/spec/services/nested_topic/list_children_spec.rb
@@ -0,0 +1,86 @@
+# frozen_string_literal: true
+
+RSpec.describe NestedTopic::ListChildren do
+ describe described_class::Contract, type: :model do
+ subject { described_class.new(parent_post_number: 2, sort: "top", page: 0, depth: 1) }
+
+ it { is_expected.to validate_presence_of(:parent_post_number) }
+ it { is_expected.to validate_presence_of(:sort) }
+ it { is_expected.to validate_presence_of(:page) }
+ it { is_expected.to validate_presence_of(:depth) }
+ it { is_expected.not_to allow_value(-1).for(:page) }
+ it { is_expected.not_to allow_value(0).for(:depth) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+ fab!(:parent_post) { Fabricate(:post, topic: topic, user: user, reply_to_post_number: 1) }
+
+ let(:topic_view) do
+ TopicView.new(topic.id, user, skip_custom_fields: true, skip_post_loading: true)
+ end
+ let(:dependencies) { { guardian: user.guardian, topic_view: topic_view } }
+ let(:params) { { parent_post_number: parent_post.post_number, sort: "top", page: 0, depth: 1 } }
+
+ before { SiteSetting.nested_replies_enabled = true }
+
+ context "when contract is invalid" do
+ let(:params) { { parent_post_number: nil, sort: nil, page: nil, depth: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when there are no children" do
+ it { is_expected.to run_successfully }
+
+ it "returns an empty children list" do
+ response = result[:response]
+ expect(response[:children]).to be_empty
+ expect(response[:has_more]).to eq(false)
+ expect(response[:page]).to eq(0)
+ end
+ end
+
+ context "when there are children" do
+ fab!(:child_post) do
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: parent_post.post_number)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "returns children with nested tree structure" do
+ response = result[:response]
+ expect(response[:children]).to be_present
+ expect(response[:children].first[:id]).to eq(child_post.id)
+ expect(response[:children].first).to have_key(:children)
+ end
+ end
+
+ context "when in flattened mode" do
+ fab!(:child_post) do
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: parent_post.post_number)
+ end
+
+ before do
+ SiteSetting.nested_replies_cap_nesting_depth = true
+ SiteSetting.nested_replies_max_depth = 1
+ end
+
+ let(:params) do
+ { parent_post_number: parent_post.post_number, sort: "top", page: 0, depth: 1 }
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "returns children with empty children arrays" do
+ response = result[:response]
+ expect(response[:children]).to be_present
+ response[:children].each { |child| expect(child[:children]).to eq([]) }
+ end
+ end
+ end
+end
diff --git a/spec/services/nested_topic/list_roots_spec.rb b/spec/services/nested_topic/list_roots_spec.rb
new file mode 100644
index 00000000000..00765804907
--- /dev/null
+++ b/spec/services/nested_topic/list_roots_spec.rb
@@ -0,0 +1,118 @@
+# frozen_string_literal: true
+
+RSpec.describe NestedTopic::ListRoots do
+ describe described_class::Contract, type: :model do
+ subject { described_class.new(sort: "top", page: 0) }
+
+ it { is_expected.to validate_presence_of(:sort) }
+ it { is_expected.to validate_presence_of(:page) }
+ it { is_expected.not_to allow_value(-1).for(:page) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+
+ let(:topic_view) do
+ TopicView.new(topic.id, user, skip_custom_fields: true, skip_post_loading: true)
+ end
+ let(:dependencies) { { guardian: user.guardian, topic_view: topic_view } }
+ let(:params) { { sort: "top", page: 0 } }
+
+ before { SiteSetting.nested_replies_enabled = true }
+
+ context "when contract is invalid" do
+ let(:params) { { sort: nil, page: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when page 0 with no posts" do
+ it { is_expected.to run_successfully }
+
+ it "returns an empty roots list with topic metadata" do
+ response = result[:response]
+ expect(response[:roots]).to be_empty
+ expect(response[:page]).to eq(0)
+ expect(response).to have_key(:topic)
+ expect(response).to have_key(:op_post)
+ expect(response).to have_key(:sort)
+ expect(response).to have_key(:message_bus_last_id)
+ end
+ end
+
+ context "when page 0 with root posts" do
+ fab!(:root_post) { Fabricate(:post, topic: topic, user: user, reply_to_post_number: 1) }
+
+ it { is_expected.to run_successfully }
+
+ it "includes root posts and topic metadata in the response" do
+ response = result[:response]
+ expect(response[:roots]).to be_present
+ expect(response[:roots].first[:id]).to eq(root_post.id)
+ expect(response[:topic]).to be_present
+ expect(response[:op_post]).to be_present
+ expect(response[:sort]).to eq("top")
+ expect(response[:message_bus_last_id]).to be_an(Integer)
+ end
+ end
+
+ context "when page is greater than 0" do
+ let(:params) { { sort: "top", page: 1 } }
+
+ it { is_expected.to run_successfully }
+
+ it "does not include topic metadata in the response" do
+ response = result[:response]
+ expect(response).to have_key(:roots)
+ expect(response).not_to have_key(:topic)
+ expect(response).not_to have_key(:op_post)
+ expect(response).not_to have_key(:sort)
+ end
+ end
+
+ context "when there are pinned roots on page 0" do
+ fab!(:root_post) { Fabricate(:post, topic: topic, user: user, reply_to_post_number: 1) }
+ fab!(:pinned_post) { Fabricate(:post, topic: topic, user: user, reply_to_post_number: 1) }
+
+ before { Fabricate(:nested_topic, topic: topic).update!(pinned_post_ids: [pinned_post.id]) }
+
+ it { is_expected.to run_successfully }
+
+ it "promotes the pinned post to the front of the roots list" do
+ response = result[:response]
+ root_ids = response[:roots].map { |r| r[:id] }
+ expect(root_ids.first).to eq(pinned_post.id)
+ end
+
+ it "includes pinned_post_ids in the response" do
+ response = result[:response]
+ expect(response[:pinned_post_ids]).to include(pinned_post.id)
+ end
+ end
+
+ context "when there are pinned roots on page 1" do
+ let(:params) { { sort: "top", page: 1 } }
+
+ fab!(:root_post) { Fabricate(:post, topic: topic, user: user, reply_to_post_number: 1) }
+
+ before { Fabricate(:nested_topic, topic: topic).update!(pinned_post_ids: [root_post.id]) }
+
+ it { is_expected.to run_successfully }
+
+ it "does not promote pinned posts" do
+ response = result[:response]
+ expect(response).not_to have_key(:pinned_post_ids)
+ end
+
+ it "excludes pinned posts from paginated results" do
+ response = result[:response]
+ root_ids = response[:roots].map { |r| r[:id] }
+ expect(root_ids).not_to include(root_post.id)
+ end
+ end
+ end
+end
diff --git a/spec/services/nested_topic/show_context_spec.rb b/spec/services/nested_topic/show_context_spec.rb
new file mode 100644
index 00000000000..41e16fb9cde
--- /dev/null
+++ b/spec/services/nested_topic/show_context_spec.rb
@@ -0,0 +1,94 @@
+# frozen_string_literal: true
+
+RSpec.describe NestedTopic::ShowContext do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:target_post_number) }
+ it { is_expected.to validate_presence_of(:sort) }
+ it { is_expected.to allow_value(nil).for(:context_depth) }
+ it { is_expected.to allow_value(0).for(:context_depth) }
+ it { is_expected.to allow_value(100).for(:context_depth) }
+ it { is_expected.not_to allow_value(101).for(:context_depth) }
+ it { is_expected.not_to allow_value(-1).for(:context_depth) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+ fab!(:target) { Fabricate(:post, topic: topic, user: user, reply_to_post_number: 1) }
+
+ let(:topic_view) do
+ TopicView.new(topic.id, user, skip_custom_fields: true, skip_post_loading: true)
+ end
+ let(:dependencies) { { guardian: user.guardian, topic_view: topic_view } }
+ let(:params) { { target_post_number: target.post_number, sort: "top" } }
+
+ before { SiteSetting.nested_replies_enabled = true }
+
+ context "when contract is invalid" do
+ let(:params) { { target_post_number: nil, sort: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when target post is not found" do
+ let(:params) { { target_post_number: 99_999, sort: "top" } }
+
+ it { is_expected.to fail_to_find_a_model(:target_post) }
+ end
+
+ context "when target post has an invisible post type" do
+ before { target.update!(post_type: Post.types[:whisper]) }
+
+ it { is_expected.to fail_to_find_a_model(:target_post) }
+ end
+
+ context "when target is a root post" do
+ it { is_expected.to run_successfully }
+
+ it "returns response with empty ancestor chain" do
+ response = result[:response]
+ expect(response[:topic]).to be_present
+ expect(response[:op_post]).to be_present
+ expect(response[:ancestor_chain]).to be_empty
+ expect(response[:ancestors_truncated]).to eq(false)
+ expect(response[:siblings]).to be_a(Hash)
+ expect(response[:target_post][:id]).to eq(target.id)
+ expect(response[:message_bus_last_id]).to be_an(Integer)
+ end
+ end
+
+ context "with context_depth set to 0" do
+ let(:params) { { target_post_number: target.post_number, sort: "top", context_depth: 0 } }
+
+ it { is_expected.to run_successfully }
+
+ it "returns an empty ancestor chain" do
+ expect(result[:response][:ancestor_chain]).to be_empty
+ end
+ end
+
+ context "when target has ancestors" do
+ fab!(:ancestor_post) { Fabricate(:post, topic: topic, user: user, reply_to_post_number: 1) }
+ fab!(:target) do
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: ancestor_post.post_number)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "populates the ancestor chain" do
+ response = result[:response]
+ expect(response[:ancestor_chain]).to be_present
+ ancestor_numbers = response[:ancestor_chain].map { |a| a[:post_number] }
+ expect(ancestor_numbers).to include(ancestor_post.post_number)
+ end
+
+ it "populates siblings for ancestors" do
+ response = result[:response]
+ expect(response[:siblings]).to be_a(Hash)
+ end
+ end
+ end
+end
diff --git a/spec/services/nested_topic/toggle_pin_spec.rb b/spec/services/nested_topic/toggle_pin_spec.rb
new file mode 100644
index 00000000000..250abdbd1cc
--- /dev/null
+++ b/spec/services/nested_topic/toggle_pin_spec.rb
@@ -0,0 +1,103 @@
+# frozen_string_literal: true
+
+RSpec.describe NestedTopic::TogglePin do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:topic_id) }
+ it { is_expected.to validate_presence_of(:post_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:topic)
+ fab!(:post) { Fabricate(:post, topic: topic, post_number: 1) }
+
+ let(:params) { { topic_id: topic.id, post_id: post.id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { topic_id: nil, post_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when topic is not found" do
+ let(:params) { { topic_id: 0, post_id: post.id } }
+
+ it { is_expected.to fail_to_find_a_model(:topic) }
+ end
+
+ context "when post is not found" do
+ let(:params) { { topic_id: topic.id, post_id: 0 } }
+
+ it { is_expected.to fail_to_find_a_model(:post) }
+ end
+
+ context "when user is not staff" do
+ fab!(:admin, :user)
+
+ it { is_expected.to fail_a_policy(:staff_can_edit) }
+ end
+
+ context "when post is not a root post" do
+ fab!(:post) { Fabricate(:post, topic: topic, reply_to_post_number: 2) }
+
+ it { is_expected.to fail_a_policy(:post_is_root) }
+ end
+
+ context "when pin limit is reached" do
+ before do
+ Fabricate(:nested_topic, topic: topic).update!(
+ pinned_post_ids: Array.new(NestedTopic::MAX_PINNED_POSTS) { |i| i + 1000 },
+ )
+ end
+
+ it { is_expected.to fail_a_policy(:within_pin_limit) }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "pins the post" do
+ result
+ nested = topic.nested_topic.reload
+ expect(nested.pinned_post_ids).to include(post.id)
+ end
+
+ context "when post is already pinned" do
+ before { Fabricate(:nested_topic, topic: topic, pinned_post_ids: [post.id]) }
+
+ it { is_expected.to run_successfully }
+
+ it "unpins the post" do
+ result
+ nested = topic.nested_topic.reload
+ expect(nested.pinned_post_ids).not_to include(post.id)
+ end
+ end
+
+ context "when post replies to the OP" do
+ fab!(:post) { Fabricate(:post, topic: topic, reply_to_post_number: 1) }
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when pin limit is reached but post is already pinned" do
+ before do
+ Fabricate(:nested_topic, topic: topic).update!(
+ pinned_post_ids: [post.id] + Array.new(9) { |i| i + 1000 },
+ )
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "unpins the post" do
+ result
+ nested = topic.nested_topic.reload
+ expect(nested.pinned_post_ids).not_to include(post.id)
+ end
+ end
+ end
+ end
+end
diff --git a/spec/services/nested_topic/toggle_spec.rb b/spec/services/nested_topic/toggle_spec.rb
new file mode 100644
index 00000000000..b4895898397
--- /dev/null
+++ b/spec/services/nested_topic/toggle_spec.rb
@@ -0,0 +1,81 @@
+# frozen_string_literal: true
+
+RSpec.describe NestedTopic::Toggle do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:topic_id) }
+ it { is_expected.to validate_inclusion_of(:enabled).in_array([true, false]) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:topic)
+
+ let(:params) { { topic_id: topic.id, enabled: } }
+ let(:dependencies) { { guardian: admin.guardian } }
+ let(:enabled) { true }
+
+ context "when contract is invalid" do
+ let(:params) { { topic_id: nil, enabled: true } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when enabled is nil" do
+ let(:params) { { topic_id: topic.id, enabled: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when topic is not found" do
+ let(:params) { { topic_id: 0, enabled: true } }
+
+ it { is_expected.to fail_to_find_a_model(:topic) }
+ end
+
+ context "when user is not staff" do
+ fab!(:admin, :user)
+
+ it { is_expected.to fail_a_policy(:staff_can_edit) }
+ end
+
+ context "when enabling nested view" do
+ let(:enabled) { true }
+
+ it { is_expected.to run_successfully }
+
+ it "creates a nested topic record" do
+ expect { result }.to change { NestedTopic.where(topic: topic).count }.from(0).to(1)
+ end
+
+ context "when nested topic already exists" do
+ before { Fabricate(:nested_topic, topic: topic) }
+
+ it { is_expected.to run_successfully }
+
+ it "does not create a duplicate record" do
+ expect { result }.not_to change { NestedTopic.count }
+ end
+ end
+ end
+
+ context "when disabling nested view" do
+ let(:enabled) { false }
+
+ before { Fabricate(:nested_topic, topic: topic) }
+
+ it { is_expected.to run_successfully }
+
+ it "destroys the nested topic record" do
+ expect { result }.to change { NestedTopic.where(topic: topic).count }.from(1).to(0)
+ end
+ end
+
+ context "when disabling nested view without existing record" do
+ let(:enabled) { false }
+
+ it { is_expected.to run_successfully }
+ end
+ end
+end
diff --git a/spec/support/nested_replies_helpers.rb b/spec/support/nested_replies_helpers.rb
new file mode 100644
index 00000000000..0cdee57475d
--- /dev/null
+++ b/spec/support/nested_replies_helpers.rb
@@ -0,0 +1,18 @@
+# frozen_string_literal: true
+
+module NestedRepliesHelpers
+ def create_reply_chain(depth:, parent: op, in_topic: topic)
+ posts = [parent]
+ depth.times do |i|
+ reply_to = i == 0 && parent == op ? nil : posts.last.post_number
+ posts << Fabricate(
+ :post,
+ topic: in_topic,
+ user: Fabricate(:user),
+ raw: "Reply at depth #{i + 1}",
+ reply_to_post_number: reply_to || posts.last.post_number,
+ )
+ end
+ posts[1..]
+ end
+end
diff --git a/spec/system/nested_category_default_spec.rb b/spec/system/nested_category_default_spec.rb
new file mode 100644
index 00000000000..860a6c8f48f
--- /dev/null
+++ b/spec/system/nested_category_default_spec.rb
@@ -0,0 +1,137 @@
+# frozen_string_literal: true
+
+require_relative "../support/nested_replies_helpers"
+
+RSpec.describe "Nested view category default" do
+ include NestedRepliesHelpers
+
+ fab!(:admin)
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:category)
+ fab!(:nested_category) { Fabricate(:category, name: "Nested Category") }
+ fab!(:topic) { Fabricate(:topic, user: user, category: nested_category) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+ fab!(:reply) { Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "A reply") }
+
+ let(:nested_view) { PageObjects::Pages::NestedView.new }
+ let(:category_page) { PageObjects::Pages::Category.new }
+ let(:form) { PageObjects::Components::FormKit.new(".form-kit") }
+
+ before do
+ SiteSetting.nested_replies_enabled = true
+ SiteSetting.enable_simplified_category_creation = false
+ nested_category.category_setting.update!(nested_replies_default: true)
+ Fabricate(:nested_topic, topic: topic)
+ end
+
+ describe "category settings UI" do
+ before { sign_in(admin) }
+
+ it "allows admin to enable nested view default for a category" do
+ unchecked_category = Fabricate(:category, name: "Unchecked Category")
+
+ category_page.visit_settings(unchecked_category)
+
+ expect(page).to have_css(
+ ".enable-nested-replies-default input[type='checkbox']:not(:checked)",
+ visible: :all,
+ )
+
+ find(".enable-nested-replies-default label.checkbox-label").click
+ category_page.save_settings
+
+ expect(page).to have_current_path(%r{/c/#{unchecked_category.slug}})
+
+ unchecked_category.reload
+ expect(unchecked_category.nested_replies_default).to eq(true)
+ end
+
+ it "shows checkbox as checked when category has nested default enabled" do
+ category_page.visit_settings(nested_category)
+
+ expect(page).to have_css(
+ ".enable-nested-replies-default input[type='checkbox']:checked",
+ visible: :all,
+ )
+ end
+
+ context "with simplified category creation" do
+ before { SiteSetting.enable_simplified_category_creation = true }
+
+ it "allows admin to enable nested view default for a category" do
+ unchecked_category = Fabricate(:category, name: "Unchecked Category")
+
+ category_page.visit_settings(unchecked_category)
+
+ form.field("category_setting.nested_replies_default").toggle
+ category_page.save_settings
+
+ unchecked_category.reload
+ expect(unchecked_category.nested_replies_default).to eq(true)
+ end
+
+ it "shows checkbox as checked when category has nested default enabled" do
+ category_page.visit_settings(nested_category)
+
+ expect(form.field("category_setting.nested_replies_default")).to be_checked
+ end
+ end
+ end
+
+ describe "topic redirect" do
+ before { sign_in(user) }
+
+ it "redirects to nested view when visiting a topic URL directly" do
+ page.visit("/t/#{topic.slug}/#{topic.id}")
+
+ expect(page).to have_current_path(%r{/n/#{topic.slug}/#{topic.id}})
+ expect(nested_view).to have_nested_view
+ end
+
+ it "redirects to nested view when clicking a topic from the category page" do
+ page.visit("/c/#{nested_category.slug}/#{nested_category.id}")
+ find(".topic-list-item .raw-topic-link[data-topic-id='#{topic.id}']").click
+
+ expect(page).to have_current_path(%r{/n/#{topic.slug}/#{topic.id}})
+ expect(nested_view).to have_nested_view
+ end
+
+ it "does not redirect topics in categories without nested default" do
+ normal_topic = Fabricate(:topic, user: user, category: category)
+ Fabricate(:post, topic: normal_topic, user: user, post_number: 1)
+
+ page.visit("/t/#{normal_topic.slug}/#{normal_topic.id}")
+
+ expect(page).to have_current_path(%r{/t/#{normal_topic.slug}/#{normal_topic.id}})
+ expect(nested_view).to have_no_nested_view
+ end
+
+ it "respects ?flat=1 to force flat view even in nested-default category" do
+ page.visit("/t/#{topic.slug}/#{topic.id}?flat=1")
+
+ expect(page).to have_current_path(%r{/t/#{topic.slug}/#{topic.id}})
+ expect(page).to have_current_path(/flat=1/)
+ expect(nested_view).to have_no_nested_view
+ end
+
+ it "does not redirect to nested when navigating within flat view (e.g. topic timeline)" do
+ page.visit("/t/#{topic.slug}/#{topic.id}?flat=1")
+ expect(nested_view).to have_no_nested_view
+
+ # Simulate the exact code path the topic timeline uses:
+ # topic.urlForPostNumber() → DiscourseURL.routeTo()
+ # This exercises the topic-url-for-post-number transformer which rewrites
+ # URLs to /nested/ for nested-default categories.
+ page.execute_script(<<~JS)
+ (function() {
+ var topic = Discourse.lookup("controller:topic").model;
+ var url = topic.urlForPostNumber(#{reply.post_number});
+ require("discourse/lib/url").default.routeTo(url);
+ })();
+ JS
+
+ expect(page).to have_current_path(%r{/t/#{topic.slug}/#{topic.id}})
+ expect(nested_view).to have_no_nested_view
+ end
+ end
+end
diff --git a/spec/system/nested_cloaking_spec.rb b/spec/system/nested_cloaking_spec.rb
new file mode 100644
index 00000000000..42e31fa0c96
--- /dev/null
+++ b/spec/system/nested_cloaking_spec.rb
@@ -0,0 +1,76 @@
+# frozen_string_literal: true
+
+RSpec.describe "Nested view cloaking" do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+
+ let(:nested_view) { PageObjects::Pages::NestedView.new }
+
+ before do
+ SiteSetting.nested_replies_enabled = true
+ sign_in(user)
+ end
+
+ context "with many root posts" do
+ before do
+ 20.times do |i|
+ root =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "Root post number #{i + 1} with enough content to take up space",
+ )
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "Child reply to root #{i + 1}",
+ reply_to_post_number: root.post_number,
+ )
+ end
+ end
+
+ it "cloaks root subtrees far from the viewport" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_nested_view
+
+ expect(nested_view).to have_cloaked_root
+
+ expect(page).to have_no_css(
+ ".nested-view__roots > .nested-post:first-child.nested-post--cloaked",
+ )
+ end
+
+ it "uncloaks roots when scrolling to them" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_nested_view
+
+ send_keys(:end)
+
+ expect(page).to have_css(
+ ".nested-view__roots > .nested-post:first-child.nested-post--cloaked",
+ wait: 5,
+ )
+
+ send_keys(:home)
+
+ expect(page).to have_no_css(
+ ".nested-view__roots > .nested-post:first-child.nested-post--cloaked",
+ )
+ end
+
+ it "hides children content when root is cloaked" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_nested_view
+
+ expect(page).to have_no_css(
+ ".nested-view__roots > .nested-post--cloaked .nested-post__article",
+ )
+ expect(page).to have_no_css(
+ ".nested-view__roots > .nested-post--cloaked .nested-post-children",
+ )
+ end
+ end
+end
diff --git a/spec/system/nested_context_view_spec.rb b/spec/system/nested_context_view_spec.rb
new file mode 100644
index 00000000000..d8f2b1cbe37
--- /dev/null
+++ b/spec/system/nested_context_view_spec.rb
@@ -0,0 +1,215 @@
+# frozen_string_literal: true
+
+RSpec.describe "Nested context view" do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+
+ let(:nested_view) { PageObjects::Pages::NestedView.new }
+ let(:composer) { PageObjects::Components::Composer.new }
+
+ fab!(:chain_posts) do
+ posts = []
+ parent = op
+ 5.times do |i|
+ post =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "Chain post #{i + 1}",
+ reply_to_post_number: parent.post_number,
+ )
+ posts << post
+ parent = post
+ end
+ posts
+ end
+
+ before do
+ SiteSetting.nested_replies_enabled = true
+ sign_in(user)
+ end
+
+ context "with full ancestor context (default)" do
+ it "shows the target with ancestor chain" do
+ nested_view.visit_nested_context(topic, post_number: chain_posts[3].post_number)
+
+ expect(nested_view).to have_context_view
+ expect(nested_view).to have_post(chain_posts[3])
+ expect(nested_view).to have_post(chain_posts[0])
+ expect(nested_view).to have_post(chain_posts[1])
+ expect(nested_view).to have_post(chain_posts[2])
+ end
+
+ it "shows 'View full thread' link but not 'View parent context'" do
+ nested_view.visit_nested_context(topic, post_number: chain_posts[2].post_number)
+
+ expect(nested_view).to have_view_full_thread_link
+ expect(nested_view).to have_no_view_parent_context_link
+ end
+
+ it "does not show 'View parent context' for a direct reply to the OP" do
+ nested_view.visit_nested_context(topic, post_number: chain_posts[0].post_number)
+
+ expect(nested_view).to have_view_full_thread_link
+ expect(nested_view).to have_no_view_parent_context_link
+ end
+
+ it "highlights the target post" do
+ nested_view.visit_nested_context(topic, post_number: chain_posts[2].post_number)
+
+ expect(nested_view).to have_highlighted_post(chain_posts[2])
+ end
+ end
+
+ context "with context=0 (no ancestors)" do
+ it "renders target at depth 0 with no ancestors" do
+ nested_view.visit_nested_context(topic, post_number: chain_posts[3].post_number, context: 0)
+
+ expect(nested_view).to have_context_view
+ expect(nested_view).to have_post_at_depth(chain_posts[3], depth: 0)
+ expect(nested_view).to have_no_post(chain_posts[0])
+ expect(nested_view).to have_no_post(chain_posts[1])
+ expect(nested_view).to have_no_post(chain_posts[2])
+ end
+
+ it "shows 'View parent context' link" do
+ nested_view.visit_nested_context(topic, post_number: chain_posts[3].post_number, context: 0)
+
+ expect(nested_view).to have_view_parent_context_link
+ end
+
+ it "clicking 'View parent context' shows full ancestor chain" do
+ nested_view.visit_nested_context(topic, post_number: chain_posts[3].post_number, context: 0)
+ nested_view.click_view_parent_context
+
+ expect(nested_view).to have_context_view
+ expect(nested_view).to have_post(chain_posts[0])
+ expect(nested_view).to have_post(chain_posts[1])
+ expect(nested_view).to have_post(chain_posts[2])
+ expect(nested_view).to have_post(chain_posts[3])
+ end
+ end
+
+ describe "navigation" do
+ it "clicking 'View full thread' returns to root view" do
+ nested_view.visit_nested_context(topic, post_number: chain_posts[2].post_number)
+ nested_view.click_view_full_thread
+
+ expect(nested_view).to have_nested_view
+ expect(nested_view).to have_no_css(".nested-context-view")
+ end
+
+ it "full navigation flow: context=0 → parent context → full thread" do
+ nested_view.visit_nested_context(topic, post_number: chain_posts[3].post_number, context: 0)
+
+ expect(nested_view).to have_no_post(chain_posts[0])
+ expect(nested_view).to have_post_at_depth(chain_posts[3], depth: 0)
+
+ nested_view.click_view_parent_context
+
+ expect(nested_view).to have_post(chain_posts[0])
+ expect(nested_view).to have_post(chain_posts[3])
+
+ nested_view.click_view_full_thread
+
+ expect(nested_view).to have_nested_view
+ expect(nested_view).to have_no_css(".nested-context-view")
+ expect(nested_view).to have_root_post(chain_posts[0])
+ end
+ end
+
+ context "with deeply nested posts exceeding max_depth" do
+ fab!(:deep_chain) do
+ posts = []
+ parent = op
+ 13.times do |i|
+ post =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "Deep chain post #{i + 1}",
+ reply_to_post_number: parent.post_number,
+ )
+ posts << post
+ parent = post
+ end
+ posts
+ end
+
+ before { SiteSetting.nested_replies_max_depth = 10 }
+
+ it "deep-link shows target with windowed ancestors within max_depth" do
+ nested_view.visit_nested_context(topic, post_number: deep_chain[12].post_number)
+
+ expect(nested_view).to have_context_view
+ expect(nested_view).to have_post(deep_chain[12])
+ expect(nested_view).to have_post(deep_chain[3])
+ expect(nested_view).to have_no_post(deep_chain[1])
+ end
+
+ it "shows 'View parent context' when ancestors are truncated" do
+ nested_view.visit_nested_context(topic, post_number: deep_chain[12].post_number)
+
+ expect(nested_view).to have_view_parent_context_link
+ end
+
+ it "clicking 'View parent context' shifts window up to topmost ancestor" do
+ nested_view.visit_nested_context(topic, post_number: deep_chain[12].post_number)
+ nested_view.click_view_parent_context
+
+ expect(nested_view).to have_context_view
+ expect(nested_view).to have_post(deep_chain[2])
+ expect(nested_view).to have_no_post(deep_chain[12])
+ end
+
+ it "navigating up from context=0 shows windowed ancestors" do
+ nested_view.visit_nested_context(topic, post_number: deep_chain[12].post_number, context: 0)
+
+ expect(nested_view).to have_post_at_depth(deep_chain[12], depth: 0)
+ expect(nested_view).to have_no_post(deep_chain[11])
+
+ nested_view.click_view_parent_context
+
+ expect(nested_view).to have_post(deep_chain[12])
+ expect(nested_view).to have_post(deep_chain[3])
+ expect(nested_view).to have_view_parent_context_link
+ end
+ end
+
+ describe "pinned posts are not carried into context view" do
+ fab!(:root_reply) { Fabricate(:post, topic: topic, user: user, raw: "A pinned root reply") }
+
+ before do
+ nested_topic = NestedTopic.find_or_create_by!(topic: topic)
+ nested_topic.toggle_pin(root_reply.id)
+ end
+
+ it "does not show pinned badge in context view" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_pinned_post(root_reply)
+
+ nested_view.visit_nested_context(topic, post_number: chain_posts[2].post_number)
+ expect(nested_view).to have_context_view
+ expect(nested_view).to have_no_pinned_post(root_reply)
+ end
+ end
+
+ describe "replying in context view" do
+ it "stays in nested view after replying" do
+ nested_view.visit_nested_context(topic, post_number: chain_posts[1].post_number)
+ expect(nested_view).to have_context_view
+
+ nested_view.click_reply_on_post(chain_posts[1])
+ expect(composer).to be_opened
+
+ composer.fill_content("Reply from context view")
+ composer.submit
+ expect(composer).to be_closed
+
+ expect(page).to have_current_path(%r{/n/})
+ end
+ end
+end
diff --git a/spec/system/nested_copy_link_spec.rb b/spec/system/nested_copy_link_spec.rb
new file mode 100644
index 00000000000..a859bb5f04f
--- /dev/null
+++ b/spec/system/nested_copy_link_spec.rb
@@ -0,0 +1,60 @@
+# frozen_string_literal: true
+
+RSpec.describe "Nested view copy link" do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+
+ let(:nested_view) { PageObjects::Pages::NestedView.new }
+ let(:cdp) { PageObjects::CDP.new }
+
+ fab!(:root_reply) do
+ Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "Root reply content")
+ end
+
+ fab!(:child_reply) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "Child reply content",
+ reply_to_post_number: root_reply.post_number,
+ )
+ end
+
+ before do
+ SiteSetting.nested_replies_enabled = true
+ sign_in(user)
+ cdp.allow_clipboard
+ end
+
+ describe "copy link on OP" do
+ it "copies the nested URL" do
+ nested_view.visit_nested(topic)
+ nested_view.click_copy_link_on_op
+
+ expected = "#{Discourse.base_url}/n/#{topic.slug}/#{topic.id}/#{op.post_number}"
+ cdp.clipboard_has_text?(expected)
+ end
+ end
+
+ describe "copy link on a nested post" do
+ it "copies the nested URL" do
+ nested_view.visit_nested(topic)
+ nested_view.click_copy_link_on_post(root_reply)
+
+ expected = "#{Discourse.base_url}/n/#{topic.slug}/#{topic.id}/#{root_reply.post_number}"
+ cdp.clipboard_has_text?(expected)
+ end
+ end
+
+ describe "copy link in context=0 view" do
+ it "copies the standard nested URL without context param" do
+ nested_view.visit_nested_context(topic, post_number: child_reply.post_number, context: 0)
+ nested_view.click_copy_link_on_post(child_reply)
+
+ expected = "#{Discourse.base_url}/n/#{topic.slug}/#{topic.id}/#{child_reply.post_number}"
+ cdp.clipboard_has_text?(expected)
+ end
+ end
+end
diff --git a/spec/system/nested_core_features_spec.rb b/spec/system/nested_core_features_spec.rb
new file mode 100644
index 00000000000..2fef0961f07
--- /dev/null
+++ b/spec/system/nested_core_features_spec.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+# Parts of the core features examples can be skipped like so:
+# it_behaves_like "having working core features", skip_examples: %i[login likes]
+#
+# List of keywords for skipping examples:
+# login, likes, profile, topics, topics:read, topics:reply, topics:create,
+# search, search:quick_search, search:full_page
+#
+# For more details, see https://meta.discourse.org/t/-/361381
+RSpec.describe "Core features" do
+ before { SiteSetting.nested_replies_enabled = true }
+
+ # Because of how routes are defined it _can_ interfere with how scope mappings work,
+ # this test checks if we can create an API key, before rendering, this route checks for all scope mappings
+ it "allows creating API keys" do
+ admin = Fabricate(:admin)
+ sign_in(admin)
+
+ visit "/admin/api/keys/new"
+
+ dialog = PageObjects::Components::Dialog.new
+
+ expect(dialog).to be_closed # if it failed to load the page, the dialog will be open with an error message
+
+ expect(page).to have_selector(".admin-api-keys")
+ expect(page).to have_selector(".admin-config-area-card")
+ end
+
+ it_behaves_like "having working core features"
+end
diff --git a/spec/system/nested_depth_spec.rb b/spec/system/nested_depth_spec.rb
new file mode 100644
index 00000000000..6a7a53097d2
--- /dev/null
+++ b/spec/system/nested_depth_spec.rb
@@ -0,0 +1,158 @@
+# frozen_string_literal: true
+
+require_relative "../support/nested_replies_helpers"
+
+RSpec.describe "Nested view depth and nesting" do
+ include NestedRepliesHelpers
+
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+
+ let(:nested_view) { PageObjects::Pages::NestedView.new }
+
+ before do
+ SiteSetting.nested_replies_enabled = true
+ sign_in(user)
+ end
+
+ describe "max depth setting" do
+ it "respects a low max depth" do
+ SiteSetting.nested_replies_max_depth = 2
+ chain = create_reply_chain(depth: 4)
+
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_post_at_depth(chain[0], depth: 0)
+ expect(nested_view).to have_post_at_depth(chain[1], depth: 1)
+ expect(nested_view).to have_post_at_depth(chain[2], depth: 2)
+ expect(nested_view).to have_continue_thread_for(chain[2])
+ end
+
+ it "allows deeper nesting with higher max depth" do
+ SiteSetting.nested_replies_max_depth = 5
+ chain = create_reply_chain(depth: 4)
+
+ nested_view.visit_nested(topic)
+
+ (0..3).each { |i| expect(nested_view).to have_no_continue_thread_for(chain[i]) }
+ end
+ end
+
+ describe "continue this thread" do
+ context "when cap_nesting_depth is OFF" do
+ before { SiteSetting.nested_replies_cap_nesting_depth = false }
+
+ it "shows 'Continue this thread' at max depth" do
+ SiteSetting.nested_replies_max_depth = 3
+ chain = create_reply_chain(depth: 5)
+
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_continue_thread_for(chain[3])
+ end
+
+ it "does not show 'Continue this thread' below max depth" do
+ SiteSetting.nested_replies_max_depth = 5
+ chain = create_reply_chain(depth: 3)
+
+ nested_view.visit_nested(topic)
+
+ chain.each { |post| expect(nested_view).to have_no_continue_thread_for(post) }
+ end
+
+ it "navigates to context=0 view when clicking 'Continue this thread'" do
+ SiteSetting.nested_replies_max_depth = 3
+ chain = create_reply_chain(depth: 5)
+
+ nested_view.visit_nested(topic)
+ nested_view.click_continue_thread(chain[3])
+
+ expect(nested_view).to have_context_view
+ expect(nested_view).to have_post_at_depth(chain[3], depth: 0)
+ end
+ end
+
+ context "when cap_nesting_depth is ON" do
+ before { SiteSetting.nested_replies_cap_nesting_depth = true }
+
+ it "does not show 'Continue this thread' at max depth" do
+ SiteSetting.nested_replies_max_depth = 3
+ chain = create_reply_chain(depth: 4)
+
+ nested_view.visit_nested(topic)
+
+ chain.each { |post| expect(nested_view).to have_no_continue_thread_for(post) }
+ end
+ end
+ end
+
+ describe "cap nesting depth" do
+ before do
+ SiteSetting.nested_replies_cap_nesting_depth = true
+ SiteSetting.nested_replies_max_depth = 3
+ end
+
+ it "preserves reply_to_post_number on save (no re-parenting)" do
+ chain = create_reply_chain(depth: 4)
+ max_depth_post = chain.last
+
+ reply =
+ PostCreator.new(
+ user,
+ raw: "This should NOT be re-parented",
+ topic_id: topic.id,
+ reply_to_post_number: max_depth_post.post_number,
+ ).create
+
+ expect(reply.reply_to_post_number).to eq(max_depth_post.post_number)
+ end
+
+ it "does not show 'Continue this thread' when cap is on" do
+ chain = create_reply_chain(depth: 4)
+
+ nested_view.visit_nested(topic)
+
+ chain.each { |post| expect(nested_view).to have_no_continue_thread_for(post) }
+ end
+ end
+
+ describe "expand button at max depth" do
+ it "does not show the expand button for posts at max depth with replies" do
+ SiteSetting.nested_replies_max_depth = 2
+ chain = create_reply_chain(depth: 4)
+
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_post(chain[2])
+ expect(nested_view).to have_no_replies_toggle_for(chain[2])
+ end
+ end
+
+ describe "depth line at max depth" do
+ it "hides the depth line at max depth when cap is ON" do
+ SiteSetting.nested_replies_cap_nesting_depth = true
+ SiteSetting.nested_replies_max_depth = 2
+ chain = create_reply_chain(depth: 4)
+
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_depth_line_for(chain[0])
+ expect(nested_view).to have_depth_line_for(chain[1])
+ expect(nested_view).to have_no_depth_line_for(chain[2])
+ end
+
+ it "shows the depth line at max depth when cap is OFF (continue thread)" do
+ SiteSetting.nested_replies_cap_nesting_depth = false
+ SiteSetting.nested_replies_max_depth = 2
+ chain = create_reply_chain(depth: 4)
+
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_depth_line_for(chain[0])
+ expect(nested_view).to have_depth_line_for(chain[1])
+ expect(nested_view).to have_depth_line_for(chain[2])
+ expect(nested_view).to have_continue_thread_for(chain[2])
+ end
+ end
+end
diff --git a/spec/system/nested_floating_actions_spec.rb b/spec/system/nested_floating_actions_spec.rb
new file mode 100644
index 00000000000..ea530319c24
--- /dev/null
+++ b/spec/system/nested_floating_actions_spec.rb
@@ -0,0 +1,103 @@
+# frozen_string_literal: true
+
+RSpec.describe "Nested view floating actions" do
+ fab!(:admin)
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+
+ let(:nested_view) { PageObjects::Pages::NestedView.new }
+ let(:composer) { PageObjects::Components::Composer.new }
+
+ before { SiteSetting.nested_replies_enabled = true }
+
+ describe "as admin" do
+ before { sign_in(admin) }
+
+ it "shows notification button, admin menu, and reply button" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_floating_actions
+ expect(nested_view).to have_notification_button
+ expect(nested_view).to have_admin_menu_button
+ expect(nested_view).to have_floating_reply_button
+ end
+
+ it "can change notification level" do
+ nested_view.visit_nested(topic)
+ nested_view.change_notification_level(3) # Watching
+ expect(page).to have_css(
+ ".nested-view__floating-actions .notifications-tracking-trigger-btn[data-level-id='3']",
+ )
+ end
+
+ it "can close and reopen a topic via admin menu" do
+ nested_view.visit_nested(topic)
+ nested_view.click_admin_close_topic
+
+ nested_view.open_admin_menu
+ expect(page).to have_css(".topic-admin-open")
+ expect(topic.reload).to be_closed
+
+ find(".topic-admin-open .btn").click
+ nested_view.open_admin_menu
+ expect(page).to have_css(".topic-admin-close")
+ expect(topic.reload).not_to be_closed
+ end
+
+ it "hides floating actions when composer is open" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_floating_actions
+
+ nested_view.click_floating_reply_button
+ expect(composer).to be_opened
+ expect(nested_view).to have_no_floating_actions
+
+ composer.close
+ expect(composer).to be_closed
+ expect(nested_view).to have_floating_actions
+ end
+ end
+
+ describe "as regular user" do
+ before { sign_in(user) }
+
+ it "shows notification button and reply button but not admin menu" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_notification_button
+ expect(nested_view).to have_floating_reply_button
+ expect(nested_view).to have_no_admin_menu_button
+ end
+ end
+
+ describe "as anonymous user" do
+ it "does not show notification button or reply button" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_no_notification_button
+ expect(nested_view).to have_no_floating_reply_button
+ end
+ end
+
+ describe "in context view" do
+ fab!(:root_reply) { Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "Root reply") }
+ fab!(:child_reply) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "Child reply",
+ reply_to_post_number: root_reply.post_number,
+ )
+ end
+
+ before { sign_in(admin) }
+
+ it "shows floating actions in context view" do
+ nested_view.visit_nested_context(topic, post_number: child_reply.post_number)
+ expect(nested_view).to have_context_view
+ expect(nested_view).to have_floating_actions
+ expect(nested_view).to have_notification_button
+ expect(nested_view).to have_admin_menu_button
+ expect(nested_view).to have_floating_reply_button
+ end
+ end
+end
diff --git a/spec/system/nested_pagination_spec.rb b/spec/system/nested_pagination_spec.rb
new file mode 100644
index 00000000000..90e6f7eb6a9
--- /dev/null
+++ b/spec/system/nested_pagination_spec.rb
@@ -0,0 +1,119 @@
+# frozen_string_literal: true
+
+RSpec.describe "Nested view pagination" do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+
+ let(:nested_view) { PageObjects::Pages::NestedView.new }
+
+ before do
+ SiteSetting.nested_replies_enabled = true
+ sign_in(user)
+ end
+
+ describe "load more children" do
+ fab!(:root_reply) do
+ Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "Root post with many children")
+ end
+
+ # Create 5 child replies — initial load preloads 3, so "load more" appears
+ fab!(:child_1) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "Child reply one",
+ reply_to_post_number: root_reply.post_number,
+ created_at: 5.minutes.ago,
+ )
+ end
+
+ fab!(:child_2) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "Child reply two",
+ reply_to_post_number: root_reply.post_number,
+ created_at: 4.minutes.ago,
+ )
+ end
+
+ fab!(:child_3) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "Child reply three",
+ reply_to_post_number: root_reply.post_number,
+ created_at: 3.minutes.ago,
+ )
+ end
+
+ fab!(:child_4) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "Child reply four",
+ reply_to_post_number: root_reply.post_number,
+ created_at: 2.minutes.ago,
+ )
+ end
+
+ fab!(:child_5) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "Child reply five",
+ reply_to_post_number: root_reply.post_number,
+ created_at: 1.minute.ago,
+ )
+ end
+
+ it "shows load more button and loads additional children on click" do
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_post(root_reply)
+ expect(page).to have_css(".nested-post-children__load-more")
+
+ find(".nested-post-children__load-more").click
+
+ expect(nested_view).to have_post(child_1)
+ expect(nested_view).to have_post(child_2)
+ expect(nested_view).to have_post(child_3)
+ expect(nested_view).to have_post(child_4)
+ expect(nested_view).to have_post(child_5)
+ expect(page).to have_no_css(".nested-post-children__load-more")
+ end
+ end
+
+ describe "load more roots" do
+ # ROOTS_PER_PAGE is 20, so create 22 to have pagination
+ before do
+ 22.times do |i|
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "Root post number #{i + 1}",
+ reply_to_post_number: nil,
+ )
+ end
+ end
+
+ it "initially shows first page of roots and loads more on scroll" do
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_nested_view
+ initial_count = all(".nested-view__roots > .nested-post").count
+ expect(initial_count).to eq(20)
+
+ page.execute_script("window.scrollTo(0, document.body.scrollHeight)")
+
+ expect(page).to have_css(".nested-view__roots > .nested-post", count: 22, wait: 5)
+ end
+ end
+end
diff --git a/spec/system/nested_post_lifecycle_spec.rb b/spec/system/nested_post_lifecycle_spec.rb
new file mode 100644
index 00000000000..46f4f415ff4
--- /dev/null
+++ b/spec/system/nested_post_lifecycle_spec.rb
@@ -0,0 +1,265 @@
+# frozen_string_literal: true
+
+RSpec.describe "Nested view post lifecycle" do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:admin) { Fabricate(:admin, refresh_auto_groups: true) }
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+
+ let(:nested_view) { PageObjects::Pages::NestedView.new }
+ let(:composer) { PageObjects::Components::Composer.new }
+ let(:dialog) { PageObjects::Components::Dialog.new }
+
+ before { SiteSetting.nested_replies_enabled = true }
+
+ describe "editing a post and saving" do
+ fab!(:root_reply) do
+ Fabricate(:post, topic: topic, user: user, raw: "Original content before editing")
+ end
+
+ before { sign_in(user) }
+
+ it "updates the post content after saving an edit" do
+ nested_view.visit_nested(topic)
+ expect(page).to have_css(
+ "[data-post-number='#{root_reply.post_number}']",
+ text: "Original content before editing",
+ )
+
+ nested_view.click_post_edit_button(root_reply)
+ expect(composer).to be_opened
+
+ composer.fill_content("Updated content after editing")
+ composer.submit
+
+ expect(composer).to be_closed
+ expect(page).to have_css(
+ "[data-post-number='#{root_reply.post_number}']",
+ text: "Updated content after editing",
+ )
+ expect(nested_view).to have_nested_view
+ end
+ end
+
+ describe "editing the OP and saving" do
+ before { sign_in(user) }
+
+ it "updates the OP content after saving an edit" do
+ op.update!(raw: "Original OP content that should be long enough to pass")
+ op.rebake!
+
+ nested_view.visit_nested(topic)
+ expect(page).to have_css(
+ ".nested-view__op",
+ text: "Original OP content that should be long enough to pass",
+ )
+
+ nested_view.click_post_edit_button(op)
+ expect(composer).to be_opened
+
+ composer.fill_content("Updated OP content that should also be long enough")
+ composer.submit
+
+ expect(composer).to be_closed
+ expect(page).to have_css(
+ ".nested-view__op",
+ text: "Updated OP content that should also be long enough",
+ )
+ end
+ end
+
+ describe "deleting a post" do
+ fab!(:root_reply) do
+ Fabricate(:post, topic: topic, user: user, raw: "Post that will be deleted")
+ end
+
+ context "when user deletes their own post" do
+ before { sign_in(user) }
+
+ it "shows a deleted placeholder after confirming deletion" do
+ nested_view.visit_nested(topic)
+ expect(page).to have_css(
+ "[data-post-number='#{root_reply.post_number}']",
+ text: "Post that will be deleted",
+ )
+
+ nested_view.click_post_delete_button(root_reply)
+ dialog.click_yes
+
+ expect(nested_view).to have_deleted_post_class_for(root_reply)
+ end
+ end
+
+ context "when admin deletes a post" do
+ before { sign_in(admin) }
+
+ it "shows a deleted placeholder" do
+ nested_view.visit_nested(topic)
+ expect(page).to have_css(
+ "[data-post-number='#{root_reply.post_number}']",
+ text: "Post that will be deleted",
+ )
+
+ nested_view.click_post_delete_button(root_reply)
+ dialog.click_yes
+
+ expect(nested_view).to have_deleted_post_class_for(root_reply)
+ end
+ end
+ end
+
+ describe "deleting a post with children" do
+ fab!(:root_reply) { Fabricate(:post, topic: topic, user: user, raw: "Parent with children") }
+
+ fab!(:child_reply) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "Child reply content",
+ reply_to_post_number: root_reply.post_number,
+ )
+ end
+
+ before { sign_in(admin) }
+
+ it "shows placeholder for parent but preserves children" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_post(root_reply)
+ expect(nested_view).to have_post(child_reply)
+
+ nested_view.click_post_delete_button(root_reply)
+ dialog.click_yes
+
+ expect(nested_view).to have_deleted_post_class_for(root_reply)
+ expect(nested_view).to have_post(child_reply)
+ expect(page).to have_css(
+ "[data-post-number='#{child_reply.post_number}']",
+ text: "Child reply content",
+ )
+ end
+ end
+
+ describe "recovering a deleted post" do
+ fab!(:root_reply) do
+ Fabricate(:post, topic: topic, user: user, raw: "Post that was deleted and recovered")
+ end
+
+ before { sign_in(admin) }
+
+ it "clears the deleted placeholder after recovery" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_post(root_reply)
+
+ nested_view.click_post_delete_button(root_reply)
+ dialog.click_yes
+ expect(nested_view).to have_deleted_post_class_for(root_reply)
+
+ nested_view.click_post_recover_button(root_reply)
+ expect(nested_view).to have_no_deleted_placeholder_for(root_reply)
+ expect(page).to have_css(
+ "[data-post-number='#{root_reply.post_number}']",
+ text: "Post that was deleted and recovered",
+ )
+ end
+ end
+
+ describe "staff viewing deleted post content" do
+ fab!(:root_reply) do
+ Fabricate(:post, topic: topic, user: user, raw: "Secret deleted content here")
+ end
+
+ context "when logged in as admin" do
+ before { sign_in(admin) }
+
+ it "shows an eye button to toggle deleted content visibility" do
+ nested_view.visit_nested(topic)
+ expect(page).to have_css(
+ "[data-post-number='#{root_reply.post_number}']",
+ text: "Secret deleted content here",
+ )
+
+ nested_view.click_post_delete_button(root_reply)
+ dialog.click_yes
+
+ expect(nested_view).to have_deleted_post_class_for(root_reply)
+ expect(nested_view).to have_toggle_deleted_content_button_for(root_reply)
+ expect(nested_view).to have_no_deleted_content_visible_for(root_reply)
+
+ nested_view.click_toggle_deleted_content(root_reply)
+
+ expect(nested_view).to have_deleted_content_visible_for(root_reply)
+ expect(page).to have_css(
+ ".nested-post__deleted-content",
+ text: "Secret deleted content here",
+ )
+ end
+
+ it "hides deleted content when toggled again" do
+ nested_view.visit_nested(topic)
+ expect(page).to have_css(
+ "[data-post-number='#{root_reply.post_number}']",
+ text: "Secret deleted content here",
+ )
+
+ nested_view.click_post_delete_button(root_reply)
+ dialog.click_yes
+
+ expect(nested_view).to have_deleted_post_class_for(root_reply)
+ nested_view.click_toggle_deleted_content(root_reply)
+ expect(nested_view).to have_deleted_content_visible_for(root_reply)
+
+ nested_view.click_toggle_deleted_content(root_reply)
+ expect(nested_view).to have_no_deleted_content_visible_for(root_reply)
+ end
+ end
+
+ context "when logged in as regular user" do
+ before { sign_in(user) }
+
+ it "does not show an eye button on deleted posts" do
+ root_reply.update!(deleted_at: Time.current)
+
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_deleted_placeholder_for(root_reply)
+ expect(nested_view).to have_no_toggle_deleted_content_button_for(root_reply)
+ end
+ end
+ end
+
+ describe "editing a child post" do
+ fab!(:root_reply) { Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "Root post") }
+
+ fab!(:child_reply) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ raw: "Original child content here",
+ reply_to_post_number: root_reply.post_number,
+ )
+ end
+
+ before { sign_in(user) }
+
+ it "updates the child post content after saving" do
+ nested_view.visit_nested(topic)
+ expect(page).to have_css(
+ "[data-post-number='#{child_reply.post_number}']",
+ text: "Original child content here",
+ )
+
+ nested_view.click_post_edit_button(child_reply)
+ expect(composer).to be_opened
+
+ composer.fill_content("Updated child content here")
+ composer.submit
+
+ expect(composer).to be_closed
+ expect(page).to have_css(
+ "[data-post-number='#{child_reply.post_number}']",
+ text: "Updated child content here",
+ )
+ end
+ end
+end
diff --git a/spec/system/nested_quoting_spec.rb b/spec/system/nested_quoting_spec.rb
new file mode 100644
index 00000000000..f7966e2c305
--- /dev/null
+++ b/spec/system/nested_quoting_spec.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+RSpec.describe "Nested view quoting" do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:op) do
+ Fabricate(:post, topic: topic, user: user, post_number: 1, raw: "Original post content here")
+ end
+ fab!(:root_reply) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "This is a root reply to quote from",
+ )
+ end
+
+ let(:nested_view) { PageObjects::Pages::NestedView.new }
+ let(:composer) { PageObjects::Components::Composer.new }
+
+ before do
+ SiteSetting.nested_replies_enabled = true
+ sign_in(user)
+ end
+
+ def nested_post_cooked_selector(post)
+ "[data-post-number='#{post.post_number}'] .cooked p"
+ end
+
+ it "shows the quote button when selecting text in a nested post" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_post(root_reply)
+
+ select_text_range(nested_post_cooked_selector(root_reply), 0, 5)
+ expect(page).to have_css(".quote-button")
+ end
+
+ it "inserts a quote into the composer when clicking the quote button" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_post(root_reply)
+
+ select_text_range(nested_post_cooked_selector(root_reply), 0, 7)
+ expect(page).to have_css(".quote-button")
+ find(".quote-button .insert-quote").click
+
+ expect(composer).to be_opened
+ expect(composer.composer_input.value).to include(
+ "[quote=\"#{root_reply.user.username}, post:#{root_reply.post_number}, topic:#{topic.id}",
+ )
+ end
+
+ it "shows the quote button when selecting text in the OP" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_op_post
+
+ select_text_range(".nested-view__op .cooked p", 0, 8)
+ expect(page).to have_css(".quote-button")
+ end
+end
diff --git a/spec/system/nested_realtime_spec.rb b/spec/system/nested_realtime_spec.rb
new file mode 100644
index 00000000000..2c917239e4a
--- /dev/null
+++ b/spec/system/nested_realtime_spec.rb
@@ -0,0 +1,62 @@
+# frozen_string_literal: true
+
+RSpec.describe "Nested view real-time updates" do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:other_user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+ fab!(:root_reply) do
+ Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "Existing root reply")
+ end
+
+ let(:nested_view) { PageObjects::Pages::NestedView.new }
+
+ before do
+ SiteSetting.nested_replies_enabled = true
+ sign_in(user)
+ end
+
+ describe "new root post by another user" do
+ it "shows new replies notification banner and loads posts on click" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_nested_view
+ expect(nested_view).to have_root_post(root_reply)
+
+ # Create a root post via PostCreator which triggers MessageBus
+ PostCreator.create!(
+ other_user,
+ topic_id: topic.id,
+ raw: "A brand new root reply from another user",
+ )
+
+ expect(page).to have_css(".nested-view__new-replies-btn", wait: 10)
+
+ find(".nested-view__new-replies-btn").click
+
+ expect(page).to have_no_css(".nested-view__new-replies-btn")
+ expect(page).to have_content("A brand new root reply from another user")
+ end
+ end
+
+ describe "new child reply by another user" do
+ it "shows the new child in the tree" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_nested_view
+ expect(nested_view).to have_root_post(root_reply)
+
+ new_child =
+ PostCreator.create!(
+ other_user,
+ topic_id: topic.id,
+ reply_to_post_number: root_reply.post_number,
+ raw: "A child reply via message bus",
+ )
+
+ expect(page).to have_css(
+ "[data-post-number='#{new_child.post_number}']",
+ text: "A child reply via message bus",
+ wait: 10,
+ )
+ end
+ end
+end
diff --git a/spec/system/nested_redirect_fallback_spec.rb b/spec/system/nested_redirect_fallback_spec.rb
new file mode 100644
index 00000000000..cdadcd68699
--- /dev/null
+++ b/spec/system/nested_redirect_fallback_spec.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+RSpec.describe "Nested redirect fallback for untracked topics" do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:category)
+ fab!(:topic_author, :user)
+ fab!(:topic) { Fabricate(:topic, user: topic_author, category: category) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: topic_author, post_number: 1) }
+ fab!(:reply) { Fabricate(:post, topic: topic, user: topic_author, raw: "A reply to the topic") }
+
+ let(:nested_view) { PageObjects::Pages::NestedView.new }
+
+ before do
+ SiteSetting.nested_replies_enabled = true
+ sign_in(user)
+ end
+
+ # When nested replies is enabled, the afterModel hook in
+ # topic/from-params.js checks topic.is_nested_view and redirects via
+ # router.replaceWith() to the nested route. That check relies on the
+ # topic's category being present in client-side state so is_nested_view
+ # can be resolved. When the topic is NOT in client-side tracking state
+ # the category lookup may be async, exercising a fallback path.
+ #
+ # These tests verify the fallback preserves the post number in the URL
+ # (so the user's scroll position isn't lost) and that non-nested topics
+ # still load the flat view correctly.
+
+ it "preserves the post number in the URL after the async category check" do
+ page.visit("/about")
+ expect(page).to have_css("#main-outlet")
+
+ # Clear the client-side tracking state so the topic misses the
+ # synchronous lookup and hits the async fallback path.
+ page.execute_script(<<~JS)
+ const tts = Discourse.lookup("service:topic-tracking-state");
+ tts.states.clear();
+ require("discourse/lib/url").default.routeTo("/t/#{topic.slug}/#{topic.id}/#{reply.post_number}");
+ JS
+
+ expect(page).to have_css("#post_#{reply.post_number}")
+ expect(page).to have_current_path("/t/#{topic.slug}/#{topic.id}/#{reply.post_number}")
+ end
+
+ it "loads the flat topic view correctly after the async category check" do
+ page.visit("/about")
+ expect(page).to have_css("#main-outlet")
+
+ page.execute_script(<<~JS)
+ const tts = Discourse.lookup("service:topic-tracking-state");
+ tts.states.clear();
+ require("discourse/lib/url").default.routeTo("/t/#{topic.slug}/#{topic.id}");
+ JS
+
+ expect(page).to have_css("#post_1")
+ expect(nested_view).to have_no_nested_view
+ end
+end
diff --git a/spec/system/nested_replying_spec.rb b/spec/system/nested_replying_spec.rb
new file mode 100644
index 00000000000..4f88c1e70af
--- /dev/null
+++ b/spec/system/nested_replying_spec.rb
@@ -0,0 +1,172 @@
+# frozen_string_literal: true
+
+RSpec.describe "Nested view replying" do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+
+ let(:nested_view) { PageObjects::Pages::NestedView.new }
+ let(:composer) { PageObjects::Components::Composer.new }
+
+ before do
+ SiteSetting.nested_replies_enabled = true
+ sign_in(user)
+ end
+
+ describe "replying to a nested post" do
+ fab!(:root_reply) do
+ Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "Root reply to discuss")
+ end
+
+ it "stays on nested view after replying" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_nested_view
+
+ nested_view.click_reply_on_post(root_reply)
+ expect(composer).to be_opened
+
+ composer.fill_content("This is my nested reply")
+ composer.submit
+
+ expect(composer).to be_closed
+ expect(nested_view).to have_nested_view
+ expect(page).to have_current_path(%r{/n/})
+ end
+ end
+
+ describe "replying to the OP" do
+ it "stays on nested view after replying" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_nested_view
+
+ nested_view.click_reply_on_op
+ expect(composer).to be_opened
+
+ composer.fill_content("This is a reply to the original post")
+ composer.submit
+
+ expect(composer).to be_closed
+ expect(nested_view).to have_nested_view
+ expect(page).to have_current_path(%r{/n/})
+ end
+ end
+
+ describe "floating reply button" do
+ it "is visible for logged-in users" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_floating_reply_button
+ end
+
+ it "is not visible for anonymous users" do
+ Capybara.reset_sessions!
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_no_floating_reply_button
+ end
+
+ it "opens the composer for a top-level reply" do
+ nested_view.visit_nested(topic)
+ nested_view.click_floating_reply_button
+ expect(composer).to be_opened
+
+ composer.fill_content("A top-level reply via floating button")
+ composer.submit
+ expect(composer).to be_closed
+
+ expect(nested_view).to have_nested_view
+ expect(page).to have_current_path(%r{/n/})
+ end
+
+ it "hides when the composer is open and reappears when closed" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_floating_reply_button
+
+ nested_view.click_floating_reply_button
+ expect(composer).to be_opened
+ expect(nested_view).to have_no_floating_reply_button
+
+ composer.close
+ expect(composer).to be_closed
+ expect(nested_view).to have_floating_reply_button
+ end
+ end
+
+ describe "replying to a collapsed post" do
+ fab!(:root_reply) do
+ Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "Root reply with children")
+ end
+
+ fab!(:child_reply) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "Child reply",
+ reply_to_post_number: root_reply.post_number,
+ )
+ end
+
+ it "auto-expands a collapsed post after submitting a reply" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_children_visible_for(root_reply)
+
+ nested_view.click_reply_on_post(root_reply)
+ expect(composer).to be_opened
+
+ nested_view.click_depth_line(root_reply)
+ expect(nested_view).to have_collapsed_bar_for(root_reply)
+
+ composer.fill_content("Reply to collapsed post")
+ composer.submit
+ expect(composer).to be_closed
+
+ expect(nested_view).to have_no_collapsed_bar_for(root_reply)
+ expect(nested_view).to have_children_visible_for(root_reply)
+ end
+ end
+
+ describe "replying to a post with no existing children" do
+ fab!(:root_reply) do
+ Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "Post with no children yet")
+ end
+
+ it "shows the depth line on the parent without refresh" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_no_depth_line_for(root_reply)
+
+ nested_view.click_reply_on_post(root_reply)
+ composer.fill_content("First child reply")
+ composer.submit
+ expect(composer).to be_closed
+
+ expect(nested_view).to have_depth_line_for(root_reply)
+ end
+ end
+
+ describe "replying to a leaf post" do
+ fab!(:root_reply) { Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "Root reply") }
+
+ fab!(:child_reply) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "Child reply (leaf)",
+ reply_to_post_number: root_reply.post_number,
+ )
+ end
+
+ it "shows the new reply as a child" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_post(child_reply)
+
+ nested_view.click_reply_on_post(child_reply)
+ expect(composer).to be_opened
+
+ composer.fill_content("Reply to leaf post")
+ composer.submit
+ expect(composer).to be_closed
+
+ expect(nested_view).to have_children_visible_for(child_reply)
+ end
+ end
+end
diff --git a/spec/system/nested_topic_admin_toggle_spec.rb b/spec/system/nested_topic_admin_toggle_spec.rb
new file mode 100644
index 00000000000..0bf8ba84c16
--- /dev/null
+++ b/spec/system/nested_topic_admin_toggle_spec.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+require_relative "../support/nested_replies_helpers"
+
+RSpec.describe "Nested replies topic admin toggle" do
+ include NestedRepliesHelpers
+
+ fab!(:admin)
+ fab!(:topic) { Fabricate(:topic, user: admin) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: admin, post_number: 1) }
+ fab!(:reply) { Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "A reply") }
+
+ let(:topic_page) { PageObjects::Pages::Topic.new }
+ let(:nested_view) { PageObjects::Pages::NestedView.new }
+
+ before do
+ SiteSetting.nested_replies_enabled = true
+ sign_in(admin)
+ end
+
+ it "enables nested replies from the flat view and routes to nested" do
+ topic_page.visit_topic(topic)
+
+ topic_page.click_admin_menu_button
+ find(".topic-admin-nested-replies").click
+
+ expect(page).to have_current_path(%r{/n/#{topic.slug}/#{topic.id}})
+ expect(nested_view).to have_nested_view
+
+ topic.reload
+ expect(topic.reload.nested_topic).to be_present
+ end
+
+ it "disables nested replies from the nested view and routes to flat" do
+ Fabricate(:nested_topic, topic: topic)
+
+ nested_view.visit_nested(topic)
+ nested_view.open_admin_menu
+ find(".topic-admin-nested-replies").click
+
+ expect(page).to have_current_path(%r{/t/#{topic.slug}/#{topic.id}})
+ expect(nested_view).to have_no_nested_view
+
+ topic.reload
+ expect(topic.reload.nested_topic).to be_nil
+ end
+end
diff --git a/spec/system/nested_view_spec.rb b/spec/system/nested_view_spec.rb
new file mode 100644
index 00000000000..66c946cdc59
--- /dev/null
+++ b/spec/system/nested_view_spec.rb
@@ -0,0 +1,295 @@
+# frozen_string_literal: true
+
+require_relative "../support/nested_replies_helpers"
+
+RSpec.describe "Nested view" do
+ include NestedRepliesHelpers
+
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+
+ let(:nested_view) { PageObjects::Pages::NestedView.new }
+
+ before do
+ SiteSetting.nested_replies_enabled = true
+ sign_in(user)
+ end
+
+ describe "basic rendering" do
+ fab!(:root_reply) { Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "Root reply") }
+
+ it "displays the nested view with root posts" do
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_nested_view
+ expect(nested_view).to have_root_post(root_reply)
+ end
+
+ it "does not show the standard replies button on the OP" do
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_no_show_replies_button_for(op)
+ end
+
+ it "shows the original post content" do
+ op.update!(raw: "This is the original post content")
+ op.rebake!
+
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_op_post
+ expect(page).to have_css(".nested-view__op", text: "This is the original post content")
+ end
+ end
+
+ describe "topic map" do
+ fab!(:root_reply) { Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "A reply") }
+
+ it "displays the topic map" do
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_topic_map
+ end
+
+ it "hides the top replies button" do
+ topic.update!(has_summary: true)
+
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_topic_map
+ expect(nested_view).to have_no_top_replies_button
+ end
+ end
+
+ describe "topic title editing" do
+ fab!(:admin) { Fabricate(:admin, refresh_auto_groups: true) }
+ fab!(:root_reply) { Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "A reply") }
+
+ before { sign_in(admin) }
+
+ it "shows the topic title editor when clicking the title" do
+ nested_view.visit_nested(topic)
+
+ nested_view.click_edit_topic
+ expect(nested_view).to have_topic_title_editor
+ end
+
+ it "cancels topic title editing" do
+ nested_view.visit_nested(topic)
+
+ nested_view.click_edit_topic
+ expect(nested_view).to have_topic_title_editor
+
+ nested_view.click_cancel_edit_topic
+ expect(nested_view).to have_no_topic_title_editor
+ end
+
+ it "saves edited topic title" do
+ nested_view.visit_nested(topic)
+
+ nested_view.click_edit_topic
+ nested_view.fill_in_topic_title("Updated Topic Title")
+ nested_view.click_save_edit_topic
+
+ expect(nested_view).to have_no_topic_title_editor
+ expect(page).to have_css(".nested-view__title", text: "Updated Topic Title")
+ end
+ end
+
+ describe "post editing" do
+ fab!(:root_reply) { Fabricate(:post, topic: topic, user: user, raw: "My editable reply") }
+
+ let(:composer) { PageObjects::Components::Composer.new }
+
+ it "opens the composer in edit mode" do
+ nested_view.visit_nested(topic)
+
+ nested_view.click_post_edit_button(root_reply)
+ expect(composer).to be_opened
+ expect(composer).to have_content("My editable reply")
+ end
+
+ it "opens the composer when editing the OP" do
+ op.update!(raw: "Original post content that is long enough")
+ op.rebake!
+
+ nested_view.visit_nested(topic)
+
+ nested_view.click_post_edit_button(op)
+ expect(composer).to be_opened
+ expect(composer).to have_content("Original post content that is long enough")
+ end
+ end
+
+ describe "empty topic" do
+ it "shows 'no replies' message when topic has no replies" do
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_nested_view
+ expect(page).to have_css(".nested-view__empty", text: "No replies yet.")
+ end
+ end
+
+ describe "sorting" do
+ fab!(:old_reply) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "Older reply",
+ created_at: 2.days.ago,
+ )
+ end
+
+ fab!(:new_reply) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "Newer reply",
+ created_at: 1.minute.ago,
+ )
+ end
+
+ it "changes sort order and updates the URL" do
+ nested_view.visit_nested(topic)
+ expect(nested_view).to have_sort_active("top")
+
+ nested_view.click_sort("new")
+ expect(nested_view).to have_sort_active("new")
+ expect(page).to have_current_path(/sort=new/)
+
+ nested_view.click_sort("old")
+ expect(nested_view).to have_sort_active("old")
+ expect(page).to have_current_path(/sort=old/)
+ end
+ end
+
+ describe "expand and collapse" do
+ fab!(:root_reply) do
+ Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "Post with children")
+ end
+
+ fab!(:child_reply) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: Fabricate(:user),
+ raw: "A child post",
+ reply_to_post_number: root_reply.post_number,
+ )
+ end
+
+ it "collapses post content and children when clicking the depth line" do
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_post(child_reply)
+ expect(nested_view).to have_children_visible_for(root_reply)
+ expect(nested_view).to have_no_collapsed_bar_for(root_reply)
+
+ nested_view.click_depth_line(root_reply)
+ expect(nested_view).to have_collapsed_bar_for(root_reply)
+ expect(nested_view).to have_no_post_content_visible_for(root_reply)
+ expect(nested_view).to have_no_children_visible_for(root_reply)
+ end
+
+ it "re-expands post content and children when clicking the collapsed bar" do
+ nested_view.visit_nested(topic)
+
+ nested_view.click_depth_line(root_reply)
+ expect(nested_view).to have_collapsed_bar_for(root_reply)
+
+ nested_view.click_collapsed_bar(root_reply)
+ expect(nested_view).to have_no_collapsed_bar_for(root_reply)
+ expect(nested_view).to have_post_content_visible_for(root_reply)
+ expect(nested_view).to have_children_visible_for(root_reply)
+ expect(nested_view).to have_post(child_reply)
+ end
+ end
+
+ describe "flat view toggle" do
+ fab!(:root_reply) { Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "A reply") }
+ fab!(:admin)
+
+ it "shows the link and navigates to flat view for allowed groups" do
+ sign_in(admin)
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_flat_view_link
+ nested_view.click_flat_view_link
+
+ expect(page).to have_current_path(%r{/t/#{topic.slug}/#{topic.id}})
+ expect(page).to have_current_path(/flat=1/)
+ expect(nested_view).to have_no_nested_view
+ end
+
+ it "does not show the link for users outside allowed groups" do
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_no_flat_view_link
+ end
+ end
+
+ describe "routing" do
+ fab!(:root_reply) { Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "A reply") }
+
+ it "direct URL loads correctly" do
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_nested_view
+ expect(nested_view).to have_root_post(root_reply)
+ expect(page).to have_current_path(%r{/n/#{topic.slug}/#{topic.id}})
+ end
+
+ it "direct URL with post_number loads context view" do
+ chain = create_reply_chain(depth: 3)
+
+ nested_view.visit_nested_context(topic, post_number: chain[1].post_number)
+
+ expect(nested_view).to have_context_view
+ expect(nested_view).to have_post(chain[1])
+ end
+ end
+
+ describe "anonymous access" do
+ fab!(:root_reply) do
+ Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "Public reply")
+ end
+
+ before { Capybara.reset_sessions! }
+
+ it "allows anonymous users to view the nested view" do
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_nested_view
+ expect(nested_view).to have_root_post(root_reply)
+ expect(nested_view).to have_op_post
+ end
+
+ it "does not show reply buttons for anonymous users" do
+ nested_view.visit_nested(topic)
+
+ expect(nested_view).to have_no_reply_button_for(root_reply)
+ expect(nested_view).to have_no_reply_button_on_op
+ expect(nested_view).to have_no_floating_reply_button
+ end
+
+ it "shows login page when anonymous user clicks like" do
+ nested_view.visit_nested(topic)
+ nested_view.click_like_on_post(root_reply)
+
+ expect(page).to have_css(".login-fullpage")
+ end
+ end
+
+ describe "plugin disabled" do
+ it "returns 404 when plugin is disabled" do
+ SiteSetting.nested_replies_enabled = false
+
+ nested_view.visit_nested(topic)
+
+ expect(page).to have_css(".page-not-found")
+ end
+ end
+end
diff --git a/spec/system/page_objects/pages/nested_view.rb b/spec/system/page_objects/pages/nested_view.rb
new file mode 100644
index 00000000000..c1b43aaf143
--- /dev/null
+++ b/spec/system/page_objects/pages/nested_view.rb
@@ -0,0 +1,453 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Pages
+ class NestedView < PageObjects::Pages::Base
+ def visit_nested(topic)
+ page.visit("/n/#{topic.slug}/#{topic.id}")
+ self
+ end
+
+ def visit_nested_context(topic, post_number:, context: nil)
+ url = "/n/#{topic.slug}/#{topic.id}/#{post_number}"
+ url += "?context=#{context}" if context
+ page.visit(url)
+ self
+ end
+
+ # ── Root view assertions ──────────────────────────────────────
+
+ def has_nested_view?
+ has_css?(".nested-view")
+ end
+
+ def has_no_nested_view?
+ has_no_css?(".nested-view")
+ end
+
+ def has_root_post?(post)
+ has_css?(".nested-view__roots [data-post-number='#{post.post_number}']")
+ end
+
+ def has_no_root_post?(post)
+ has_no_css?(".nested-view__roots [data-post-number='#{post.post_number}']")
+ end
+
+ # ── Context view assertions ───────────────────────────────────
+
+ def has_context_view?
+ has_css?(".nested-context-view")
+ end
+
+ def has_view_full_thread_link?
+ has_css?(".nested-context-view__full-thread")
+ end
+
+ def has_view_parent_context_link?
+ has_css?(".nested-context-view__parent-context")
+ end
+
+ def has_no_view_parent_context_link?
+ has_no_css?(".nested-context-view__parent-context")
+ end
+
+ # ── Post assertions ───────────────────────────────────────────
+
+ def has_post_at_depth?(post, depth:)
+ has_css?(".nested-post.--depth-#{depth} [data-post-number='#{post.post_number}']")
+ end
+
+ def has_post?(post)
+ has_css?("[data-post-number='#{post.post_number}']")
+ end
+
+ def has_no_post?(post)
+ has_no_css?("[data-post-number='#{post.post_number}']")
+ end
+
+ def has_continue_thread_for?(post)
+ within(post_container(post)) { has_css?(".nested-post__continue-link") }
+ end
+
+ def has_no_continue_thread_for?(post)
+ within(post_container(post)) { has_no_css?(".nested-post__continue-link") }
+ end
+
+ def has_highlighted_post?(post)
+ has_css?(".nested-post--highlighted [data-post-number='#{post.post_number}']", wait: 5)
+ end
+
+ def has_reply_button_for?(post)
+ has_css?("[data-post-number='#{post.post_number}'] .post-action-menu__reply")
+ end
+
+ def has_no_reply_button_for?(post)
+ has_no_css?("[data-post-number='#{post.post_number}'] .post-action-menu__reply")
+ end
+
+ def has_like_button_for?(post)
+ has_css?("[data-post-number='#{post.post_number}'] .post-action-menu__like")
+ end
+
+ def click_like_on_post(post)
+ find("[data-post-number='#{post.post_number}'] .post-action-menu__like").click
+ end
+
+ def has_replies_toggle_for?(post)
+ has_css?("[data-post-number='#{post.post_number}'] .nested-post__expand-replies")
+ end
+
+ def has_no_replies_toggle_for?(post)
+ has_no_css?("[data-post-number='#{post.post_number}'] .nested-post__expand-replies")
+ end
+
+ def has_no_show_replies_button_for?(post)
+ has_no_css?("[data-post-number='#{post.post_number}'] .post-action-menu__show-replies")
+ end
+
+ def has_depth_line_for?(post)
+ has_css?(wrapper_selector(post, ".nested-post__gutter .nested-post__depth-line"))
+ end
+
+ def has_no_depth_line_for?(post)
+ has_no_css?(wrapper_selector(post, ".nested-post__gutter .nested-post__depth-line"))
+ end
+
+ def has_children_visible_for?(post)
+ has_css?(wrapper_selector(post, ".nested-post-children"))
+ end
+
+ def has_no_children_visible_for?(post)
+ has_no_css?(wrapper_selector(post, ".nested-post-children"))
+ end
+
+ def has_collapsed_bar_for?(post)
+ has_css?(wrapper_selector(post, ".nested-post__collapsed-bar"))
+ end
+
+ def has_no_collapsed_bar_for?(post)
+ has_no_css?(wrapper_selector(post, ".nested-post__collapsed-bar"))
+ end
+
+ def has_post_content_visible_for?(post)
+ has_css?(wrapper_selector(post, ".nested-post__article"))
+ end
+
+ def has_no_post_content_visible_for?(post)
+ has_no_css?(wrapper_selector(post, ".nested-post__article"))
+ end
+
+ def has_flat_view_link?
+ has_css?(".nested-view__flat-link")
+ end
+
+ def has_no_flat_view_link?
+ has_no_css?(".nested-view__flat-link")
+ end
+
+ def has_view_as_nested_link?
+ has_css?(".nested-view-link")
+ end
+
+ def has_no_view_as_nested_link?
+ has_no_css?(".nested-view-link")
+ end
+
+ def has_sort_active?(sort)
+ has_css?(
+ ".nested-sort-selector__option--active",
+ text: I18n.t("js.nested_replies.sort.#{sort}"),
+ )
+ end
+
+ def has_op_post?
+ has_css?(".nested-view__op")
+ end
+
+ def has_no_reply_button_on_op?
+ has_no_css?(".nested-view__op .post-action-menu__reply")
+ end
+
+ def has_topic_title_editor?
+ has_css?(".edit-topic-title")
+ end
+
+ def has_no_topic_title_editor?
+ has_no_css?(".edit-topic-title")
+ end
+
+ def has_topic_map?
+ has_css?(".nested-view__topic-map .topic-map__contents")
+ end
+
+ def has_no_top_replies_button?
+ has_no_css?(".nested-view__topic-map .top-replies")
+ end
+
+ def has_floating_reply_button?
+ has_css?(".nested-view__floating-actions:not(.--hidden) .nested-view__floating-reply")
+ end
+
+ def has_no_floating_reply_button?
+ has_no_css?(".nested-view__floating-actions:not(.--hidden) .nested-view__floating-reply")
+ end
+
+ def has_floating_actions?
+ has_css?(".nested-view__floating-actions:not(.--hidden)")
+ end
+
+ def has_no_floating_actions?
+ has_no_css?(".nested-view__floating-actions:not(.--hidden)")
+ end
+
+ def has_notification_button?
+ has_css?(".nested-view__floating-actions .topic-notifications-button")
+ end
+
+ def has_no_notification_button?
+ has_no_css?(".nested-view__floating-actions .topic-notifications-button")
+ end
+
+ def has_admin_menu_button?
+ has_css?(".nested-view__floating-actions .toggle-admin-menu")
+ end
+
+ def has_no_admin_menu_button?
+ has_no_css?(".nested-view__floating-actions .toggle-admin-menu")
+ end
+
+ # ── Actions ───────────────────────────────────────────────────
+
+ def click_edit_topic
+ find(".nested-view__title .fancy-title").click
+ self
+ end
+
+ def click_cancel_edit_topic
+ find(".edit-topic-title .cancel-edit").click
+ self
+ end
+
+ def click_save_edit_topic
+ find(".edit-topic-title .submit-edit").click
+ self
+ end
+
+ def fill_in_topic_title(title)
+ find(".edit-topic-title input#edit-title").fill_in(with: title)
+ self
+ end
+
+ def click_post_edit_button(post)
+ within("[data-post-number='#{post.post_number}']") do
+ find(".show-more-actions").click if has_css?(".show-more-actions", wait: 2)
+ find("button.edit").click
+ end
+ self
+ end
+
+ def click_reply_on_post(post)
+ find("[data-post-number='#{post.post_number}'] .post-action-menu__reply").click
+ self
+ end
+
+ def click_reply_on_op
+ find(".nested-view__op .post-action-menu__reply").click
+ self
+ end
+
+ def click_continue_thread(post)
+ within(post_container(post)) { find(".nested-post__continue-link").click }
+ self
+ end
+
+ def click_depth_line(post)
+ find(wrapper_selector(post, ".nested-post__depth-line")).click
+ self
+ end
+
+ def click_collapsed_bar(post)
+ find(wrapper_selector(post, ".nested-post__collapsed-bar")).click
+ self
+ end
+
+ def click_view_full_thread
+ find(".nested-context-view__full-thread").click
+ self
+ end
+
+ def click_view_parent_context
+ find(".nested-context-view__parent-context").click
+ self
+ end
+
+ def click_floating_reply_button
+ find(".nested-view__floating-reply").click
+ self
+ end
+
+ def open_admin_menu
+ find(".nested-view__floating-actions .toggle-admin-menu").click
+ self
+ end
+
+ def click_admin_close_topic
+ open_admin_menu
+ find(".topic-admin-close .btn").click
+ self
+ end
+
+ def click_admin_open_topic
+ open_admin_menu
+ find(".topic-admin-open .btn").click
+ self
+ end
+
+ def change_notification_level(level)
+ find(
+ ".nested-view__floating-actions .topic-notifications-button .notifications-tracking-trigger-btn",
+ ).click
+ find(".notifications-tracking-btn[data-level-id='#{level}']").click
+ self
+ end
+
+ def click_copy_link_on_op
+ within(".nested-view__op") do
+ find(".show-more-actions").click if has_css?(".show-more-actions", wait: 0)
+ find("button.post-action-menu__copy-link").click
+ end
+ self
+ end
+
+ def click_copy_link_on_post(post)
+ within("[data-post-number='#{post.post_number}']") do
+ find(".show-more-actions").click if has_css?(".show-more-actions", wait: 0)
+ find("button.post-action-menu__copy-link").click
+ end
+ self
+ end
+
+ def click_flat_view_link
+ find(".nested-view__flat-link").click
+ self
+ end
+
+ def click_sort(sort)
+ find(".nested-sort-selector__option", text: I18n.t("js.nested_replies.sort.#{sort}")).click
+ self
+ end
+
+ # ── Deletion/recovery assertions ─────────────────────────────
+
+ def has_deleted_placeholder_for?(post)
+ has_css?("[data-post-number='#{post.post_number}'].nested-post__deleted-placeholder")
+ end
+
+ def has_no_deleted_placeholder_for?(post)
+ has_no_css?("[data-post-number='#{post.post_number}'].nested-post__deleted-placeholder")
+ end
+
+ def has_deleted_post_class_for?(post)
+ has_css?(".nested-post--deleted [data-post-number='#{post.post_number}']")
+ end
+
+ def has_toggle_deleted_content_button_for?(post)
+ has_css?("[data-post-number='#{post.post_number}'] button.toggle-deleted-content")
+ end
+
+ def has_no_toggle_deleted_content_button_for?(post)
+ has_no_css?("[data-post-number='#{post.post_number}'] button.toggle-deleted-content")
+ end
+
+ def click_toggle_deleted_content(post)
+ find("[data-post-number='#{post.post_number}'] button.toggle-deleted-content").click
+ self
+ end
+
+ def has_deleted_content_visible_for?(post)
+ has_css?(wrapper_selector(post, ".nested-post__deleted-content"))
+ end
+
+ def has_no_deleted_content_visible_for?(post)
+ has_no_css?(wrapper_selector(post, ".nested-post__deleted-content"))
+ end
+
+ # ── Post actions ────────────────────────────────────────────
+
+ def click_post_delete_button(post)
+ within("[data-post-number='#{post.post_number}']") do
+ find(".show-more-actions").click if has_css?(".show-more-actions", wait: 2)
+ find("button.delete").click
+ end
+ self
+ end
+
+ def click_post_recover_button(post)
+ selector = "[data-post-number='#{post.post_number}']"
+ if has_css?("#{selector} button.recover", wait: 5)
+ find("#{selector} button.recover").click
+ else
+ within(selector) do
+ find(".show-more-actions").click
+ find("button.recover").click
+ end
+ end
+ self
+ end
+
+ # ── Pinned post assertions ─────────────────────────────────
+
+ def has_pinned_post?(post)
+ has_css?(".nested-post--pinned [data-post-number='#{post.post_number}']")
+ end
+
+ def has_no_pinned_post?(post)
+ has_no_css?(".nested-post--pinned [data-post-number='#{post.post_number}']")
+ end
+
+ # ── Load more ───────────────────────────────────────────────
+
+ def has_load_more_roots_button?
+ has_css?(".nested-view__load-more")
+ end
+
+ def click_load_more_roots
+ find(".nested-view__load-more").click
+ self
+ end
+
+ # ── Cloaking ─────────────────────────────────────────────────
+
+ def has_cloaked_root?
+ has_css?(".nested-view__roots > .nested-post--cloaked")
+ end
+
+ def has_no_cloaked_root?
+ has_no_css?(".nested-view__roots > .nested-post--cloaked")
+ end
+
+ def has_cloaked_root_for?(post)
+ has_css?(".nested-post--cloaked [data-post-number='#{post.post_number}']")
+ end
+
+ def has_uncloaked_root_for?(post)
+ has_no_css?(".nested-post--cloaked [data-post-number='#{post.post_number}']") &&
+ has_css?("[data-post-number='#{post.post_number}']")
+ end
+
+ private
+
+ def post_container(post)
+ find("[data-post-number='#{post.post_number}']")
+ end
+
+ def wrapper_selector(post, child_selector = nil)
+ # Builds a CSS selector that targets the DIRECT .nested-post wrapper for
+ # the given post, without storing any find() results. Uses > combinators
+ # to avoid matching ancestor .nested-post wrappers in the nested tree.
+ base = ".nested-post:has(> .nested-post__main > [data-post-number='#{post.post_number}'])"
+ child_selector ? "#{base} #{child_selector}" : base
+ end
+ end
+ end
+end
diff --git a/spec/system/view_as_nested_button_spec.rb b/spec/system/view_as_nested_button_spec.rb
new file mode 100644
index 00000000000..dbbc02c8a06
--- /dev/null
+++ b/spec/system/view_as_nested_button_spec.rb
@@ -0,0 +1,54 @@
+# frozen_string_literal: true
+
+RSpec.describe "View as nested button" do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:admin)
+ fab!(:category)
+ fab!(:nested_category) { Fabricate(:category, name: "Nested Category") }
+ fab!(:topic) { Fabricate(:topic, user: user, category: category) }
+ fab!(:op) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+ fab!(:reply) { Fabricate(:post, topic: topic, user: Fabricate(:user), raw: "A reply") }
+ fab!(:nested_topic) { Fabricate(:topic, user: user, category: nested_category) }
+ fab!(:nested_op) { Fabricate(:post, topic: nested_topic, user: user, post_number: 1) }
+ fab!(:nested_reply) do
+ Fabricate(:post, topic: nested_topic, user: Fabricate(:user), raw: "A nested reply")
+ end
+
+ let(:nested_view) { PageObjects::Pages::NestedView.new }
+
+ before do
+ SiteSetting.nested_replies_enabled = true
+ nested_category.category_setting.update!(nested_replies_default: true)
+ Fabricate(:nested_topic, topic: nested_topic)
+ end
+
+ it "does not show the link on a normal topic" do
+ sign_in(admin)
+ page.visit("/t/#{topic.slug}/#{topic.id}")
+
+ expect(nested_view).to have_no_view_as_nested_link
+ end
+
+ it "shows the link on a nested topic for users in the allowed group" do
+ sign_in(admin)
+ page.visit("/t/#{nested_topic.slug}/#{nested_topic.id}?flat=1")
+
+ expect(nested_view).to have_view_as_nested_link
+ end
+
+ it "does not show the link for users outside the allowed group" do
+ sign_in(user)
+ page.visit("/t/#{nested_topic.slug}/#{nested_topic.id}?flat=1")
+
+ expect(nested_view).to have_no_view_as_nested_link
+ end
+
+ it "shows the link when topic has a nested_topic record" do
+ sign_in(admin)
+ Fabricate(:nested_topic, topic: topic)
+
+ page.visit("/t/#{topic.slug}/#{topic.id}?flat=1")
+
+ expect(nested_view).to have_view_as_nested_link
+ end
+end
diff --git a/vendor/assets/svg-icons/nested-replies-icons.svg b/vendor/assets/svg-icons/nested-replies-icons.svg
new file mode 100644
index 00000000000..acd34860c13
--- /dev/null
+++ b/vendor/assets/svg-icons/nested-replies-icons.svg
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
+ <symbol id="nested-circle-plus" viewBox="0 0 20 20">
+ <path fill-rule="evenodd" d="M10 1A9 9 0 0 1 10 19A9 9 0 0 1 10 1ZM10 3A7 7 0 0 1 10 17A7 7 0 0 1 10 3Z"/>
+ <path d="M6 9h8v2H6zM9 6h2v8H9z"/>
+ </symbol>
+ <symbol id="nested-circle-minus" viewBox="0 0 20 20">
+ <path fill-rule="evenodd" d="M10 1A9 9 0 0 1 10 19A9 9 0 0 1 10 1ZM10 3A7 7 0 0 1 10 17A7 7 0 0 1 10 3Z"/>
+ <path d="M6 9h8v2H6z"/>
+ </symbol>
+ <symbol id="nested-thread" viewBox="0 0 16 15" fill-rule="evenodd" clip-rule="evenodd">
+ <path d="M5 0L4.57143 3H1V5H4.28571L3.71429 9H0V11H3.42857L3 14L4.9799 14.2828L5.44888 11H9.16317L8.59173 14.2828L10.5714 14.5657L11.1429 11H15V9H11.4286L12.0602 5H16V3H12.3459L12.9799 0.282843L11 0L10.4286 3H6.59173L6.9799 0.282843L5 0ZM6.30602 5L5.73459 9H9.44888L10.0204 5H6.30602Z"/>
+ </symbol>
+</svg>