Skip to content

Commit

Permalink
Simplify page URL hash logic (#725)
Browse files Browse the repository at this point in the history
  • Loading branch information
DragonRider0o0 authored Apr 1, 2022
1 parent 21e8ad6 commit 50f2fc3
Showing 1 changed file with 20 additions and 35 deletions.
55 changes: 20 additions & 35 deletions codelab-elements/google-codelab/google_codelab.js
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,24 @@ class Codelab extends HTMLElement {
this.setAttribute(SELECTED_ATTR, index);
}

/**
* @export
* @return{string}
*/
get hash() {
return window.location.hash;
}

/**
* @export
* @param {string} newHash
*/
set hash(newHash) {
if (newHash !== '' && window.location.hash !== newHash) {
window.location.hash = newHash;
}
}

/**
* @protected
*/
Expand Down Expand Up @@ -484,32 +502,6 @@ class Codelab extends HTMLElement {
}
}

/**
* History popState callback
* @param {!Event} e
* @private
*/
handlePopStateChanged_(e) {
const step = this.getStepFromHash_(document.location.hash);
this.setAttribute(DONT_SET_HISTORY_ATTR, '');
this.setAttribute(SELECTED_ATTR, `${step}`);
this.removeAttribute(DONT_SET_HISTORY_ATTR);
}

/**
* Updates the browser history state
* @param {string} path The new browser state
* @param {boolean=} replaceState optionally replace state instead of pushing
* @export
*/
updateHistoryState(path, replaceState = false) {
if (replaceState) {
window.history.replaceState({path}, document.title, path);
} else {
window.history.pushState({path}, document.title, path);
}
}

/**
* @param {!Event} e
* @private
Expand Down Expand Up @@ -864,22 +856,15 @@ class Codelab extends HTMLElement {
*/
init_() {
this.id_ = this.getAttribute(ID_ATTR);
let step = this.getStepFromHash_(document.location.hash) ||
this.getStepFromStorage_();
let step = this.getStepFromHash_(this.hash) || this.getStepFromStorage_();
this.setAttribute(SELECTED_ATTR, `${step}`);
this.eventHandler_.listen(
dom.getWindow(), events.EventType.POPSTATE, (e) => {
this.handlePopStateChanged_(e);
});
}

/**
* @protected
*/
saveStep() {
if (!this.hasAttribute(DONT_SET_HISTORY_ATTR)) {
this.updateHistoryState(`#${this.currentSelectedStep}`, true);
}
this.hash = `#${this.currentSelectedStep}`;
if (this.id_) {
this.storage_.set(
`progress_${this.id_}`, String(this.currentSelectedStep));
Expand Down

0 comments on commit 50f2fc3

Please sign in to comment.