OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
Preserve scroll during infinite scroll page render
Kabiru Mwenjaaa7901d3cba6
diff --git a/app/components/work_packages/activities_tab/journals/index_component.rb b/app/components/work_packages/activities_tab/journals/index_component.rbindex 86d049ca7ed..f0f6fad66b8 100644--- a/app/components/work_packages/activities_tab/journals/index_component.rb+++ b/app/components/work_packages/activities_tab/journals/index_component.rb@@ -55,6 +55,9 @@ module WorkPackagesWorkPackages::ActivitiesTab::Journals::PageComponent.new(journals:, emoji_reactions:, page:, filter:)end+ def self.insert_target_modifier_id = "#{wrapper_key}-pages"+ delegate :insert_target_modifier_id, to: :class+privateattr_reader :work_package, :journals, :page, :next_page, :filterdiff --git a/app/components/work_packages/activities_tab/journals/infinite_scroll_component.rb b/app/components/work_packages/activities_tab/journals/infinite_scroll_component.rbindex dd0a8932781..b09fda12557 100644--- a/app/components/work_packages/activities_tab/journals/infinite_scroll_component.rb+++ b/app/components/work_packages/activities_tab/journals/infinite_scroll_component.rb@@ -50,12 +50,17 @@ module WorkPackagesdef wrapper_data_attributes{controller: infinite_scroll_stimulus_controller,+ infinite_scroll_stimulus_controller("-insert-target-id-value") => insert_target_id,infinite_scroll_stimulus_controller("-page-value") => page,infinite_scroll_stimulus_controller("-is-last-page-value") => next_page.blank?,infinite_scroll_stimulus_controller("-url-value") => page_streams_url}end+ def insert_target_id+ WorkPackages::ActivitiesTab::Journals::IndexComponent.insert_target_modifier_id+ end+def page_streams_urlpage_streams_work_package_activities_path(work_package, format: :turbo_stream)enddiff --git a/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/infinite-scroll.controller.ts b/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/infinite-scroll.controller.tsindex 652c388b139..cc38cf63210 100644--- a/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/infinite-scroll.controller.ts+++ b/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/infinite-scroll.controller.ts@@ -28,9 +28,11 @@* ++*/-import BaseController from './base.controller';import { TurboRequestsService } from 'core-app/core/turbo/turbo-requests.service';+import type { TurboBeforeStreamRenderEvent } from 'core-typings/turbo';import { useIntersection } from 'stimulus-use';+import BaseController from './base.controller';+import { DomHelpers } from './services/dom_helpers';export default class extends BaseController {static values = {@@ -52,6 +54,8 @@ export default class extends BaseController {private updateInProgress = false;private turboRequests:TurboRequestsService;+ private abortController = new AbortController();+ private pageStreamHandler?:(_event:TurboBeforeStreamRenderEvent) => void;connect() {if (this.isLastPageValue) return;@@ -59,6 +63,14 @@ export default class extends BaseController {super.connect();void this.initializeTurboRequestService();useIntersection(this, { threshold: 1.0 });++ this.setupScrollPreservation();+ }++ disconnect() {+ super.disconnect();+ this.abortController.abort();+ if (this.pageStreamHandler) this.pageStreamHandler = undefined;}async appear() {@@ -81,6 +93,31 @@ export default class extends BaseController {}}+ setupScrollPreservation() {+ if (!this.scrollableContainer || this.pageStreamHandler) return;++ const { signal } = this.abortController;++ this.pageStreamHandler = (event:TurboBeforeStreamRenderEvent) => {+ event.preventDefault();++ const stream = event.detail.newStream;+ const scrollContainer = this.scrollableContainer!;++ if (stream.target.includes(this.insertTargetIdValue)) {+ const isPrepend = stream.action === 'prepend';+ void DomHelpers.keepScroll(scrollContainer, isPrepend, () => {+ event.detail.render(stream);+ return Promise.resolve();+ });+ } else {+ event.detail.render(stream);+ }+ };++ document.addEventListener('turbo:before-stream-render', this.pageStreamHandler as EventListener, { signal });+ }+private fetchNextPageStream():Promise<{ html:string, headers:Headers }> {const url = this.preparePageStreamsUrl();return this.turboRequests.requestStream(url);diff --git a/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/services/dom_helpers.ts b/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/services/dom_helpers.tsnew file mode 100644index 00000000000..9427231a758--- /dev/null+++ b/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/services/dom_helpers.ts@@ -0,0 +1,98 @@+/*+* -- copyright+* OpenProject is an open source project management software.+* Copyright (C) 2023 the OpenProject GmbH+*+* This program is free software; you can redistribute it and/or+* modify it under the terms of the GNU General Public License version 3.+*+* OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+* Copyright (C) 2006-2013 Jean-Philippe Lang+* Copyright (C) 2010-2013 the ChiliProject Team+*+* This program is free software; you can redistribute it and/or+* modify it under the terms of the GNU General Public License+* as published by the Free Software Foundation; either version 2+* of the License, or (at your option) any later version.+*+* This program is distributed in the hope that it will be useful,+* but WITHOUT ANY WARRANTY; without even the implied warranty of+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+* GNU General Public License for more details.+*+* You should have received a copy of the GNU General Public License+* along with this program; if not, write to the Free Software+* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+*+* See COPYRIGHT and LICENSE files for more details.+* +++*/++export namespace DomHelpers {+ /**+ * Preserves scroll position during DOM manipulations that change content height.+ *+ * This is crucial for infinite scroll UX - when older content is prepended above+ * the current view, we need to adjust scroll position so the user doesn't suddenly+ * jump to a different part of the content.+ *+ * @param {HTMLElement} container - The scrollable container+ * @param {boolean} top - Whether content is being added at the top (prepend)+ * true: adjust scroll for prepended content+ * false: maintain position for appended content+ * @param {Function} fn - Async function that performs the DOM manipulation+ *+ * Algorithm:+ * - Capture current scroll position and total height BEFORE DOM changes+ * - Execute the DOM manipulation (adding/removing content)+ * - Calculate height difference and adjust scroll position accordingly+ *+ * For prepend: scrollTop + heightDifference (push view down by added content height)+ * For append: maintain original scrollTop (new content below doesn't affect view)+ */+ export async function keepScroll(container:HTMLElement, top:boolean, fn:() => Promise<void>) {+ pauseInertiaScroll(container);++ const scrollTop = container.scrollTop;+ const scrollHeight = container.scrollHeight;++ await fn();++ if (top) {+ container.scrollTop = scrollTop + (container.scrollHeight - scrollHeight);+ } else {+ container.scrollTop = scrollTop;+ }+ }++ /**+ * Temporarily pauses inertial/momentum scrolling to prevent scroll position drift.+ *+ * CRITICAL for iOS Safari and other mobile browsers with momentum scrolling!+ *+ * The Problem:+ * When programmatically setting scrollTop during an active momentum scroll,+ * the browser continues the inertial scroll AFTER our position adjustment,+ * causing the scroll position to drift away from our intended target.+ *+ * The Solution:+ * - Set overflow: hidden to immediately stop any momentum scrolling+ * - Use requestAnimationFrame to restore overflow on next frame+ * - This gives us a clean slate to set the exact scroll position+ *+ * Without this, scroll preservation would be unreliable on mobile devices,+ * especially during infinite scroll when users are actively scrolling up.+ *+ * Credit: This technique was adapted from Basecamp's Campfire implementation+ * where they solved similar scroll position issues in their real-time chat.+ *+ * @param {Element} container - The scrollable container to pause momentum on+ */+ function pauseInertiaScroll(container:HTMLElement) {+ container.style.overflow = 'hidden';++ requestAnimationFrame(() => {+ container.style.overflow = '';+ });+ }+}diff --git a/frontend/src/typings/turbo.d.ts b/frontend/src/typings/turbo.d.tsindex e7a6389d8e4..ef9bcfed146 100644--- a/frontend/src/typings/turbo.d.ts+++ b/frontend/src/typings/turbo.d.ts@@ -6,3 +6,10 @@ export interface TurboStreamElement extends HTMLElement {action:string;target:string;}++export interface TurboBeforeStreamRenderEvent extends CustomEvent {+ detail:{+ newStream:TurboStreamElement;+ render:(stream:TurboStreamElement) => void;+ };+}