history源码解析-管理会话历史记录

history是一个JavaScript库,可以让你在JavaScript运行的任何地方轻松管理会话历史记录javascript

1.前言

history是由Facebook维护的,react-router依赖于history,区别于浏览器的window.historyhistory是包含window.history的,让开发者能够在任何环境都能使用history的api(例如NodeReact Native等)。html

本篇读后感分为五部分,分别为前言、使用、解析、demo、总结,五部分互不相连可根据须要分开看。java

前言为介绍、使用为库的使用、解析为源码的解析、demo是抽取源码的核心实现的小demo,总结为吹水,学以至用。react

建议跟着源码结合本文阅读,这样更加容易理解!git

  1. history
  2. history解析的Github地址
  3. 手把手带你上react-router的history车(掘金)

2.使用

history有三种不一样的方法建立history对象,取决于你的代码环境:github

  1. createBrowserHistory:支持HTML5 history api的现代浏览器(例如:/index);
  2. createHashHistory:传统浏览器(例如:/#/index);
  3. createMemoryHistory:没有Dom的环境(例如:NodeReact Native)。

注意:本片文章只解析createBrowserHistory,其实三种构造原理都是差很少的api

<!DOCTYPE html>
<html>
  <head>
    <script src="./umd/history.js"></script>
    <script> var createHistory = History.createBrowserHistory // var createHistory = History.createHashHistory var page = 0 // createHistory建立所须要的history对象 var h = createHistory() // h.block触发在地址栏改变以前,用于告知用户地址栏即将改变 h.block(function (location, action) { return 'Are you sure you want to go to ' + location.path + '?' }) // h.listen监听当前地址栏的改变 h.listen(function (location) { console.log(location, 'lis-1') }) </script>
  </head>
  <body>
    <p>Use the two buttons below to test normal transitions.</p>
    <p>
      <!-- h.push用于跳转 -->
      <button onclick="page++; h.push('/' + page, { page: page })">history.push</button>
      <!-- <button onclick="page++; h.push('/#/' + page)">history.push</button> -->

      <button onclick="h.goBack()">history.goBack</button>
    </p>
  </body>
</html>
复制代码

block用于地址改变以前的截取,listener用于监听地址栏的改变,pushreplacego(n)等用于跳转,用法简单明了数组

3.解析

贴出来的源码我会删减对理解原理不重要的部分!!!若是想看完整的请下载源码看哈浏览器

从history的源码库目录能够看到modules文件夹,包含了几个文件:react-router

  1. createBrowserHistory.js 建立createBrowserHistory的history对象;
  2. createHashHistory.js 建立createHashHistory的history对象;
  3. createMemoryHistory.js 建立createMemoryHistory的history对象;
  4. createTransitionManager.js 过渡管理(例如:处理block函数中的弹框、处理listener的队列);
  5. DOMUtils.js Dom工具类(例如弹框、判断浏览器兼容性);
  6. index.js 入口文件;
  7. LocationUtils.js 处理Location工具;
  8. PathUtils.js 处理Path工具。

入口文件index.js

export { default as createBrowserHistory } from "./createBrowserHistory";
export { default as createHashHistory } from "./createHashHistory";
export { default as createMemoryHistory } from "./createMemoryHistory";
export { createLocation, locationsAreEqual } from "./LocationUtils";
export { parsePath, createPath } from "./PathUtils";
复制代码

把全部须要暴露的方法根据文件名区分开,咱们先看history的构造函数createBrowserHistory

3.1 createBrowserHistory

// createBrowserHistory.js
function createBrowserHistory(props = {}){
  // 浏览器的history
  const globalHistory = window.history;
  // 初始化location
  const initialLocation = getDOMLocation(window.history.state);
  // 建立地址
  function createHref(location) {
    return basename + createPath(location);
  }

  ...

  const history = {
    // window.history属性长度
    length: globalHistory.length,

    // history 当前行为(包含PUSH-进入、POP-弹出、REPLACE-替换)
    action: "POP",

    // location对象(与地址有关)
    location: initialLocation,

    // 当前地址(包含pathname)
    createHref,

    // 跳转的方法
    push,
    replace,
    go,
    goBack,
    goForward,

    // 截取
    block,

    // 监听
    listen
  };

  return history;
}

export default createBrowserHistory;
复制代码

不管是从代码仍是从用法上咱们也能够看出,执行了createBrowserHistory后函数会返回history对象,history对象提供了不少属性和方法,最大的疑问应该是initialLocation函数,即history.location。咱们的解析顺序以下:

  1. location;
  2. createHref;
  3. block;
  4. listen;
  5. push;
  6. replace。

3.2 location

location属性存储了与地址栏有关的信息,咱们对比下createBrowserHistory的返回值history.locationwindow.location

// history.location
history.location = {
  hash: ""
  pathname: "/history/index.html"
  search: "?_ijt=2mt7412gnfvjpfeuv4hjkq2uf8"
  state: undefined
}

// window.location
window.location = {
  hash: ""
  host: "localhost:63342"
  hostname: "localhost"
  href: "http://localhost:63342/history/index.html?_ijt=2mt7412gnfvjpfeuv4hjkq2uf8"
  origin: "http://localhost:63342"
  pathname: "/history/index.html"
  port: "63342"
  protocol: "http:"
  reload: ƒ reload()
  replace: ƒ ()
  search: "?_ijt=2mt7412gnfvjpfeuv4hjkq2uf8"
}
复制代码

结论是history.location是window.location的儿砸!咱们来研究研究做者是怎么处理的。

const initialLocation = getDOMLocation(window.history.state)
复制代码

initialLocation函数等于getDOMLocation函数的返回值(getDOMLocationhistory中会常常调用,理解好这个函数比较重要)。

// createBrowserHistory.js
function createBrowserHistory(props = {}){
  // 处理basename(相对地址,例如:首页为index,假如设置了basename为/the/base,那么首页为/the/base/index)
  const basename = props.basename ? stripTrailingSlash(addLeadingSlash(props.basename)) : "";
  
  const initialLocation = getDOMLocation(window.history.state);

  // 处理state参数和window.location
  function getDOMLocation(historyState) {
    const { key, state } = historyState || {};
    const { pathname, search, hash } = window.location;

    let path = pathname + search + hash;

    // 保证path是不包含basename的
    if (basename) path = stripBasename(path, basename);

    // 建立history.location对象
    return createLocation(path, state, key);
  };

  const history = {
    // location对象(与地址有关)
    location: initialLocation,
    ...
  };

  return history;
}
复制代码

通常大型的项目中都会把一个功能拆分红至少两个函数,一个专门处理参数的函数和一个接收处理参数实现功能的函数:

  1. 处理参数:getDOMLocation函数主要处理statewindow.location这两参数,返回自定义的history.location对象,主要构造history.location对象是createLocation函数;
  2. 构造功能:createLocation实现具体构造location的逻辑。

接下来咱们看在LocationUtils.js文件中的createLocation函数

// LocationUtils.js
import { parsePath } from "./PathUtils";

export function createLocation(path, state, key, currentLocation) {
  let location;
  if (typeof path === "string") {
    // 两个参数 例如: push(path, state)

    // parsePath函数用于拆解地址 例如:parsePath('www.aa.com/aa?b=bb') => {pathname: 'www.aa.com/aa', search: '?b=bb', hash: ''}
    location = parsePath(path);
    location.state = state;
  } else {
    // 一个参数 例如: push(location)
    location = { ...path };

    location.state = state;
  }

  if (key) location.key = key;

  // location = {
  // hash: ""
  // pathname: "/history/index.html"
  // search: "?_ijt=2mt7412gnfvjpfeuv4hjkq2uf8"
  // state: undefined
  // }
  return location;
}

// PathUtils.js
export function parsePath(path) {
  let pathname = path || "/";
  let search = "";
  let hash = "";

  const hashIndex = pathname.indexOf("#");
  if (hashIndex !== -1) {
    hash = pathname.substr(hashIndex);
    pathname = pathname.substr(0, hashIndex);
  }

  const searchIndex = pathname.indexOf("?");
  if (searchIndex !== -1) {
    search = pathname.substr(searchIndex);
    pathname = pathname.substr(0, searchIndex);
  }

  return {
    pathname,
    search: search === "?" ? "" : search,
    hash: hash === "#" ? "" : hash
  };
}
复制代码

createLocation根据传递进来的path或者location值,返回格式化好的location,代码简单。

3.3 createHref

createHref函数的做用是返回当前路径名,例如地址http://localhost:63342/history/index.html?a=1,调用h.createHref(location)后返回/history/index.html?a=1

// createBrowserHistory.js
import {createPath} from "./PathUtils";

function createBrowserHistory(props = {}){
  // 处理basename(相对地址,例如:首页为index,假如设置了basename为/the/base,那么首页为/the/base/index)
  const basename = props.basename ? stripTrailingSlash(addLeadingSlash(props.basename)) : "";

  function createHref(location) {
    return basename + createPath(location);
  }
  
  const history = {
    // 当前地址(包含pathname)
    createHref,
    ...
  };

  return history;
}

// PathUtils.js
function createPath(location) {
  const { pathname, search, hash } = location;

  let path = pathname || "/";
  
  if (search && search !== "?") path += search.charAt(0) === "?" ? search : `?${search}`;

  if (hash && hash !== "#") path += hash.charAt(0) === "#" ? hash : `#${hash}`;

  return path;
}
复制代码

3.4 listen

在这里咱们能够想象下大概的 监听 流程:

  1. 绑定咱们设置的监听函数;
  2. 监听历史记录条目的改变,触发监听函数。

第二章使用代码中,建立了History对象后使用了h.listen函数。

// index.html
h.listen(function (location) {
  console.log(location, 'lis-1')
})
h.listen(function (location) {
  console.log(location, 'lis-2')
})
复制代码

可见listen能够绑定多个监听函数,咱们先看做者的createTransitionManager.js是如何实现绑定多个监听函数的。

createTransitionManager是过渡管理(例如:处理block函数中的弹框、处理listener的队列)。代码风格跟createBrowserHistory几乎一致,暴露全局函数,调用后返回对象便可使用。

// createTransitionManager.js
function createTransitionManager() {
  let listeners = [];

  // 设置监听函数
  function appendListener(fn) {
    let isActive = true;

    function listener(...args) {
      // good
      if (isActive) fn(...args);
    }

    listeners.push(listener);

    // 解除
    return () => {
      isActive = false;
      listeners = listeners.filter(item => item !== listener);
    };
  }

  // 执行监听函数
  function notifyListeners(...args) {
    listeners.forEach(listener => listener(...args));
  }

  return {
    appendListener,
    notifyListeners
  };
}
复制代码
  1. 设置监听函数appendListenerfn就是用户设置的监听函数,把全部的监听函数存储在listeners数组中;
  2. 执行监听函数notifyListeners:执行的时候仅仅须要循环依次执行便可。

这里感受有值得借鉴的地方:添加队列函数时,增长状态管理(如上面代码的isActive),决定是否启用。

有了上面的理解,下面看listen源码。

// createBrowserHistory.js
import createTransitionManager from "./createTransitionManager";
const transitionManager = createTransitionManager();

function createBrowserHistory(props = {}){
  function listen(listener) {
    // 添加 监听函数 到 队列
    const unlisten = transitionManager.appendListener(listener);

    // 添加 历史记录条目 的监听
    checkDOMListeners(1);

    // 解除监听
    return () => {
      checkDOMListeners(-1);
      unlisten();
    };
  }

  const history = {
    // 监听
    listen
    ...
  };

  return history;
}


复制代码

history.listen是当历史记录条目改变时,触发回调监听函数。因此这里有两步:

  1. transitionManager.appendListener(listener)把回调的监听函数添加到队列里;
  2. checkDOMListeners监听历史记录条目的改变;

下面看看如何历史记录条目的改变checkDOMListeners(1)

// createBrowserHistory.js
function createBrowserHistory(props = {}){
  let listenerCount = 0;

  function checkDOMListeners(delta) {
    listenerCount += delta;
    
    // 是否已经添加
    if (listenerCount === 1 && delta === 1) {
      // 添加绑定,当历史记录条目改变的时候
      window.addEventListener('popstate', handlePopState);
    } else if (listenerCount === 0) {
      // 解除绑定
      window.removeEventListener('popstate', handlePopState);
    }
  }
  
  // getDOMLocation(event.state) = location = {
  // hash: ""
  // pathname: "/history/index.html"
  // search: "?_ijt=2mt7412gnfvjpfeuv4hjkq2uf8"
  // state: undefined
  // }
  function handlePopState(event) {
    handlePop(getDOMLocation(event.state));
  }
  
  function handlePop(location) {
    const action = "POP";
    setState({ action, location })
  }
}
复制代码

虽然做者写了不少很细的回调函数,可能会致使有些很差理解,但细细看仍是有它道理的:

  1. checkDOMListeners:全局只能有一个监听历史记录条目的函数(listenerCount来控制);
  2. handlePopState:必须把监听函数提取出来,否则不能解绑;
  3. handlePop:监听历史记录条目的核心函数,监听成功后执行setState

setState({ action, location })做用是根据当前地址信息(location)更新history。

// createBrowserHistory.js
function createBrowserHistory(props = {}){
  function setState(nextState) {
    // 更新history
    Object.assign(history, nextState);
    history.length = globalHistory.length;

    // 执行监听函数listen
    transitionManager.notifyListeners(history.location, history.action);
  }

  const history = {
    // 监听
    listen
    ...
  };

  return history;
}
复制代码

在这里,当更改历史记录条目成功后:

  1. 更新history;
  2. 执行监听函数listen;

这就是h.listen的主要流程了,是否是还挺简单的。

3.5 block

history.block的功能是当历史记录条目改变时,触发提示信息。在这里咱们能够想象下大概的 截取 流程:

  1. 绑定咱们设置的截取函数;
  2. 监听历史记录条目的改变,触发截取函数。

哈哈这里是否是感受跟listen函数的套路差很少呢?其实h.listenh.block的监听历史记录条目改变的代码是公用同一套(固然拉只能绑定一个监听历史记录条目改变的函数),3.1.3为了方便理解我修改了部分代码,下面是完整的源码。


第二章使用代码中,建立了History对象后使用了h.block函数(只能绑定一个block函数)。

// index.html
h.block(function (location, action) {
  return 'Are you sure you want to go to ' + location.path + '?'
})
复制代码

一样的咱们先看看做者的createTransitionManager.js是如何实现提示的。

createTransitionManager是过渡管理(例如:处理block函数中的弹框、处理listener的队列)。代码风格跟createBrowserHistory几乎一致,暴露全局函数,调用后返回对象便可使用。

// createTransitionManager.js
function createTransitionManager() {
  let prompt = null;

  // 设置提示
  function setPrompt(nextPrompt) {
    prompt = nextPrompt;

    // 解除
    return () => {
      if (prompt === nextPrompt) prompt = null;
    };
  }

  /** * 实现提示 * @param location:地址 * @param action:行为 * @param getUserConfirmation 设置弹框 * @param callback 回调函数:block函数的返回值做为参数 */
  function confirmTransitionTo(location, action, getUserConfirmation, callback) {
    if (prompt != null) {
      const result = typeof prompt === "function" ? prompt(location, action) : prompt;

      if (typeof result === "string") {
        // 方便理解我把源码getUserConfirmation(result, callback)直接替换成callback(window.confirm(result))
        callback(window.confirm(result))
      } else {
        callback(result !== false);
      }
    } else {
      callback(true);
    }
  }

  return {
    setPrompt,
    confirmTransitionTo
    ...
  };
}
复制代码

setPromptconfirmTransitionTo的用意:

  1. 设置提示setPrompt:把用户设置的提示信息函数存储在prompt变量;
  2. 实现提示confirmTransitionTo:
    1. 获得提示信息:执行prompt变量;
    2. 提示信息后的回调:执行callback把提示信息做为结果返回出去。

下面看h.block源码。

// createBrowserHistory.js
import createTransitionManager from "./createTransitionManager";
const transitionManager = createTransitionManager();

function createBrowserHistory(props = {}){
  let isBlocked = false;

  function block(prompt = false) {
    // 设置提示
    const unblock = transitionManager.setPrompt(prompt);

    // 是否设置了block
    if (!isBlocked) {
      checkDOMListeners(1);
      isBlocked = true;
    }

    // 解除block函数
    return () => {
      if (isBlocked) {
        isBlocked = false;
        checkDOMListeners(-1);
      }

      // 消除提示
      return unblock();
    };
  }

  const history = {
    // 截取
    block,
    ...
  };

  return history;
}
复制代码

history.block的功能是当历史记录条目改变时,触发提示信息。因此这里有两步:

  1. transitionManager.setPrompt(prompt) 设置提示;
  2. checkDOMListeners 监听历史记录条目改变的改变。

这里感受有值得借鉴的地方:调用history.block,它会返回一个解除监听方法,只要调用一下返回函数便可解除监听或者复原(有趣)。


咱们看看监听历史记录条目改变函数checkDOMListeners(1)(注意:transitionManager.confirmTransitionTo)。

// createBrowserHistory.js
function createBrowserHistory(props = {}){
  function block(prompt = false) {
    // 设置提示
    const unblock = transitionManager.setPrompt(prompt);

    // 是否设置了block
    if (!isBlocked) {
      checkDOMListeners(1);
      isBlocked = true;
    }

    // 解除block函数
    return () => {
      if (isBlocked) {
        isBlocked = false;
        checkDOMListeners(-1);
      }

      // 消除提示
      return unblock();
    };
  }

  let listenerCount = 0;

  function checkDOMListeners(delta) {
    listenerCount += delta;
    
    // 是否已经添加
    if (listenerCount === 1 && delta === 1) {
      // 添加绑定,当地址栏改变的时候
      window.addEventListener('popstate', handlePopState);
    } else if (listenerCount === 0) {
      // 解除绑定
      window.removeEventListener('popstate', handlePopState);
    }
  }
  
  // getDOMLocation(event.state) = location = {
  // hash: ""
  // pathname: "/history/index.html"
  // search: "?_ijt=2mt7412gnfvjpfeuv4hjkq2uf8"
  // state: undefined
  // }
  function handlePopState(event) {
    handlePop(getDOMLocation(event.state));
  }
  
  function handlePop(location) {
    // 不须要刷新页面
    const action = "POP";

    // 实现提示
    transitionManager.confirmTransitionTo(
      location,
      action,
      getUserConfirmation,
      ok => {
        if (ok) {
          // 肯定
          setState({ action, location });
        } else {
          // 取消
          revertPop(location);
        }
      }
    );
  }

  const history = {
    // 截取
    block
    ...
  };

  return history;
}
复制代码

就是在handlePop函数触发transitionManager.confirmTransitionTo的(3.1.3我对这里作了修改成了方便理解)。


transitionManager.confirmTransitionTo的回调函数callback有两条分支,用户点击提示框的肯定按钮或者取消按钮:

  1. 当用户点击提示框的肯定后,执行setState({ action, location })
  2. 当用户点击提示框的取消后,执行revertPop(location)(忽略)。

到这里已经了解完h.block函数、h.listencreateTransitionManager.js。接下来咱们继续看另外一个重要的函数h.push

3.6 push

function createBrowserHistory(props = {}){
  function push(path, state) {
    const action = "PUSH";
    // 构造location
    const location = createLocation(path, state, createKey(), history.location);

    // 执行block函数,弹出框
    transitionManager.confirmTransitionTo(
      location,
      action,
      getUserConfirmation,
      ok => {
        if (!ok) return;

        // 获取当前路径名
        const href = createHref(location);
        const { key, state } = location;

        // 添加历史条目
        globalHistory.pushState({ key, state }, null, href);
        
        if (forceRefresh) {
          // 强制刷新
          window.location.href = href;
        } else {
          // 更新history
          setState({ action, location });
        }
      }
    );
  }

  const history = {
    // 跳转
    push,
    ...
  };

  return history;
}
复制代码

这里最重要的是globalHistory.pushState函数,它直接添加新的历史条目。

3.7 replace

function createBrowserHistory(props = {}){
  function replace(path, state) {
    const action = "REPLACE";
    // 构造location
    const location = createLocation(path, state, createKey(), history.location);

    // 执行block函数,弹出框
    transitionManager.confirmTransitionTo(
      location,
      action,
      getUserConfirmation,
      ok => {
        if (!ok) return;
        // 获取当前路径名
        const href = createHref(location);
        const { key, state } = location;

        globalHistory.replaceState({ key, state }, null, href);

        if (forceRefresh) {
          window.location.replace(href);
        } else {
          setState({ action, location });
        }
      }
    );
  }

  const history = {
    // 跳转
    replace,
    ...
  };

  return history;
}
复制代码

其实pushreplace的区别就是history.pushStatehistory.replaceState的区别。

3.8 go

function createBrowserHistory(props = {}){
   function go(n) {
    globalHistory.go(n);
  }

  function goBack() {
    go(-1);
  }

  function goForward() {
    go(1);
  }

  const history = {
    // 跳转
    go,
    goBack,
    goForward,
    ...
  };

  return history;
}
复制代码

其实就是history.go的运用。

4.demo

手把手带你上react-router的history车(掘金)

5.总结

总的来讲,若是不须要block的话,原生方法能够知足。最主要仍是对history.pushStatehistory.replaceStatehistory.go(n)popstate方法的运用。公司加班严重,利用仅剩的时间扩充下本身的知识面,最好的方法那就是阅读源码了哈哈。开始总会有点困难,第一次读一脸懵逼,第二次读二脸懵逼,第三次读有点懵逼,第四次读这b牛逼~。只要坚持下多写点测试用例慢慢理解就行了,加油!

fafa
相关文章
相关标签/搜索