Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent scrolling to the top of the page on websocket reload #1097

Merged
merged 1 commit into from
Nov 19, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/cmd/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@
use super::watch;
use crate::{get_book_dir, open};
use clap::{App, Arg, ArgMatches, SubCommand};
use iron::headers;
use iron::{status, AfterMiddleware, Chain, Iron, IronError, IronResult, Request, Response, Set};
use mdbook::errors::*;
use mdbook::utils;
use mdbook::MDBook;

struct ErrorRecover;

struct NoCache;

// Create clap subcommand arguments
pub fn make_subcommand<'a, 'b>() -> App<'a, 'b> {
SubCommand::with_name("serve")
Expand Down Expand Up @@ -86,6 +89,7 @@ pub fn execute(args: &ArgMatches) -> Result<()> {
book.build()?;

let mut chain = Chain::new(staticfile::Static::new(book.build_dir_for("html")));
chain.link_after(NoCache);
chain.link_after(ErrorRecover);
let _iron = Iron::new(chain)
.http(&*address)
Expand Down Expand Up @@ -133,6 +137,17 @@ pub fn execute(args: &ArgMatches) -> Result<()> {
Ok(())
}

impl AfterMiddleware for NoCache {
fn after(&self, _: &mut Request, mut res: Response) -> IronResult<Response> {
res.headers.set(headers::CacheControl(vec![
headers::CacheDirective::NoStore,
headers::CacheDirective::MaxAge(0u32),
]));

Ok(res)
}
}

impl AfterMiddleware for ErrorRecover {
fn catch(&self, _: &mut Request, err: IronError) -> IronResult<Response> {
match err.response.status {
Expand Down
2 changes: 1 addition & 1 deletion src/theme/index.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@
socket.onmessage = function (event) {
if (event.data === "reload") {
socket.close();
location.reload(true); // force reload from server (not from cache)
location.reload();
}
};

Expand Down