Skip to content

Commit

Permalink
playground: add an option for URL hash persistence
Browse files Browse the repository at this point in the history
  • Loading branch information
divarvel committed Sep 8, 2022
1 parent 63e385c commit 8c07498
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/bc-datalog-playground.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
export class BCDatalogPlayground extends LitElement {
@property() code = "";
@property() showBlocks = false;
@property() fromHash = false;
@state() blocks: Array<{ code: string; externalKey: string | null }> = [];
@state() private started = false;

Expand All @@ -40,6 +41,26 @@ export class BCDatalogPlayground extends LitElement {
return { code, externalKey };
})
.filter(({ code }, i) => i === 0 || code !== "");
setTimeout(() => this.updateFromHash(), 0);
}

updateFromHash() {
if (!this.fromHash) return;
let hashContents;
try {
hashContents = JSON.parse(atob(window.location.hash.substr(1)));
} catch (e) {
console.error({ e });
}
const [code, blocks] = hashContents;
this.code = code;
this.blocks = blocks;
}

updateHash() {
if (!this.fromHash) return;
const ser = [this.code, this.blocks];
window.location.hash = btoa(JSON.stringify(ser));
}

firstUpdated() {
Expand All @@ -50,6 +71,7 @@ export class BCDatalogPlayground extends LitElement {
const newBlocks = [...this.blocks];
newBlocks.push({ code: "", externalKey: null });
this.blocks = newBlocks;
this.updateHash();
}

onUpdatedBlock(blockId: number, e: { detail: { code: string } }) {
Expand All @@ -59,6 +81,7 @@ export class BCDatalogPlayground extends LitElement {
externalKey: newBlocks[blockId].externalKey,
};
this.blocks = newBlocks;
this.updateHash();
}

onUpdatedExternalKey(blockId: number, e: InputEvent) {
Expand All @@ -69,10 +92,12 @@ export class BCDatalogPlayground extends LitElement {
externalKey: newValue !== "" ? newValue : null,
};
this.blocks = newBlocks;
this.updateHash();
}

onUpdatedCode(e: { detail: { code: string } }) {
this.code = e.detail.code;
this.updateHash();
}

render() {
Expand Down

0 comments on commit 8c07498

Please sign in to comment.