| 1 |
import { getCurrentUrl } from './getCurrentUrl.js'; |
| 2 |
|
| 3 |
export interface HistoryState { |
| 4 |
url: string; |
| 5 |
source: 'swup'; |
| 6 |
random: number; |
| 7 |
index?: number; |
| 8 |
[key: string]: unknown; |
| 9 |
} |
| 10 |
|
| 11 |
type HistoryData = Record<string, unknown>; |
| 12 |
|
| 13 |
/** Create a new history record with a custom swup identifier. */ |
| 14 |
export const createHistoryRecord = (url: string, data: HistoryData = {}): void => { |
| 15 |
url = url || getCurrentUrl({ hash: true }); |
| 16 |
const state: HistoryState = { |
| 17 |
url, |
| 18 |
random: Math.random(), |
| 19 |
source: 'swup', |
| 20 |
...data |
| 21 |
}; |
| 22 |
window.history.pushState(state, '', url); |
| 23 |
}; |
| 24 |
|
| 25 |
/** Update the current history record with a custom swup identifier. */ |
| 26 |
export const updateHistoryRecord = (url: string | null = null, data: HistoryData = {}): void => { |
| 27 |
url = url || getCurrentUrl({ hash: true }); |
| 28 |
const currentState = (window.history.state as HistoryState) || {}; |
| 29 |
const state: HistoryState = { |
| 30 |
...currentState, |
| 31 |
url, |
| 32 |
random: Math.random(), |
| 33 |
source: 'swup', |
| 34 |
...data |
| 35 |
}; |
| 36 |
window.history.replaceState(state, '', url); |
| 37 |
}; |