Skip to content

Commit 41be15a

Browse files
authored
Merge pull request #2667 from spamguy/2130
Scroll to top of view upon route entry
2 parents c8e8f32 + 5525cff commit 41be15a

File tree

2 files changed

+23
-7
lines changed

2 files changed

+23
-7
lines changed

assets/javascripts/lib/page.js

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -98,26 +98,35 @@ page.canGoForward = () => !Context.isLastState(currentState);
9898
const currentPath = () => location.pathname + location.search + location.hash;
9999

100100
class Context {
101+
/**
102+
* A counter tracking the largest state ID used.
103+
*/
104+
static stateId = 0;
105+
106+
/**
107+
* The session ID to apply across all contexts.
108+
*/
109+
static sessionId = Date.now();
110+
101111
static isIntialState(state) {
102112
return state.id === 0;
103113
}
104114

105115
static isLastState(state) {
106-
return state.id === this.stateId - 1;
116+
return state.id === Context.stateId - 1;
107117
}
108118

109119
static isInitialPopState(state) {
110-
return state.path === this.initialPath && this.stateId === 1;
120+
return state.path === this.initialPath && Context.stateId === 1;
111121
}
112122

113123
static isSameSession(state) {
114-
return state.sessionId === this.sessionId;
124+
return state.sessionId === Context.sessionId;
115125
}
116126

117127
constructor(path, state) {
118128
this.initialPath = currentPath();
119-
this.sessionId = Date.now();
120-
this.stateId = 0;
129+
121130
if (path == null) {
122131
path = "/";
123132
}
@@ -136,10 +145,11 @@ class Context {
136145
);
137146

138147
if (this.state.id == null) {
139-
this.state.id = this.constructor.stateId++;
148+
Context.stateId++;
149+
this.state.id = Context.stateId;
140150
}
141151
if (this.state.sessionId == null) {
142-
this.state.sessionId = this.constructor.sessionId;
152+
this.state.sessionId = Context.sessionId;
143153
}
144154
this.state.path = this.path;
145155
}

assets/javascripts/views/content/content.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,12 @@ app.views.Content = class Content extends app.View {
149149

150150
beforeRoute(context) {
151151
this.cacheScrollPosition();
152+
153+
// If scroll position wasn't cached from an earlier visit, scroll to top.
154+
if (!this.scrollMap[context.state.id]) {
155+
this.scrollToTop();
156+
}
157+
152158
this.routeCtx = context;
153159
this.scrollToTargetTimeout = this.delay(this.scrollToTarget);
154160
}

0 commit comments

Comments
 (0)