diff --git a/bins/index.html b/bins/index.html index de2d466..ce3936d 100644 --- a/bins/index.html +++ b/bins/index.html @@ -7376,6 +7376,26 @@

Your drawers

let attached = null; // the drawer this page saves into, or null for an unsaved design let base = null; // its shared keys as this page arrived with or last saved them let failing = false; // the browser refused the last save into it + /* The page arrived as a page whose change the drawer refused left it (see attach), and + nothing it has saved since has gone through: the change is still the address's alone. */ + let refusedIn = false; + const refused = () => failing || refusedIn; + /* The refusals the page holds, by the ids its records hand on (see carry and land): any + it arrived with, and one of its own for its refused saves since it last handed them + on, by a hand-over or as it went into the back-forward cache (`sealed` till then). + With one id for the whole chain, a save that went through on an earlier page counted + a later page's change as landed too, though it had never been saved: Forward to that + page lost a depth refused there. + Each id has the base its own changes are counted from (`bases`): the page's shared keys + as it last sealed (`sealedAt`), arriving, saving or coming back from the cache. Counted + from the first page's base, a size that page's refusal held stayed a change of the + later page's after it was saved and set back since, and Forward to the later page + wrote it over the one set back. */ + let rids = []; + let bases = new Map(); + let sealedAt = null; + let sealed = true; + const drop = () => { rids = []; bases = new Map(); sealed = true; }; /* This tool's mark in the drawer at the page's last save into it that went through, or as it arrived: the page's half is that save or newer. Newer when the browser refused the saves since (storage full), and then the address is the one copy of the @@ -7401,19 +7421,99 @@

Your drawers

if (n[o.tool] !== id) { n[o.tool] = id; writeNote(area, key, n); } } } + /* For a page whose design holds a change the drawer refused (`on`), what the page that + takes the design on needs to know of it, in a note, a mark or a raced reload's + record: that it does, and the page's base `b`, its shared keys as it last saved them + or arrived with them, which its changes are counted from (see attach). With the ids + of the refusals it holds (see rids), so that once they land, its records can be told + apart from one still to save (see land), and each one's base (`bs`, the page's own + but for a catch-up's). Nothing for any other page, whose base is the design it hands + on. */ + const newRid = () => Math.random().toString(36).slice(2, 10) || 'r'; + const carry = (on, b, bs = bases) => { + if (!(on && b)) return {}; + if (!rids.length) { rids = [newRid()]; bases = new Map([[rids[0], b]]); } + return { refused: true, base: [...b], rids: rids.slice(), bases: rids.map((id) => [...(bs.get(id) || b)]) }; + }; + // ids as a record or the tab's note has them, what carry makes and no more + const RID = /^[a-z0-9]{1,16}$/; + const ridsIn = (v) => strings(v).filter((id) => RID.test(id)); + const landedIds = () => ridsIn(readNote('sessionStorage', TAB).landed); + /* A save that went through while the page held refusals: their changes are in the + drawer now, or were changed again before they got there, and either way every record + of them is older than the drawer. Kept for this tab, the last 128, so Back to one of + them is a page of yours come back, caught up with the drawer. Counted from its base, + a size set back on the other page since was taken for the change, and saved over the + one set back. */ + function land() { + if (rids.length) { + const done = landedIds(); + const add = rids.filter((id) => !done.includes(id)); + if (add.length) { + const n = readNote('sessionStorage', TAB); + n.landed = done.concat(add).slice(-128); + writeNote('sessionStorage', TAB, n); + } + } + drop(); + } + /* How many of `ids`, oldest first, have landed: all up to the last one that has. The + page that held it held those before it too, with their changes, so its save that went + through saved them, or a change since replaced them. A page that keeps only the last + of a long chain's ids (see hold) lands them so, and Back to one holding the first + found it still to save. */ + const landedTo = (ids) => { + const done = new Set(landedIds()); + let n = ids.length; + while (n > 0 && !done.has(ids[n - 1])) n -= 1; + return n; + }; + // a base as a record has it, the shared keys and no more + const baseIn = (b) => new Map((Array.isArray(b) ? b : []).filter((p) => Array.isArray(p) && + p.length === 2 && typeof p[0] === 'string' && typeof p[1] === 'string' && SHARED.has(p[0]))); + /* What a note, mark or record carries (see carry): its refusals still to land, oldest + first, as [id, base], and the base the page's changes are counted from, the first + one's. Null for one that carries none, or whose refusals have all landed since. */ + function carried(r) { + if (!isPlain(r) || r.refused !== true || !Array.isArray(r.base)) return null; + const all = baseIn(r.base); + const ids = Array.isArray(r.rids) ? r.rids : []; + // a record from before each id had a base: all of them have the record's + const bs = Array.isArray(r.bases) && r.bases.length === ids.length ? r.bases : null; + const held = []; + for (let i = Math.max(0, ids.length - 64); i < ids.length; i += 1) { // more than a page keeps + if (typeof ids[i] === 'string' && RID.test(ids[i])) held.push([ids[i], bs ? baseIn(bs[i]) : all]); + } + const n = landedTo(held.map(([id]) => id)); + if (held.length && n === held.length) return null; + const rest = held.slice(n); + return { base: rest.length ? rest[0][1] : all, held: rest }; + } + /* The refusals `held` ([id, base], oldest first) as the page's own: the last 32, the + first of them counted from the page's base, which is the first one's, so the changes + of those let go are still counted. */ + function hold(held) { + const kept = held.slice(-32); + if (kept.length < held.length) kept[0] = [kept[0][0], base]; + rids = kept.map(([id]) => id); + bases = new Map(kept); + } /* The note for the next page to load in this tab: the drawer ('' for none), and the fingerprint of the design that page will arrive with. `link` lists the drawer, bed and infill settings in it that are still someone's link's, not yours (the tool's ui.js works that out); `open` says a drawer was opened from the list, or caught up, rather than handed over. `marks` gives, for each tool, its mark in the drawer when its settings in `h` were current, where that is known (see restore): by tool, since - by way of the guide the next page can be either. Read once, by the page's boot (see - arrival). False if the browser would not keep it. */ + by way of the guide the next page can be either. `refused` and `base` say `h` holds + a change the drawer refused, and what it is counted from (see carry). Read once, by + the page's boot (see arrival). False if the browser would not keep it. */ function handOver(id, h, caughtUp, more) { const n = readNote('sessionStorage', TAB); n.next = { id, fp: fingerprint(h), caughtUp: !!caughtUp, link: (more && more.link) || [], open: !!(more && more.open), - marks: (more && more.marks) || {} }; + marks: (more && more.marks) || {}, + ...(more && more.refused ? { refused: true, base: more.base, rids: more.rids, bases: more.bases } + : {}) }; return writeNote('sessionStorage', TAB, n); } /* With it, the record of the address this tool's last save left (see wrote), which is @@ -7441,11 +7541,12 @@

Your drawers

pasted over the page reloads it too, and the page says so first (forget). The record also carries what the address's own mark would have said: the page's marks from before the save (ours, theirs), by which the drawer has moved on from the address or - not, and which settings in the design saved are still someone's link's (link). */ - function leaving(id, now, had, link) { + not, which settings in the design saved are still someone's link's (link), and + whether the drawer refused the save, with the page's base (see carry). */ + function leaving(id, now, had, link, refusedSave) { const n = readNote('sessionStorage', TAB); n.left = { tool: o.tool, id, was: fingerprint((location.hash || '').replace(/^#/, '')), now, - ours: had, theirs, link: strings(link) }; + ours: had, theirs, link: strings(link), ...carry(refusedSave, base) }; writeNote('sessionStorage', TAB, n); } function reloaded() { @@ -7486,12 +7587,13 @@

Your drawers

link, untouched since it arrived; `note` the note the page arrived at it by, until the page saves from it. */ const stamp = (h, link, note) => ({ drawerforge: { tool: o.tool, fp: fingerprint(h), - id: attached || '', link: !!link, ...(note ? { note } : {}), ours, theirs } }); + id: attached || '', link: !!link, ...(note ? { note } : {}), ours, theirs, ...carry(refused(), base) } }); // marks the address the page is at, if it is `h`, leaving it as it is function markHere(h, link, note) { if ((location.hash || '').replace(/^#/, '') !== h) return; try { history.replaceState(stamp(h, link, note), ''); } - catch (err) { /* refused on file://: a reload goes by the tab's record instead */ } + catch (err) { /* refused, as a browser may when it is called too often: a reload + goes by the tab's record instead */ } } // the marks for a note: this tool's `mine`, and the other's as this page has it const marksFor = (mine) => ({ [o.tool]: mine, [otherTool]: theirs }); @@ -7516,7 +7618,9 @@

Your drawers

this page finds, or another tab did. Showing the old values would be wrong twice over, since a download would use them too, so the page reloads onto the stored ones instead. The note marks that reload as a catch-up, and a catch-up is never followed - by another, so this cannot loop. True if the page is reloading. */ + by another, so this cannot loop. A change of the page's that the drawer refused goes + with it, counted from the base as it moves on with the drawer. True if the page is + reloading. */ function catchUp(h, d) { const stored = sharedOf(d.hash); const moved = [...stored.keys()].filter((k) => o.owns(k) && base.get(k) !== stored.get(k)); @@ -7524,8 +7628,23 @@

Your drawers

const pairs = parsePairs(h) || []; const merged = encodePairs(pairs.map(([k, v]) => [k, moved.includes(k) ? stored.get(k) : v]) .concat(moved.filter((k) => !pairs.some((p) => p[0] === k)).map((k) => [k, stored.get(k)]))); + // a base with the keys caught up as the drawer has them: the page's, and each refusal's + const catching = (b) => new Map([...b, ...moved.map((k) => [k, stored.get(k)])]); + const caught = catching(base); + const caughtEach = new Map([...bases].map(([id, b]) => [id, catching(b)])); + /* The page has the drawer's settings already: they are its base now, with nothing to + reload, and its address's mark says so. Left with the base before, a reload after + another tab set the size back took the page's size for its own change still to + save, and wrote it over the one set back. */ + if (merged === h) { + base = caught; bases = caughtEach; + const m = refused() && markOf(h); + if (m) markHere(h, m.link, m.note); + return false; + } + const more = { open: true, marks: marksFor(ours), ...carry(refused(), caught, caughtEach) }; // without the note the reloaded page could not tell it is this drawer, so stay put - if (!handOver(d.id, merged, true, { open: true, marks: marksFor(ours) })) return false; + if (!handOver(d.id, merged, true, more)) return false; go(merged); return true; } @@ -7559,16 +7678,19 @@

Your drawers

half the other page's copy was current with (`seen`), and while the drawer still holds that save, the copy is as new as the drawer or newer: with the browser's storage full, a bin placed before going across was saved nowhere else, and taking - the drawer's half lost it. True if the page is reloading. */ + the drawer's half lost it. A change the drawer refused goes with it, with its base + (see carry): the half reloaded is this tool's alone. True if the page is reloading. */ const half = (k) => o.owns(k) && !SHARED.has(k) && !(o.given || []).includes(k); + // this tool's half of the design `s`, in one order, so two halves compare as strings + const halfPairs = (s) => (parsePairs(s) || []).filter(([k]) => half(k)) + .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)); function restore(h, d, link, seen) { if (seen === d.marks[o.tool]) return false; - const mine = (s) => (parsePairs(s) || []).filter(([k]) => half(k)) - .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)); - const stored = mine(d.hash); - if (encodePairs(stored) === encodePairs(mine(h))) return false; + const stored = halfPairs(d.hash); + if (encodePairs(stored) === encodePairs(halfPairs(h))) return false; const merged = encodePairs((parsePairs(h) || []).filter(([k]) => !half(k)).concat(stored)); - if (!handOver(d.id, merged, false, { link, marks: marksFor(d.marks[o.tool]) })) return false; + const more = { link, marks: marksFor(d.marks[o.tool]), ...carry(refused(), base) }; + if (!handOver(d.id, merged, false, more)) return false; go(merged); return true; } @@ -7584,7 +7706,8 @@

Your drawers

} function paintBar() { const d = attached && find(loadAll(), attached); - if (attached && !d) { attached = null; failing = false; } // deleted on another tab + // deleted on another tab + if (attached && !d) { attached = null; failing = false; refusedIn = false; drop(); } /* A refused save leads, ahead of the name: on a phone the bar shows about a dozen characters, and the warning is the part that has to survive the cut. */ const shown = d ? (failing ? `not saving · ${d.name}` : d.name) : 'not saved'; @@ -7721,7 +7844,7 @@

Your drawers

return; } attached = d.id; armed = ''; renaming = ''; - base = sharedOf(h); failing = false; + base = sharedOf(h); sealedAt = base; failing = false; refusedIn = false; drop(); ours = d.marks[o.tool]; theirs = undefined; // the other tool has no mark in a new drawer savedInto(d.id); @@ -7780,7 +7903,7 @@

Your drawers

s.drawers = s.drawers.filter((x) => x.id !== id); if (!saveAll(s)) { say('This browser would not store the change.', 'bad'); return; } const wasOpen = attached === id; - if (wasOpen) { attached = null; failing = false; } + if (wasOpen) { attached = null; failing = false; refusedIn = false; drop(); } armed = ''; render(); say(`Deleted “${d.name}”.` + (wasOpen @@ -7896,8 +8019,24 @@

Your drawers

addEventListener('pageshow', (e) => { if (!e.persisted || !attached) return; const d = find(loadAll(), attached); - if (!d) return; + if (!d) { paintBar(); return; } // deleted since: the bar says so const h = o.design(); + /* Refusals that have all landed since, from a later page: this one is as any page come + back. All but a change to its own half, which the later page did not save: refused + with the size, it is still this page's alone, and the bar still says so until a save + goes through. Some of them landed: its changes are counted from the first still to + land. */ + const n = refused() ? landedTo(rids) : 0; + if (n && n === rids.length) { + refusedIn = false; drop(); base = sharedOf(h); + if (encodePairs(halfPairs(h)) === encodePairs(halfPairs(d.hash))) failing = false; + paintBar(); + } else if (n) { + hold(rids.slice(n).map((id) => [id, bases.get(id) || base])); + base = bases.get(rids[0]); + } + sealed = true; // its records so far went into the cache with it + sealedAt = sharedOf(h); if (movedOn(d, h, ours)) reopen(d); // a later page saved into it else catchUp(h, d); }); @@ -7988,6 +8127,8 @@

Your drawers

attached = null; ours = undefined; theirs = undefined; + refusedIn = false; + drop(); const { next, left } = takeOnce(); // read every time, so a stale note never lingers if (arrivedWith) { const s = loadAll(); @@ -8014,11 +8155,13 @@

Your drawers

} if (d) { attached = d.id; - base = sharedOf(arrivedWith); - // the marks the design's halves came with, from the note or this tab's own mark - const came = noted ? (isPlain(next.marks) ? next.marks : {}) - : mine && mine.id === d.id ? { [o.tool]: mine.ours, [otherTool]: mine.theirs } - : gone && gone.id === d.id ? { [o.tool]: gone.ours, [otherTool]: gone.theirs } : {}; + base = sharedOf(arrivedWith); sealedAt = base; + // the record the design came with: the note, this tab's own mark, or a raced reload's + const from = noted ? next : mine && mine.id === d.id ? mine + : gone && gone.id === d.id ? gone : null; + // the marks the design's halves came with, by it + const came = !from ? {} : noted ? (isPlain(next.marks) ? next.marks : {}) + : { [o.tool]: from.ours, [otherTool]: from.theirs }; const str = (v) => (typeof v === 'string' ? v : undefined); theirs = str(came[otherTool]); /* A raced reload's link settings, those the drawer still has as the page had @@ -8028,6 +8171,17 @@

Your drawers

? strings(gone.link).filter((k) => stored.get(k) === base.get(k)) : null; if (!noted && movedOn(d, arrivedWith, str(came[o.tool])) && reopen(d, held)) return; ours = d.marks[o.tool]; + /* A design holding a change the drawer refused: a hand-over from a page whose + saves into the drawer were refused, or this page reloaded or gone Back to after + its own were. The record says so, with that page's base (see carry), and the + change is counted from that base, as it was there. It is still to be saved, + and a size another tab moved on since that page last saved is caught up below. + Counted from the design, the change was taken for the drawer's, and the + catch-up put the older size back over it. Counted from the drawer's settings, + a size that page had kept from before another tab moved it on was taken for + the change, and its next save wrote it over that tab's. */ + const kept = carried(from); + if (kept) { refusedIn = true; base = kept.base; hold(kept.held); } /* A hand-over, onto a drawer this tool has saved into. One carrying a link's settings too: restore keeps the settings the other page sets, which are the link's, and this tool's half was saved into the drawer with them. */ @@ -8042,7 +8196,10 @@

Your drawers

if (noted) { d.hash = mergeDesign(d.hash, arrivedWith, o.owns, base); d.marks[o.tool] = fp; - if (saveAll(s)) ours = fp; + if (saveAll(s)) { + if (refused()) land(); + ours = fp; base = sharedOf(arrivedWith); sealedAt = base; refusedIn = false; + } savedInto(d.id); } } @@ -8065,7 +8222,8 @@

Your drawers

const s = loadAll(); const d = find(s, attached); if (!d) { - attached = null; failing = false; savedInto(''); leaving('', '', ours, link); paintBar(); return; + attached = null; failing = false; refusedIn = false; drop(); + savedInto(''); leaving('', '', ours, link); paintBar(); return; } // nothing of this page's own to save, and a reload reopens onto the drawer if (behind(d, h)) { leaving(d.id, d.marks[o.tool], ours, link); return; } @@ -8074,12 +8232,23 @@

Your drawers

d.marks[o.tool] = fingerprint(h); d.saved = Date.now(); const ok = saveAll(s); - if (ok) { base = sharedOf(h); ours = d.marks[o.tool]; } + if (ok) { + if (refused()) land(); + base = sharedOf(h); sealedAt = base; ours = d.marks[o.tool]; refusedIn = false; + } else if (sealed) { + /* A refusal of this page's own, apart from any it arrived with (see rids), counted + from the page as it last sealed. The first the page holds counts from its base, + which can be older: a change it arrived with, from a record with no ids, is + still to save. */ + const at = rids.length ? sealedAt || base : base; + hold(rids.map((id) => [id, bases.get(id) || base]).concat([[newRid(), at]])); + sealed = false; + } savedInto(d.id); /* Refused, the drawer still holds the save before, and the address has the page's change, past the save the page last made into it (had): a reload that raced this save keeps it, rather than reopening onto the older half. */ - leaving(d.id, ok ? d.marks[o.tool] : was, had, link); + leaving(d.id, ok ? d.marks[o.tool] : was, had, link, !ok); /* The page's own save shares this storage and fails without a word, but this one is promised in so many words — the dialog says changes save into the drawer as you work — so a refused save is said, on the bar and in the dialog, until one goes @@ -8106,11 +8275,16 @@

Your drawers

if (d && typeof mine === 'string' && !behind(d, mine)) { d.hash = mergeDesign(d.hash, h, o.owns, base); d.saved = Date.now(); - if (saveAll(s)) base = sharedOf(h); + if (saveAll(s)) { + if (refused()) land(); + base = sharedOf(h); + } } /* Behind or not, the note says which save this page's half is: one the drawer has moved on from comes back from the other page as the drawer has it (restore). */ - handOver(d ? d.id : '', h, false, { link, marks: d ? marksFor(ours) : {} }); + handOver(d ? d.id : '', h, false, + { link, marks: d ? marksFor(ours) : {}, ...carry(!!d && refused(), base) }); + sealed = true; // handed on: a refusal after this, from the cache, is another }, }; } @@ -18419,6 +18593,8 @@

Your drawers

* stops that being your problem. */ let hashSaveT = 0, hashReady = false; +// saves were on when Start fresh left the page, and nothing has left it since (see startFresh) +let freshLeft = false; /* Kept on this browser, so the work survives arriving without a link. * * The address bar already carries the design and a refresh already restores it. What it @@ -18439,6 +18615,8 @@

Your drawers

* when it has done one and offers a way back. */ const SAVE_KEY = 'drawerforge:bins:v1'; +// this tab's record of a save a pasted link set aside (see pastedFrom), declared here for Start fresh +const PASTED_KEY = SAVE_KEY + ':pasted'; const saveLocal = (h) => { try { localStorage.setItem(SAVE_KEY, h); } catch (err) { /* private mode, or the quota is full — losing the save is not worth @@ -18451,11 +18629,25 @@

Your drawers

const isLayoutHash = (h) => /(^|&)[^&=]+=/.test(h); function startFresh() { try { localStorage.removeItem(SAVE_KEY); } catch (err) { /* nothing to clear */ } - location.href = location.origin + location.pathname; // drop the hash and reload clean + forgetPasted(); + const saving = hashReady || freshLeft; // pressed again before the page goes: as the first press found it + /* Left as Put back leaves, by leaveFor: the page runs on until the bare one arrives, and + a change that landed in between was saved after the clearing, and came back with the + note that it had been restored. */ + leaveFor(location.origin + location.pathname); // drop the hash and reload clean + freshLeft = saving; // after leaveFor, which clears it } /* Wired here, before the boot below reads any link: a link that throws there must not - also take away the button that gets you out of it, or stop the next link working. */ + also take away the button that gets you out of it, or stop the next link working. What + leaveFor stops, hashReady and hashSaveT, is declared above, so it works from here too. */ $('startFresh').addEventListener('click', startFresh); +/* Left by Start fresh and shown again from the back-forward cache, as Back from the fresh + page can be in some browsers: the page is yours again, and saves as it did before, as it + does loaded. Not after Put back or Try anyway, which leave by leaveFor too, even pressed + after Start fresh before the page has gone: loaded, that page is a link again and sets + your layout aside first, and from the cache its first save would go over the layout just + put back. */ +addEventListener('pageshow', (e) => { if (e.persisted && freshLeft) { hashReady = true; freshLeft = false; } }); /* A hash this page did not write means someone navigated to a link — pasted a share URL into the address bar, or picked a bookmark — and changing only the fragment is a same-document navigation, so nothing re-reads it and the drawer on screen stays put. @@ -18524,7 +18716,7 @@

Your drawers

return [...SHARED_KEYS].filter((k) => k in q && p[k] === q[k]); } function leaveFor(url) { - hashReady = false; clearTimeout(hashSaveT); // no save of this page's may land after + hashReady = false; freshLeft = false; clearTimeout(hashSaveT); // no save of this page's may land after location.href = url; } /* Swapped rather than copied over: what is here now goes aside in its place, so putting @@ -18540,6 +18732,7 @@

Your drawers

} saveLocal(prev); writeKey(LINKED_KEY, prevLinked); + forgetPasted(); leaveFor(location.href.split('#')[0]); // a bare visit restores it, and says so } function tryAnyway() { @@ -18601,11 +18794,45 @@

Your drawers

drawer the address is at: marked before it, a reload took the save before for its own, and after another tab put the drawer back to that one, the reload wrote this page's later change back over it. */ - try { history.replaceState(drawers.stamp(h, linkedNow && bootDesc !== null), '', '#' + h); } - catch (err) { /* some browsers refuse replaceState on file:// — a lost URL is not - worth an exception that stops the rest of the page working */ } + if (!pastedOver()) { + try { history.replaceState(drawers.stamp(h, linkedNow && bootDesc !== null), '', '#' + h); } + catch (err) { /* some browsers refuse replaceState on file:// — a lost URL is not + worth an exception that stops the rest of the page working */ } + ownHash = location.hash; + } else { + try { sessionStorage.setItem(PASTED_KEY, JSON.stringify({ save: DRAWERS.fingerprint(h), + at: DRAWERS.fingerprint(ownHash) })); } + catch (err) { /* not kept, Back offers nothing: no worse than before */ } + } } } +/* The address as this page last left it: as it arrived, then as each save wrote it. One + that differs, with a layout in it, is a link gone to over this page, pasted or picked + from the bookmarks, whose hashchange (above) has not run yet: a page busy drawing comes + to a save that was waiting first. That save is still made, so the layout the link + replaces holds the change and is set aside with it, but the address is the link's. + Written back over, the hashchange found this page's design there and reloaded that, + and the link was gone. */ +let ownHash = null; +const pastedOver = () => ownHash !== null && location.hash !== ownHash && + isLayoutHash((location.hash || '').replace(/^#/, '')); +/* That save, and the address it left as it was, by fingerprint, for this tab: the layout + the link sets aside is the save, and it is later than the address, which never had the + change. Back to the address offers it, and only it (see `later` below). */ +const pastedFrom = (prev) => { + try { + const r = JSON.parse(sessionStorage.getItem(PASTED_KEY) || 'null'); + return !!r && !!prev && r.save === DRAWERS.fingerprint(prev) && + r.at === DRAWERS.fingerprint(location.hash); + } catch (err) { return false; } +}; +/* Start fresh and Put back each leave that save behind, and the record goes with them. + Kept past Start fresh, Back to a page at the same address offered the save as the later + layout, though Start fresh came after it. Start fresh works from before the boot reads a + link, so PASTED_KEY is declared with SAVE_KEY, above it. */ +function forgetPasted() { + try { sessionStorage.removeItem(PASTED_KEY); } catch (err) { /* nothing kept to forget */ } +} /* A reload takes the address as it stands when it starts, and the page runs on until the new one arrives. A save still waiting would land in that gap and record in the saved drawer a design the reloaded page did not arrive with, and the page came back unsaved. @@ -19014,17 +19241,30 @@

Your drawers

layout was set aside and offered a Put back that brought nothing back. */ let keptAside = false; if (aside) { + const asideLinked = linkKeys(saved, linked).length ? linked : ''; writeKey(PREV_KEY, saved); keptAside = readKey(PREV_KEY) === saved; - if (keptAside) writeKey(PREV_LINKED_KEY, linkKeys(saved, linked).length ? linked : ''); + if (keptAside) writeKey(PREV_LINKED_KEY, asideLinked); + /* With the record of whether it is a link's refused, the one left from the layout set + aside before would answer for it. That goes, and put back, this one is yours: still + better than not setting it aside (unkept), which keeps it only until the first + change made on the link. */ + if (keptAside && readKey(PREV_LINKED_KEY) !== asideLinked) writeKey(PREV_LINKED_KEY, ''); /* Not kept, it is not written over either (unkept), unless a hand-over of your own brings on anything the other page sets: then the save holds the drawer, bed or the other page's settings from before, and a bare visit took those back to the other page. One still carrying someone's link is that link, and your layout is kept. */ - else unkept = !handOver || handOver.link.length > 0 || drawers.onlyMine(saved, src); - } + if (!keptAside) unkept = !handOver || handOver.link.length > 0 || drawers.onlyMine(saved, src); + } + /* Back to your own earlier page over a link's layout, untouched, sets nothing aside: what + the link replaced is aside already. That can be later than the page Back brings: a change + whose save came due as the link was pasted is aside, and in no earlier address (see + pastedOver). So that layout is offered, if it is the one aside and this is the address it + came from, and no other: one aside for any other reason can be older than this page, and + Put back went further back, not on. */ + const later = back && savedLinked && pastedFrom(readKey(PREV_KEY)) ? readKey(PREV_KEY) : ''; const canPutBack = (replaces && !kept && (keptAside || (savedLinked && !!readKey(PREV_KEY)))) || - (back && keptAside); + (back && (keptAside || (!!later && !sameDesign(later, src)))); if (stalled) { showSetAside('This layout did not finish loading last time, so the page has started ' + 'from its defaults rather than try it again.', canPutBack, true); @@ -19065,6 +19305,7 @@

Your drawers

} readControls(); hashReady = true; // loadFromHash has had its say; ours may start +ownHash = location.hash; initThree(); initMap(); drawLayerTabs(); diff --git a/index.html b/index.html index 3c3d924..51907d7 100644 --- a/index.html +++ b/index.html @@ -7163,6 +7163,26 @@

Your drawers

let attached = null; // the drawer this page saves into, or null for an unsaved design let base = null; // its shared keys as this page arrived with or last saved them let failing = false; // the browser refused the last save into it + /* The page arrived as a page whose change the drawer refused left it (see attach), and + nothing it has saved since has gone through: the change is still the address's alone. */ + let refusedIn = false; + const refused = () => failing || refusedIn; + /* The refusals the page holds, by the ids its records hand on (see carry and land): any + it arrived with, and one of its own for its refused saves since it last handed them + on, by a hand-over or as it went into the back-forward cache (`sealed` till then). + With one id for the whole chain, a save that went through on an earlier page counted + a later page's change as landed too, though it had never been saved: Forward to that + page lost a depth refused there. + Each id has the base its own changes are counted from (`bases`): the page's shared keys + as it last sealed (`sealedAt`), arriving, saving or coming back from the cache. Counted + from the first page's base, a size that page's refusal held stayed a change of the + later page's after it was saved and set back since, and Forward to the later page + wrote it over the one set back. */ + let rids = []; + let bases = new Map(); + let sealedAt = null; + let sealed = true; + const drop = () => { rids = []; bases = new Map(); sealed = true; }; /* This tool's mark in the drawer at the page's last save into it that went through, or as it arrived: the page's half is that save or newer. Newer when the browser refused the saves since (storage full), and then the address is the one copy of the @@ -7188,19 +7208,99 @@

Your drawers

if (n[o.tool] !== id) { n[o.tool] = id; writeNote(area, key, n); } } } + /* For a page whose design holds a change the drawer refused (`on`), what the page that + takes the design on needs to know of it, in a note, a mark or a raced reload's + record: that it does, and the page's base `b`, its shared keys as it last saved them + or arrived with them, which its changes are counted from (see attach). With the ids + of the refusals it holds (see rids), so that once they land, its records can be told + apart from one still to save (see land), and each one's base (`bs`, the page's own + but for a catch-up's). Nothing for any other page, whose base is the design it hands + on. */ + const newRid = () => Math.random().toString(36).slice(2, 10) || 'r'; + const carry = (on, b, bs = bases) => { + if (!(on && b)) return {}; + if (!rids.length) { rids = [newRid()]; bases = new Map([[rids[0], b]]); } + return { refused: true, base: [...b], rids: rids.slice(), bases: rids.map((id) => [...(bs.get(id) || b)]) }; + }; + // ids as a record or the tab's note has them, what carry makes and no more + const RID = /^[a-z0-9]{1,16}$/; + const ridsIn = (v) => strings(v).filter((id) => RID.test(id)); + const landedIds = () => ridsIn(readNote('sessionStorage', TAB).landed); + /* A save that went through while the page held refusals: their changes are in the + drawer now, or were changed again before they got there, and either way every record + of them is older than the drawer. Kept for this tab, the last 128, so Back to one of + them is a page of yours come back, caught up with the drawer. Counted from its base, + a size set back on the other page since was taken for the change, and saved over the + one set back. */ + function land() { + if (rids.length) { + const done = landedIds(); + const add = rids.filter((id) => !done.includes(id)); + if (add.length) { + const n = readNote('sessionStorage', TAB); + n.landed = done.concat(add).slice(-128); + writeNote('sessionStorage', TAB, n); + } + } + drop(); + } + /* How many of `ids`, oldest first, have landed: all up to the last one that has. The + page that held it held those before it too, with their changes, so its save that went + through saved them, or a change since replaced them. A page that keeps only the last + of a long chain's ids (see hold) lands them so, and Back to one holding the first + found it still to save. */ + const landedTo = (ids) => { + const done = new Set(landedIds()); + let n = ids.length; + while (n > 0 && !done.has(ids[n - 1])) n -= 1; + return n; + }; + // a base as a record has it, the shared keys and no more + const baseIn = (b) => new Map((Array.isArray(b) ? b : []).filter((p) => Array.isArray(p) && + p.length === 2 && typeof p[0] === 'string' && typeof p[1] === 'string' && SHARED.has(p[0]))); + /* What a note, mark or record carries (see carry): its refusals still to land, oldest + first, as [id, base], and the base the page's changes are counted from, the first + one's. Null for one that carries none, or whose refusals have all landed since. */ + function carried(r) { + if (!isPlain(r) || r.refused !== true || !Array.isArray(r.base)) return null; + const all = baseIn(r.base); + const ids = Array.isArray(r.rids) ? r.rids : []; + // a record from before each id had a base: all of them have the record's + const bs = Array.isArray(r.bases) && r.bases.length === ids.length ? r.bases : null; + const held = []; + for (let i = Math.max(0, ids.length - 64); i < ids.length; i += 1) { // more than a page keeps + if (typeof ids[i] === 'string' && RID.test(ids[i])) held.push([ids[i], bs ? baseIn(bs[i]) : all]); + } + const n = landedTo(held.map(([id]) => id)); + if (held.length && n === held.length) return null; + const rest = held.slice(n); + return { base: rest.length ? rest[0][1] : all, held: rest }; + } + /* The refusals `held` ([id, base], oldest first) as the page's own: the last 32, the + first of them counted from the page's base, which is the first one's, so the changes + of those let go are still counted. */ + function hold(held) { + const kept = held.slice(-32); + if (kept.length < held.length) kept[0] = [kept[0][0], base]; + rids = kept.map(([id]) => id); + bases = new Map(kept); + } /* The note for the next page to load in this tab: the drawer ('' for none), and the fingerprint of the design that page will arrive with. `link` lists the drawer, bed and infill settings in it that are still someone's link's, not yours (the tool's ui.js works that out); `open` says a drawer was opened from the list, or caught up, rather than handed over. `marks` gives, for each tool, its mark in the drawer when its settings in `h` were current, where that is known (see restore): by tool, since - by way of the guide the next page can be either. Read once, by the page's boot (see - arrival). False if the browser would not keep it. */ + by way of the guide the next page can be either. `refused` and `base` say `h` holds + a change the drawer refused, and what it is counted from (see carry). Read once, by + the page's boot (see arrival). False if the browser would not keep it. */ function handOver(id, h, caughtUp, more) { const n = readNote('sessionStorage', TAB); n.next = { id, fp: fingerprint(h), caughtUp: !!caughtUp, link: (more && more.link) || [], open: !!(more && more.open), - marks: (more && more.marks) || {} }; + marks: (more && more.marks) || {}, + ...(more && more.refused ? { refused: true, base: more.base, rids: more.rids, bases: more.bases } + : {}) }; return writeNote('sessionStorage', TAB, n); } /* With it, the record of the address this tool's last save left (see wrote), which is @@ -7228,11 +7328,12 @@

Your drawers

pasted over the page reloads it too, and the page says so first (forget). The record also carries what the address's own mark would have said: the page's marks from before the save (ours, theirs), by which the drawer has moved on from the address or - not, and which settings in the design saved are still someone's link's (link). */ - function leaving(id, now, had, link) { + not, which settings in the design saved are still someone's link's (link), and + whether the drawer refused the save, with the page's base (see carry). */ + function leaving(id, now, had, link, refusedSave) { const n = readNote('sessionStorage', TAB); n.left = { tool: o.tool, id, was: fingerprint((location.hash || '').replace(/^#/, '')), now, - ours: had, theirs, link: strings(link) }; + ours: had, theirs, link: strings(link), ...carry(refusedSave, base) }; writeNote('sessionStorage', TAB, n); } function reloaded() { @@ -7273,12 +7374,13 @@

Your drawers

link, untouched since it arrived; `note` the note the page arrived at it by, until the page saves from it. */ const stamp = (h, link, note) => ({ drawerforge: { tool: o.tool, fp: fingerprint(h), - id: attached || '', link: !!link, ...(note ? { note } : {}), ours, theirs } }); + id: attached || '', link: !!link, ...(note ? { note } : {}), ours, theirs, ...carry(refused(), base) } }); // marks the address the page is at, if it is `h`, leaving it as it is function markHere(h, link, note) { if ((location.hash || '').replace(/^#/, '') !== h) return; try { history.replaceState(stamp(h, link, note), ''); } - catch (err) { /* refused on file://: a reload goes by the tab's record instead */ } + catch (err) { /* refused, as a browser may when it is called too often: a reload + goes by the tab's record instead */ } } // the marks for a note: this tool's `mine`, and the other's as this page has it const marksFor = (mine) => ({ [o.tool]: mine, [otherTool]: theirs }); @@ -7303,7 +7405,9 @@

Your drawers

this page finds, or another tab did. Showing the old values would be wrong twice over, since a download would use them too, so the page reloads onto the stored ones instead. The note marks that reload as a catch-up, and a catch-up is never followed - by another, so this cannot loop. True if the page is reloading. */ + by another, so this cannot loop. A change of the page's that the drawer refused goes + with it, counted from the base as it moves on with the drawer. True if the page is + reloading. */ function catchUp(h, d) { const stored = sharedOf(d.hash); const moved = [...stored.keys()].filter((k) => o.owns(k) && base.get(k) !== stored.get(k)); @@ -7311,8 +7415,23 @@

Your drawers

const pairs = parsePairs(h) || []; const merged = encodePairs(pairs.map(([k, v]) => [k, moved.includes(k) ? stored.get(k) : v]) .concat(moved.filter((k) => !pairs.some((p) => p[0] === k)).map((k) => [k, stored.get(k)]))); + // a base with the keys caught up as the drawer has them: the page's, and each refusal's + const catching = (b) => new Map([...b, ...moved.map((k) => [k, stored.get(k)])]); + const caught = catching(base); + const caughtEach = new Map([...bases].map(([id, b]) => [id, catching(b)])); + /* The page has the drawer's settings already: they are its base now, with nothing to + reload, and its address's mark says so. Left with the base before, a reload after + another tab set the size back took the page's size for its own change still to + save, and wrote it over the one set back. */ + if (merged === h) { + base = caught; bases = caughtEach; + const m = refused() && markOf(h); + if (m) markHere(h, m.link, m.note); + return false; + } + const more = { open: true, marks: marksFor(ours), ...carry(refused(), caught, caughtEach) }; // without the note the reloaded page could not tell it is this drawer, so stay put - if (!handOver(d.id, merged, true, { open: true, marks: marksFor(ours) })) return false; + if (!handOver(d.id, merged, true, more)) return false; go(merged); return true; } @@ -7346,16 +7465,19 @@

Your drawers

half the other page's copy was current with (`seen`), and while the drawer still holds that save, the copy is as new as the drawer or newer: with the browser's storage full, a bin placed before going across was saved nowhere else, and taking - the drawer's half lost it. True if the page is reloading. */ + the drawer's half lost it. A change the drawer refused goes with it, with its base + (see carry): the half reloaded is this tool's alone. True if the page is reloading. */ const half = (k) => o.owns(k) && !SHARED.has(k) && !(o.given || []).includes(k); + // this tool's half of the design `s`, in one order, so two halves compare as strings + const halfPairs = (s) => (parsePairs(s) || []).filter(([k]) => half(k)) + .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)); function restore(h, d, link, seen) { if (seen === d.marks[o.tool]) return false; - const mine = (s) => (parsePairs(s) || []).filter(([k]) => half(k)) - .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)); - const stored = mine(d.hash); - if (encodePairs(stored) === encodePairs(mine(h))) return false; + const stored = halfPairs(d.hash); + if (encodePairs(stored) === encodePairs(halfPairs(h))) return false; const merged = encodePairs((parsePairs(h) || []).filter(([k]) => !half(k)).concat(stored)); - if (!handOver(d.id, merged, false, { link, marks: marksFor(d.marks[o.tool]) })) return false; + const more = { link, marks: marksFor(d.marks[o.tool]), ...carry(refused(), base) }; + if (!handOver(d.id, merged, false, more)) return false; go(merged); return true; } @@ -7371,7 +7493,8 @@

Your drawers

} function paintBar() { const d = attached && find(loadAll(), attached); - if (attached && !d) { attached = null; failing = false; } // deleted on another tab + // deleted on another tab + if (attached && !d) { attached = null; failing = false; refusedIn = false; drop(); } /* A refused save leads, ahead of the name: on a phone the bar shows about a dozen characters, and the warning is the part that has to survive the cut. */ const shown = d ? (failing ? `not saving · ${d.name}` : d.name) : 'not saved'; @@ -7508,7 +7631,7 @@

Your drawers

return; } attached = d.id; armed = ''; renaming = ''; - base = sharedOf(h); failing = false; + base = sharedOf(h); sealedAt = base; failing = false; refusedIn = false; drop(); ours = d.marks[o.tool]; theirs = undefined; // the other tool has no mark in a new drawer savedInto(d.id); @@ -7567,7 +7690,7 @@

Your drawers

s.drawers = s.drawers.filter((x) => x.id !== id); if (!saveAll(s)) { say('This browser would not store the change.', 'bad'); return; } const wasOpen = attached === id; - if (wasOpen) { attached = null; failing = false; } + if (wasOpen) { attached = null; failing = false; refusedIn = false; drop(); } armed = ''; render(); say(`Deleted “${d.name}”.` + (wasOpen @@ -7683,8 +7806,24 @@

Your drawers

addEventListener('pageshow', (e) => { if (!e.persisted || !attached) return; const d = find(loadAll(), attached); - if (!d) return; + if (!d) { paintBar(); return; } // deleted since: the bar says so const h = o.design(); + /* Refusals that have all landed since, from a later page: this one is as any page come + back. All but a change to its own half, which the later page did not save: refused + with the size, it is still this page's alone, and the bar still says so until a save + goes through. Some of them landed: its changes are counted from the first still to + land. */ + const n = refused() ? landedTo(rids) : 0; + if (n && n === rids.length) { + refusedIn = false; drop(); base = sharedOf(h); + if (encodePairs(halfPairs(h)) === encodePairs(halfPairs(d.hash))) failing = false; + paintBar(); + } else if (n) { + hold(rids.slice(n).map((id) => [id, bases.get(id) || base])); + base = bases.get(rids[0]); + } + sealed = true; // its records so far went into the cache with it + sealedAt = sharedOf(h); if (movedOn(d, h, ours)) reopen(d); // a later page saved into it else catchUp(h, d); }); @@ -7775,6 +7914,8 @@

Your drawers

attached = null; ours = undefined; theirs = undefined; + refusedIn = false; + drop(); const { next, left } = takeOnce(); // read every time, so a stale note never lingers if (arrivedWith) { const s = loadAll(); @@ -7801,11 +7942,13 @@

Your drawers

} if (d) { attached = d.id; - base = sharedOf(arrivedWith); - // the marks the design's halves came with, from the note or this tab's own mark - const came = noted ? (isPlain(next.marks) ? next.marks : {}) - : mine && mine.id === d.id ? { [o.tool]: mine.ours, [otherTool]: mine.theirs } - : gone && gone.id === d.id ? { [o.tool]: gone.ours, [otherTool]: gone.theirs } : {}; + base = sharedOf(arrivedWith); sealedAt = base; + // the record the design came with: the note, this tab's own mark, or a raced reload's + const from = noted ? next : mine && mine.id === d.id ? mine + : gone && gone.id === d.id ? gone : null; + // the marks the design's halves came with, by it + const came = !from ? {} : noted ? (isPlain(next.marks) ? next.marks : {}) + : { [o.tool]: from.ours, [otherTool]: from.theirs }; const str = (v) => (typeof v === 'string' ? v : undefined); theirs = str(came[otherTool]); /* A raced reload's link settings, those the drawer still has as the page had @@ -7815,6 +7958,17 @@

Your drawers

? strings(gone.link).filter((k) => stored.get(k) === base.get(k)) : null; if (!noted && movedOn(d, arrivedWith, str(came[o.tool])) && reopen(d, held)) return; ours = d.marks[o.tool]; + /* A design holding a change the drawer refused: a hand-over from a page whose + saves into the drawer were refused, or this page reloaded or gone Back to after + its own were. The record says so, with that page's base (see carry), and the + change is counted from that base, as it was there. It is still to be saved, + and a size another tab moved on since that page last saved is caught up below. + Counted from the design, the change was taken for the drawer's, and the + catch-up put the older size back over it. Counted from the drawer's settings, + a size that page had kept from before another tab moved it on was taken for + the change, and its next save wrote it over that tab's. */ + const kept = carried(from); + if (kept) { refusedIn = true; base = kept.base; hold(kept.held); } /* A hand-over, onto a drawer this tool has saved into. One carrying a link's settings too: restore keeps the settings the other page sets, which are the link's, and this tool's half was saved into the drawer with them. */ @@ -7829,7 +7983,10 @@

Your drawers

if (noted) { d.hash = mergeDesign(d.hash, arrivedWith, o.owns, base); d.marks[o.tool] = fp; - if (saveAll(s)) ours = fp; + if (saveAll(s)) { + if (refused()) land(); + ours = fp; base = sharedOf(arrivedWith); sealedAt = base; refusedIn = false; + } savedInto(d.id); } } @@ -7852,7 +8009,8 @@

Your drawers

const s = loadAll(); const d = find(s, attached); if (!d) { - attached = null; failing = false; savedInto(''); leaving('', '', ours, link); paintBar(); return; + attached = null; failing = false; refusedIn = false; drop(); + savedInto(''); leaving('', '', ours, link); paintBar(); return; } // nothing of this page's own to save, and a reload reopens onto the drawer if (behind(d, h)) { leaving(d.id, d.marks[o.tool], ours, link); return; } @@ -7861,12 +8019,23 @@

Your drawers

d.marks[o.tool] = fingerprint(h); d.saved = Date.now(); const ok = saveAll(s); - if (ok) { base = sharedOf(h); ours = d.marks[o.tool]; } + if (ok) { + if (refused()) land(); + base = sharedOf(h); sealedAt = base; ours = d.marks[o.tool]; refusedIn = false; + } else if (sealed) { + /* A refusal of this page's own, apart from any it arrived with (see rids), counted + from the page as it last sealed. The first the page holds counts from its base, + which can be older: a change it arrived with, from a record with no ids, is + still to save. */ + const at = rids.length ? sealedAt || base : base; + hold(rids.map((id) => [id, bases.get(id) || base]).concat([[newRid(), at]])); + sealed = false; + } savedInto(d.id); /* Refused, the drawer still holds the save before, and the address has the page's change, past the save the page last made into it (had): a reload that raced this save keeps it, rather than reopening onto the older half. */ - leaving(d.id, ok ? d.marks[o.tool] : was, had, link); + leaving(d.id, ok ? d.marks[o.tool] : was, had, link, !ok); /* The page's own save shares this storage and fails without a word, but this one is promised in so many words — the dialog says changes save into the drawer as you work — so a refused save is said, on the bar and in the dialog, until one goes @@ -7893,11 +8062,16 @@

Your drawers

if (d && typeof mine === 'string' && !behind(d, mine)) { d.hash = mergeDesign(d.hash, h, o.owns, base); d.saved = Date.now(); - if (saveAll(s)) base = sharedOf(h); + if (saveAll(s)) { + if (refused()) land(); + base = sharedOf(h); + } } /* Behind or not, the note says which save this page's half is: one the drawer has moved on from comes back from the other page as the drawer has it (restore). */ - handOver(d ? d.id : '', h, false, { link, marks: d ? marksFor(ours) : {} }); + handOver(d ? d.id : '', h, false, + { link, marks: d ? marksFor(ours) : {}, ...carry(!!d && refused(), base) }); + sealed = true; // handed on: a refusal after this, from the cache, is another }, }; } @@ -10120,6 +10294,8 @@

Your drawers

* stops that being your problem. */ let hashSaveT = 0, hashReady = false; +// saves were on when Start fresh left the page, and nothing has left it since (see startFresh) +let freshLeft = false; /* Kept on this browser, so the work survives arriving without a link. * * The address bar already carries the design and a refresh already restores it. What it @@ -10140,6 +10316,8 @@

Your drawers

* when it has done one and offers a way back. */ const SAVE_KEY = 'drawerforge:plates:v1'; +// this tab's record of a save a pasted link set aside (see pastedFrom), declared here for Start fresh +const PASTED_KEY = SAVE_KEY + ':pasted'; const saveLocal = (h) => { try { localStorage.setItem(SAVE_KEY, h); } catch (err) { /* private mode, or the quota is full — losing the save is not worth @@ -10152,11 +10330,25 @@

Your drawers

const isLayoutHash = (h) => /(^|&)[^&=]+=/.test(h); function startFresh() { try { localStorage.removeItem(SAVE_KEY); } catch (err) { /* nothing to clear */ } - location.href = location.origin + location.pathname; // drop the hash and reload clean + forgetPasted(); + const saving = hashReady || freshLeft; // pressed again before the page goes: as the first press found it + /* Left as Put back leaves, by leaveFor: the page runs on until the bare one arrives, and + a change that landed in between was saved after the clearing, and came back with the + note that it had been restored. */ + leaveFor(location.origin + location.pathname); // drop the hash and reload clean + freshLeft = saving; // after leaveFor, which clears it } /* Wired here, before the boot below reads any link: a link that throws there must not - also take away the button that gets you out of it, or stop the next link working. */ + also take away the button that gets you out of it, or stop the next link working. What + leaveFor stops, hashReady and hashSaveT, is declared above, so it works from here too. */ $('startFresh').addEventListener('click', startFresh); +/* Left by Start fresh and shown again from the back-forward cache, as Back from the fresh + page can be in some browsers: the page is yours again, and saves as it did before, as it + does loaded. Not after Put back or Try anyway, which leave by leaveFor too, even pressed + after Start fresh before the page has gone: loaded, that page is a link again and sets + your layout aside first, and from the cache its first save would go over the layout just + put back. */ +addEventListener('pageshow', (e) => { if (e.persisted && freshLeft) { hashReady = true; freshLeft = false; } }); /* A hash this page did not write means someone navigated to a link — pasted a share URL into the address bar, or picked a bookmark — and changing only the fragment is a same-document navigation, so nothing re-reads it and the drawer on screen stays put. @@ -10225,7 +10417,7 @@

Your drawers

return [...SHARED_KEYS].filter((k) => k in q && p[k] === q[k]); } function leaveFor(url) { - hashReady = false; dropSave(); // no save of this page's may land after + hashReady = false; freshLeft = false; dropSave(); // no save of this page's may land after location.href = url; } /* Swapped rather than copied over: what is here now goes aside in its place, so putting @@ -10241,6 +10433,7 @@

Your drawers

} saveLocal(prev); writeKey(LINKED_KEY, prevLinked); + forgetPasted(); leaveFor(location.href.split('#')[0]); // a bare visit restores it, and says so } function tryAnyway() { @@ -10322,10 +10515,44 @@

Your drawers

drawer the address is at: marked before it, a reload took the save before for its own, and after another tab put the drawer back to that one, the reload wrote this page's later change back over it. */ - try { history.replaceState(drawers.stamp(h, linkedNow && bootDesc !== null), '', '#' + h); } - catch (err) { /* some browsers refuse replaceState on file:// — a lost URL is not - worth an exception that stops the rest of the page working */ } - } + if (!pastedOver()) { + try { history.replaceState(drawers.stamp(h, linkedNow && bootDesc !== null), '', '#' + h); } + catch (err) { /* some browsers refuse replaceState on file:// — a lost URL is not + worth an exception that stops the rest of the page working */ } + ownHash = location.hash; + } else { + try { sessionStorage.setItem(PASTED_KEY, JSON.stringify({ save: DRAWERS.fingerprint(h), + at: DRAWERS.fingerprint(ownHash) })); } + catch (err) { /* not kept, Back offers nothing: no worse than before */ } + } + } +} +/* The address as this page last left it: as it arrived, then as each save wrote it. One + that differs, with a layout in it, is a link gone to over this page, pasted or picked + from the bookmarks, whose hashchange (above) has not run yet: a page busy drawing comes + to a save that was waiting first. That save is still made, so the layout the link + replaces holds the change and is set aside with it, but the address is the link's. + Written back over, the hashchange found this page's design there and reloaded that, + and the link was gone. */ +let ownHash = null; +const pastedOver = () => ownHash !== null && location.hash !== ownHash && + isLayoutHash((location.hash || '').replace(/^#/, '')); +/* That save, and the address it left as it was, by fingerprint, for this tab: the layout + the link sets aside is the save, and it is later than the address, which never had the + change. Back to the address offers it, and only it (see `later` below). */ +const pastedFrom = (prev) => { + try { + const r = JSON.parse(sessionStorage.getItem(PASTED_KEY) || 'null'); + return !!r && !!prev && r.save === DRAWERS.fingerprint(prev) && + r.at === DRAWERS.fingerprint(location.hash); + } catch (err) { return false; } +}; +/* Start fresh and Put back each leave that save behind, and the record goes with them. + Kept past Start fresh, Back to a page at the same address offered the save as the later + layout, though Start fresh came after it. Start fresh works from before the boot reads a + link, so PASTED_KEY is declared with SAVE_KEY, above it. */ +function forgetPasted() { + try { sessionStorage.removeItem(PASTED_KEY); } catch (err) { /* nothing kept to forget */ } } /* A reload takes the address as it stands when it starts, and the page runs on until the new one arrives. A save still waiting would land in that gap and record in the saved @@ -10761,17 +10988,30 @@

Your drawers

layout was set aside and offered a Put back that brought nothing back. */ let keptAside = false; if (aside) { + const asideLinked = linkKeys(saved, linked).length ? linked : ''; writeKey(PREV_KEY, saved); keptAside = readKey(PREV_KEY) === saved; - if (keptAside) writeKey(PREV_LINKED_KEY, linkKeys(saved, linked).length ? linked : ''); + if (keptAside) writeKey(PREV_LINKED_KEY, asideLinked); + /* With the record of whether it is a link's refused, the one left from the layout set + aside before would answer for it. That goes, and put back, this one is yours: still + better than not setting it aside (unkept), which keeps it only until the first + change made on the link. */ + if (keptAside && readKey(PREV_LINKED_KEY) !== asideLinked) writeKey(PREV_LINKED_KEY, ''); /* Not kept, it is not written over either (unkept), unless a hand-over of your own brings on anything the other page sets: then the save holds the drawer, bed or the other page's settings from before, and a bare visit took those back to the other page. One still carrying someone's link is that link, and your layout is kept. */ - else unkept = !handOver || handOver.link.length > 0 || drawers.onlyMine(saved, src); - } + if (!keptAside) unkept = !handOver || handOver.link.length > 0 || drawers.onlyMine(saved, src); + } + /* Back to your own earlier page over a link's layout, untouched, sets nothing aside: what + the link replaced is aside already. That can be later than the page Back brings: a change + whose save came due as the link was pasted is aside, and in no earlier address (see + pastedOver). So that layout is offered, if it is the one aside and this is the address it + came from, and no other: one aside for any other reason can be older than this page, and + Put back went further back, not on. */ + const later = back && savedLinked && pastedFrom(readKey(PREV_KEY)) ? readKey(PREV_KEY) : ''; const canPutBack = (replaces && !kept && (keptAside || (savedLinked && !!readKey(PREV_KEY)))) || - (back && keptAside); + (back && (keptAside || (!!later && !sameDesign(later, src)))); if (stalled) { showSetAside('This layout did not finish loading last time, so the page has started ' + 'from its defaults rather than try it again.', canPutBack, true); @@ -10799,6 +11039,7 @@

Your drawers

} } hashReady = true; // loadFromHash has had its say; ours may start +ownHash = location.hash; recomputeLayout(); autoFrame(); bootDesc = encodeDesc(descriptor()); diff --git a/src/bins/ui.js b/src/bins/ui.js index e061703..ce0dd88 100644 --- a/src/bins/ui.js +++ b/src/bins/ui.js @@ -5325,6 +5325,8 @@ function cleanNote(n) { * stops that being your problem. */ let hashSaveT = 0, hashReady = false; +// saves were on when Start fresh left the page, and nothing has left it since (see startFresh) +let freshLeft = false; /* Kept on this browser, so the work survives arriving without a link. * * The address bar already carries the design and a refresh already restores it. What it @@ -5345,6 +5347,8 @@ let hashSaveT = 0, hashReady = false; * when it has done one and offers a way back. */ const SAVE_KEY = 'drawerforge:bins:v1'; +// this tab's record of a save a pasted link set aside (see pastedFrom), declared here for Start fresh +const PASTED_KEY = SAVE_KEY + ':pasted'; const saveLocal = (h) => { try { localStorage.setItem(SAVE_KEY, h); } catch (err) { /* private mode, or the quota is full — losing the save is not worth @@ -5357,11 +5361,25 @@ const readLocal = () => { try { return localStorage.getItem(SAVE_KEY) || ''; } c const isLayoutHash = (h) => /(^|&)[^&=]+=/.test(h); function startFresh() { try { localStorage.removeItem(SAVE_KEY); } catch (err) { /* nothing to clear */ } - location.href = location.origin + location.pathname; // drop the hash and reload clean + forgetPasted(); + const saving = hashReady || freshLeft; // pressed again before the page goes: as the first press found it + /* Left as Put back leaves, by leaveFor: the page runs on until the bare one arrives, and + a change that landed in between was saved after the clearing, and came back with the + note that it had been restored. */ + leaveFor(location.origin + location.pathname); // drop the hash and reload clean + freshLeft = saving; // after leaveFor, which clears it } /* Wired here, before the boot below reads any link: a link that throws there must not - also take away the button that gets you out of it, or stop the next link working. */ + also take away the button that gets you out of it, or stop the next link working. What + leaveFor stops, hashReady and hashSaveT, is declared above, so it works from here too. */ $('startFresh').addEventListener('click', startFresh); +/* Left by Start fresh and shown again from the back-forward cache, as Back from the fresh + page can be in some browsers: the page is yours again, and saves as it did before, as it + does loaded. Not after Put back or Try anyway, which leave by leaveFor too, even pressed + after Start fresh before the page has gone: loaded, that page is a link again and sets + your layout aside first, and from the cache its first save would go over the layout just + put back. */ +addEventListener('pageshow', (e) => { if (e.persisted && freshLeft) { hashReady = true; freshLeft = false; } }); /* A hash this page did not write means someone navigated to a link — pasted a share URL into the address bar, or picked a bookmark — and changing only the fragment is a same-document navigation, so nothing re-reads it and the drawer on screen stays put. @@ -5430,7 +5448,7 @@ function linkKeys(h, link) { return [...SHARED_KEYS].filter((k) => k in q && p[k] === q[k]); } function leaveFor(url) { - hashReady = false; clearTimeout(hashSaveT); // no save of this page's may land after + hashReady = false; freshLeft = false; clearTimeout(hashSaveT); // no save of this page's may land after location.href = url; } /* Swapped rather than copied over: what is here now goes aside in its place, so putting @@ -5446,6 +5464,7 @@ function putBack() { } saveLocal(prev); writeKey(LINKED_KEY, prevLinked); + forgetPasted(); leaveFor(location.href.split('#')[0]); // a bare visit restores it, and says so } function tryAnyway() { @@ -5507,11 +5526,45 @@ function saveNow() { drawer the address is at: marked before it, a reload took the save before for its own, and after another tab put the drawer back to that one, the reload wrote this page's later change back over it. */ - try { history.replaceState(drawers.stamp(h, linkedNow && bootDesc !== null), '', '#' + h); } - catch (err) { /* some browsers refuse replaceState on file:// — a lost URL is not - worth an exception that stops the rest of the page working */ } + if (!pastedOver()) { + try { history.replaceState(drawers.stamp(h, linkedNow && bootDesc !== null), '', '#' + h); } + catch (err) { /* some browsers refuse replaceState on file:// — a lost URL is not + worth an exception that stops the rest of the page working */ } + ownHash = location.hash; + } else { + try { sessionStorage.setItem(PASTED_KEY, JSON.stringify({ save: DRAWERS.fingerprint(h), + at: DRAWERS.fingerprint(ownHash) })); } + catch (err) { /* not kept, Back offers nothing: no worse than before */ } + } } } +/* The address as this page last left it: as it arrived, then as each save wrote it. One + that differs, with a layout in it, is a link gone to over this page, pasted or picked + from the bookmarks, whose hashchange (above) has not run yet: a page busy drawing comes + to a save that was waiting first. That save is still made, so the layout the link + replaces holds the change and is set aside with it, but the address is the link's. + Written back over, the hashchange found this page's design there and reloaded that, + and the link was gone. */ +let ownHash = null; +const pastedOver = () => ownHash !== null && location.hash !== ownHash && + isLayoutHash((location.hash || '').replace(/^#/, '')); +/* That save, and the address it left as it was, by fingerprint, for this tab: the layout + the link sets aside is the save, and it is later than the address, which never had the + change. Back to the address offers it, and only it (see `later` below). */ +const pastedFrom = (prev) => { + try { + const r = JSON.parse(sessionStorage.getItem(PASTED_KEY) || 'null'); + return !!r && !!prev && r.save === DRAWERS.fingerprint(prev) && + r.at === DRAWERS.fingerprint(location.hash); + } catch (err) { return false; } +}; +/* Start fresh and Put back each leave that save behind, and the record goes with them. + Kept past Start fresh, Back to a page at the same address offered the save as the later + layout, though Start fresh came after it. Start fresh works from before the boot reads a + link, so PASTED_KEY is declared with SAVE_KEY, above it. */ +function forgetPasted() { + try { sessionStorage.removeItem(PASTED_KEY); } catch (err) { /* nothing kept to forget */ } +} /* A reload takes the address as it stands when it starts, and the page runs on until the new one arrives. A save still waiting would land in that gap and record in the saved drawer a design the reloaded page did not arrive with, and the page came back unsaved. @@ -5920,17 +5973,30 @@ let arrivedWith = ''; // the design string this page was opened with layout was set aside and offered a Put back that brought nothing back. */ let keptAside = false; if (aside) { + const asideLinked = linkKeys(saved, linked).length ? linked : ''; writeKey(PREV_KEY, saved); keptAside = readKey(PREV_KEY) === saved; - if (keptAside) writeKey(PREV_LINKED_KEY, linkKeys(saved, linked).length ? linked : ''); + if (keptAside) writeKey(PREV_LINKED_KEY, asideLinked); + /* With the record of whether it is a link's refused, the one left from the layout set + aside before would answer for it. That goes, and put back, this one is yours: still + better than not setting it aside (unkept), which keeps it only until the first + change made on the link. */ + if (keptAside && readKey(PREV_LINKED_KEY) !== asideLinked) writeKey(PREV_LINKED_KEY, ''); /* Not kept, it is not written over either (unkept), unless a hand-over of your own brings on anything the other page sets: then the save holds the drawer, bed or the other page's settings from before, and a bare visit took those back to the other page. One still carrying someone's link is that link, and your layout is kept. */ - else unkept = !handOver || handOver.link.length > 0 || drawers.onlyMine(saved, src); + if (!keptAside) unkept = !handOver || handOver.link.length > 0 || drawers.onlyMine(saved, src); } + /* Back to your own earlier page over a link's layout, untouched, sets nothing aside: what + the link replaced is aside already. That can be later than the page Back brings: a change + whose save came due as the link was pasted is aside, and in no earlier address (see + pastedOver). So that layout is offered, if it is the one aside and this is the address it + came from, and no other: one aside for any other reason can be older than this page, and + Put back went further back, not on. */ + const later = back && savedLinked && pastedFrom(readKey(PREV_KEY)) ? readKey(PREV_KEY) : ''; const canPutBack = (replaces && !kept && (keptAside || (savedLinked && !!readKey(PREV_KEY)))) || - (back && keptAside); + (back && (keptAside || (!!later && !sameDesign(later, src)))); if (stalled) { showSetAside('This layout did not finish loading last time, so the page has started ' + 'from its defaults rather than try it again.', canPutBack, true); @@ -5971,6 +6037,7 @@ if (pendingNotes) { } readControls(); hashReady = true; // loadFromHash has had its say; ours may start +ownHash = location.hash; initThree(); initMap(); drawLayerTabs(); diff --git a/src/shared-ui/drawers.js b/src/shared-ui/drawers.js index 4beb04e..39f2ca3 100644 --- a/src/shared-ui/drawers.js +++ b/src/shared-ui/drawers.js @@ -326,6 +326,26 @@ const DRAWERS = (function () { let attached = null; // the drawer this page saves into, or null for an unsaved design let base = null; // its shared keys as this page arrived with or last saved them let failing = false; // the browser refused the last save into it + /* The page arrived as a page whose change the drawer refused left it (see attach), and + nothing it has saved since has gone through: the change is still the address's alone. */ + let refusedIn = false; + const refused = () => failing || refusedIn; + /* The refusals the page holds, by the ids its records hand on (see carry and land): any + it arrived with, and one of its own for its refused saves since it last handed them + on, by a hand-over or as it went into the back-forward cache (`sealed` till then). + With one id for the whole chain, a save that went through on an earlier page counted + a later page's change as landed too, though it had never been saved: Forward to that + page lost a depth refused there. + Each id has the base its own changes are counted from (`bases`): the page's shared keys + as it last sealed (`sealedAt`), arriving, saving or coming back from the cache. Counted + from the first page's base, a size that page's refusal held stayed a change of the + later page's after it was saved and set back since, and Forward to the later page + wrote it over the one set back. */ + let rids = []; + let bases = new Map(); + let sealedAt = null; + let sealed = true; + const drop = () => { rids = []; bases = new Map(); sealed = true; }; /* This tool's mark in the drawer at the page's last save into it that went through, or as it arrived: the page's half is that save or newer. Newer when the browser refused the saves since (storage full), and then the address is the one copy of the @@ -351,19 +371,99 @@ const DRAWERS = (function () { if (n[o.tool] !== id) { n[o.tool] = id; writeNote(area, key, n); } } } + /* For a page whose design holds a change the drawer refused (`on`), what the page that + takes the design on needs to know of it, in a note, a mark or a raced reload's + record: that it does, and the page's base `b`, its shared keys as it last saved them + or arrived with them, which its changes are counted from (see attach). With the ids + of the refusals it holds (see rids), so that once they land, its records can be told + apart from one still to save (see land), and each one's base (`bs`, the page's own + but for a catch-up's). Nothing for any other page, whose base is the design it hands + on. */ + const newRid = () => Math.random().toString(36).slice(2, 10) || 'r'; + const carry = (on, b, bs = bases) => { + if (!(on && b)) return {}; + if (!rids.length) { rids = [newRid()]; bases = new Map([[rids[0], b]]); } + return { refused: true, base: [...b], rids: rids.slice(), bases: rids.map((id) => [...(bs.get(id) || b)]) }; + }; + // ids as a record or the tab's note has them, what carry makes and no more + const RID = /^[a-z0-9]{1,16}$/; + const ridsIn = (v) => strings(v).filter((id) => RID.test(id)); + const landedIds = () => ridsIn(readNote('sessionStorage', TAB).landed); + /* A save that went through while the page held refusals: their changes are in the + drawer now, or were changed again before they got there, and either way every record + of them is older than the drawer. Kept for this tab, the last 128, so Back to one of + them is a page of yours come back, caught up with the drawer. Counted from its base, + a size set back on the other page since was taken for the change, and saved over the + one set back. */ + function land() { + if (rids.length) { + const done = landedIds(); + const add = rids.filter((id) => !done.includes(id)); + if (add.length) { + const n = readNote('sessionStorage', TAB); + n.landed = done.concat(add).slice(-128); + writeNote('sessionStorage', TAB, n); + } + } + drop(); + } + /* How many of `ids`, oldest first, have landed: all up to the last one that has. The + page that held it held those before it too, with their changes, so its save that went + through saved them, or a change since replaced them. A page that keeps only the last + of a long chain's ids (see hold) lands them so, and Back to one holding the first + found it still to save. */ + const landedTo = (ids) => { + const done = new Set(landedIds()); + let n = ids.length; + while (n > 0 && !done.has(ids[n - 1])) n -= 1; + return n; + }; + // a base as a record has it, the shared keys and no more + const baseIn = (b) => new Map((Array.isArray(b) ? b : []).filter((p) => Array.isArray(p) && + p.length === 2 && typeof p[0] === 'string' && typeof p[1] === 'string' && SHARED.has(p[0]))); + /* What a note, mark or record carries (see carry): its refusals still to land, oldest + first, as [id, base], and the base the page's changes are counted from, the first + one's. Null for one that carries none, or whose refusals have all landed since. */ + function carried(r) { + if (!isPlain(r) || r.refused !== true || !Array.isArray(r.base)) return null; + const all = baseIn(r.base); + const ids = Array.isArray(r.rids) ? r.rids : []; + // a record from before each id had a base: all of them have the record's + const bs = Array.isArray(r.bases) && r.bases.length === ids.length ? r.bases : null; + const held = []; + for (let i = Math.max(0, ids.length - 64); i < ids.length; i += 1) { // more than a page keeps + if (typeof ids[i] === 'string' && RID.test(ids[i])) held.push([ids[i], bs ? baseIn(bs[i]) : all]); + } + const n = landedTo(held.map(([id]) => id)); + if (held.length && n === held.length) return null; + const rest = held.slice(n); + return { base: rest.length ? rest[0][1] : all, held: rest }; + } + /* The refusals `held` ([id, base], oldest first) as the page's own: the last 32, the + first of them counted from the page's base, which is the first one's, so the changes + of those let go are still counted. */ + function hold(held) { + const kept = held.slice(-32); + if (kept.length < held.length) kept[0] = [kept[0][0], base]; + rids = kept.map(([id]) => id); + bases = new Map(kept); + } /* The note for the next page to load in this tab: the drawer ('' for none), and the fingerprint of the design that page will arrive with. `link` lists the drawer, bed and infill settings in it that are still someone's link's, not yours (the tool's ui.js works that out); `open` says a drawer was opened from the list, or caught up, rather than handed over. `marks` gives, for each tool, its mark in the drawer when its settings in `h` were current, where that is known (see restore): by tool, since - by way of the guide the next page can be either. Read once, by the page's boot (see - arrival). False if the browser would not keep it. */ + by way of the guide the next page can be either. `refused` and `base` say `h` holds + a change the drawer refused, and what it is counted from (see carry). Read once, by + the page's boot (see arrival). False if the browser would not keep it. */ function handOver(id, h, caughtUp, more) { const n = readNote('sessionStorage', TAB); n.next = { id, fp: fingerprint(h), caughtUp: !!caughtUp, link: (more && more.link) || [], open: !!(more && more.open), - marks: (more && more.marks) || {} }; + marks: (more && more.marks) || {}, + ...(more && more.refused ? { refused: true, base: more.base, rids: more.rids, bases: more.bases } + : {}) }; return writeNote('sessionStorage', TAB, n); } /* With it, the record of the address this tool's last save left (see wrote), which is @@ -391,11 +491,12 @@ const DRAWERS = (function () { pasted over the page reloads it too, and the page says so first (forget). The record also carries what the address's own mark would have said: the page's marks from before the save (ours, theirs), by which the drawer has moved on from the address or - not, and which settings in the design saved are still someone's link's (link). */ - function leaving(id, now, had, link) { + not, which settings in the design saved are still someone's link's (link), and + whether the drawer refused the save, with the page's base (see carry). */ + function leaving(id, now, had, link, refusedSave) { const n = readNote('sessionStorage', TAB); n.left = { tool: o.tool, id, was: fingerprint((location.hash || '').replace(/^#/, '')), now, - ours: had, theirs, link: strings(link) }; + ours: had, theirs, link: strings(link), ...carry(refusedSave, base) }; writeNote('sessionStorage', TAB, n); } function reloaded() { @@ -436,12 +537,13 @@ const DRAWERS = (function () { link, untouched since it arrived; `note` the note the page arrived at it by, until the page saves from it. */ const stamp = (h, link, note) => ({ drawerforge: { tool: o.tool, fp: fingerprint(h), - id: attached || '', link: !!link, ...(note ? { note } : {}), ours, theirs } }); + id: attached || '', link: !!link, ...(note ? { note } : {}), ours, theirs, ...carry(refused(), base) } }); // marks the address the page is at, if it is `h`, leaving it as it is function markHere(h, link, note) { if ((location.hash || '').replace(/^#/, '') !== h) return; try { history.replaceState(stamp(h, link, note), ''); } - catch (err) { /* refused on file://: a reload goes by the tab's record instead */ } + catch (err) { /* refused, as a browser may when it is called too often: a reload + goes by the tab's record instead */ } } // the marks for a note: this tool's `mine`, and the other's as this page has it const marksFor = (mine) => ({ [o.tool]: mine, [otherTool]: theirs }); @@ -466,7 +568,9 @@ const DRAWERS = (function () { this page finds, or another tab did. Showing the old values would be wrong twice over, since a download would use them too, so the page reloads onto the stored ones instead. The note marks that reload as a catch-up, and a catch-up is never followed - by another, so this cannot loop. True if the page is reloading. */ + by another, so this cannot loop. A change of the page's that the drawer refused goes + with it, counted from the base as it moves on with the drawer. True if the page is + reloading. */ function catchUp(h, d) { const stored = sharedOf(d.hash); const moved = [...stored.keys()].filter((k) => o.owns(k) && base.get(k) !== stored.get(k)); @@ -474,8 +578,23 @@ const DRAWERS = (function () { const pairs = parsePairs(h) || []; const merged = encodePairs(pairs.map(([k, v]) => [k, moved.includes(k) ? stored.get(k) : v]) .concat(moved.filter((k) => !pairs.some((p) => p[0] === k)).map((k) => [k, stored.get(k)]))); + // a base with the keys caught up as the drawer has them: the page's, and each refusal's + const catching = (b) => new Map([...b, ...moved.map((k) => [k, stored.get(k)])]); + const caught = catching(base); + const caughtEach = new Map([...bases].map(([id, b]) => [id, catching(b)])); + /* The page has the drawer's settings already: they are its base now, with nothing to + reload, and its address's mark says so. Left with the base before, a reload after + another tab set the size back took the page's size for its own change still to + save, and wrote it over the one set back. */ + if (merged === h) { + base = caught; bases = caughtEach; + const m = refused() && markOf(h); + if (m) markHere(h, m.link, m.note); + return false; + } + const more = { open: true, marks: marksFor(ours), ...carry(refused(), caught, caughtEach) }; // without the note the reloaded page could not tell it is this drawer, so stay put - if (!handOver(d.id, merged, true, { open: true, marks: marksFor(ours) })) return false; + if (!handOver(d.id, merged, true, more)) return false; go(merged); return true; } @@ -509,16 +628,19 @@ const DRAWERS = (function () { half the other page's copy was current with (`seen`), and while the drawer still holds that save, the copy is as new as the drawer or newer: with the browser's storage full, a bin placed before going across was saved nowhere else, and taking - the drawer's half lost it. True if the page is reloading. */ + the drawer's half lost it. A change the drawer refused goes with it, with its base + (see carry): the half reloaded is this tool's alone. True if the page is reloading. */ const half = (k) => o.owns(k) && !SHARED.has(k) && !(o.given || []).includes(k); + // this tool's half of the design `s`, in one order, so two halves compare as strings + const halfPairs = (s) => (parsePairs(s) || []).filter(([k]) => half(k)) + .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)); function restore(h, d, link, seen) { if (seen === d.marks[o.tool]) return false; - const mine = (s) => (parsePairs(s) || []).filter(([k]) => half(k)) - .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)); - const stored = mine(d.hash); - if (encodePairs(stored) === encodePairs(mine(h))) return false; + const stored = halfPairs(d.hash); + if (encodePairs(stored) === encodePairs(halfPairs(h))) return false; const merged = encodePairs((parsePairs(h) || []).filter(([k]) => !half(k)).concat(stored)); - if (!handOver(d.id, merged, false, { link, marks: marksFor(d.marks[o.tool]) })) return false; + const more = { link, marks: marksFor(d.marks[o.tool]), ...carry(refused(), base) }; + if (!handOver(d.id, merged, false, more)) return false; go(merged); return true; } @@ -534,7 +656,8 @@ const DRAWERS = (function () { } function paintBar() { const d = attached && find(loadAll(), attached); - if (attached && !d) { attached = null; failing = false; } // deleted on another tab + // deleted on another tab + if (attached && !d) { attached = null; failing = false; refusedIn = false; drop(); } /* A refused save leads, ahead of the name: on a phone the bar shows about a dozen characters, and the warning is the part that has to survive the cut. */ const shown = d ? (failing ? `not saving · ${d.name}` : d.name) : 'not saved'; @@ -671,7 +794,7 @@ const DRAWERS = (function () { return; } attached = d.id; armed = ''; renaming = ''; - base = sharedOf(h); failing = false; + base = sharedOf(h); sealedAt = base; failing = false; refusedIn = false; drop(); ours = d.marks[o.tool]; theirs = undefined; // the other tool has no mark in a new drawer savedInto(d.id); @@ -730,7 +853,7 @@ const DRAWERS = (function () { s.drawers = s.drawers.filter((x) => x.id !== id); if (!saveAll(s)) { say('This browser would not store the change.', 'bad'); return; } const wasOpen = attached === id; - if (wasOpen) { attached = null; failing = false; } + if (wasOpen) { attached = null; failing = false; refusedIn = false; drop(); } armed = ''; render(); say(`Deleted “${d.name}”.` + (wasOpen @@ -846,8 +969,24 @@ const DRAWERS = (function () { addEventListener('pageshow', (e) => { if (!e.persisted || !attached) return; const d = find(loadAll(), attached); - if (!d) return; + if (!d) { paintBar(); return; } // deleted since: the bar says so const h = o.design(); + /* Refusals that have all landed since, from a later page: this one is as any page come + back. All but a change to its own half, which the later page did not save: refused + with the size, it is still this page's alone, and the bar still says so until a save + goes through. Some of them landed: its changes are counted from the first still to + land. */ + const n = refused() ? landedTo(rids) : 0; + if (n && n === rids.length) { + refusedIn = false; drop(); base = sharedOf(h); + if (encodePairs(halfPairs(h)) === encodePairs(halfPairs(d.hash))) failing = false; + paintBar(); + } else if (n) { + hold(rids.slice(n).map((id) => [id, bases.get(id) || base])); + base = bases.get(rids[0]); + } + sealed = true; // its records so far went into the cache with it + sealedAt = sharedOf(h); if (movedOn(d, h, ours)) reopen(d); // a later page saved into it else catchUp(h, d); }); @@ -938,6 +1077,8 @@ const DRAWERS = (function () { attached = null; ours = undefined; theirs = undefined; + refusedIn = false; + drop(); const { next, left } = takeOnce(); // read every time, so a stale note never lingers if (arrivedWith) { const s = loadAll(); @@ -964,11 +1105,13 @@ const DRAWERS = (function () { } if (d) { attached = d.id; - base = sharedOf(arrivedWith); - // the marks the design's halves came with, from the note or this tab's own mark - const came = noted ? (isPlain(next.marks) ? next.marks : {}) - : mine && mine.id === d.id ? { [o.tool]: mine.ours, [otherTool]: mine.theirs } - : gone && gone.id === d.id ? { [o.tool]: gone.ours, [otherTool]: gone.theirs } : {}; + base = sharedOf(arrivedWith); sealedAt = base; + // the record the design came with: the note, this tab's own mark, or a raced reload's + const from = noted ? next : mine && mine.id === d.id ? mine + : gone && gone.id === d.id ? gone : null; + // the marks the design's halves came with, by it + const came = !from ? {} : noted ? (isPlain(next.marks) ? next.marks : {}) + : { [o.tool]: from.ours, [otherTool]: from.theirs }; const str = (v) => (typeof v === 'string' ? v : undefined); theirs = str(came[otherTool]); /* A raced reload's link settings, those the drawer still has as the page had @@ -978,6 +1121,17 @@ const DRAWERS = (function () { ? strings(gone.link).filter((k) => stored.get(k) === base.get(k)) : null; if (!noted && movedOn(d, arrivedWith, str(came[o.tool])) && reopen(d, held)) return; ours = d.marks[o.tool]; + /* A design holding a change the drawer refused: a hand-over from a page whose + saves into the drawer were refused, or this page reloaded or gone Back to after + its own were. The record says so, with that page's base (see carry), and the + change is counted from that base, as it was there. It is still to be saved, + and a size another tab moved on since that page last saved is caught up below. + Counted from the design, the change was taken for the drawer's, and the + catch-up put the older size back over it. Counted from the drawer's settings, + a size that page had kept from before another tab moved it on was taken for + the change, and its next save wrote it over that tab's. */ + const kept = carried(from); + if (kept) { refusedIn = true; base = kept.base; hold(kept.held); } /* A hand-over, onto a drawer this tool has saved into. One carrying a link's settings too: restore keeps the settings the other page sets, which are the link's, and this tool's half was saved into the drawer with them. */ @@ -992,7 +1146,10 @@ const DRAWERS = (function () { if (noted) { d.hash = mergeDesign(d.hash, arrivedWith, o.owns, base); d.marks[o.tool] = fp; - if (saveAll(s)) ours = fp; + if (saveAll(s)) { + if (refused()) land(); + ours = fp; base = sharedOf(arrivedWith); sealedAt = base; refusedIn = false; + } savedInto(d.id); } } @@ -1015,7 +1172,8 @@ const DRAWERS = (function () { const s = loadAll(); const d = find(s, attached); if (!d) { - attached = null; failing = false; savedInto(''); leaving('', '', ours, link); paintBar(); return; + attached = null; failing = false; refusedIn = false; drop(); + savedInto(''); leaving('', '', ours, link); paintBar(); return; } // nothing of this page's own to save, and a reload reopens onto the drawer if (behind(d, h)) { leaving(d.id, d.marks[o.tool], ours, link); return; } @@ -1024,12 +1182,23 @@ const DRAWERS = (function () { d.marks[o.tool] = fingerprint(h); d.saved = Date.now(); const ok = saveAll(s); - if (ok) { base = sharedOf(h); ours = d.marks[o.tool]; } + if (ok) { + if (refused()) land(); + base = sharedOf(h); sealedAt = base; ours = d.marks[o.tool]; refusedIn = false; + } else if (sealed) { + /* A refusal of this page's own, apart from any it arrived with (see rids), counted + from the page as it last sealed. The first the page holds counts from its base, + which can be older: a change it arrived with, from a record with no ids, is + still to save. */ + const at = rids.length ? sealedAt || base : base; + hold(rids.map((id) => [id, bases.get(id) || base]).concat([[newRid(), at]])); + sealed = false; + } savedInto(d.id); /* Refused, the drawer still holds the save before, and the address has the page's change, past the save the page last made into it (had): a reload that raced this save keeps it, rather than reopening onto the older half. */ - leaving(d.id, ok ? d.marks[o.tool] : was, had, link); + leaving(d.id, ok ? d.marks[o.tool] : was, had, link, !ok); /* The page's own save shares this storage and fails without a word, but this one is promised in so many words — the dialog says changes save into the drawer as you work — so a refused save is said, on the bar and in the dialog, until one goes @@ -1056,11 +1225,16 @@ const DRAWERS = (function () { if (d && typeof mine === 'string' && !behind(d, mine)) { d.hash = mergeDesign(d.hash, h, o.owns, base); d.saved = Date.now(); - if (saveAll(s)) base = sharedOf(h); + if (saveAll(s)) { + if (refused()) land(); + base = sharedOf(h); + } } /* Behind or not, the note says which save this page's half is: one the drawer has moved on from comes back from the other page as the drawer has it (restore). */ - handOver(d ? d.id : '', h, false, { link, marks: d ? marksFor(ours) : {} }); + handOver(d ? d.id : '', h, false, + { link, marks: d ? marksFor(ours) : {}, ...carry(!!d && refused(), base) }); + sealed = true; // handed on: a refusal after this, from the cache, is another }, }; } diff --git a/src/ui.js b/src/ui.js index 22dae09..ff41155 100644 --- a/src/ui.js +++ b/src/ui.js @@ -2210,6 +2210,8 @@ function parseHash(h) { * stops that being your problem. */ let hashSaveT = 0, hashReady = false; +// saves were on when Start fresh left the page, and nothing has left it since (see startFresh) +let freshLeft = false; /* Kept on this browser, so the work survives arriving without a link. * * The address bar already carries the design and a refresh already restores it. What it @@ -2230,6 +2232,8 @@ let hashSaveT = 0, hashReady = false; * when it has done one and offers a way back. */ const SAVE_KEY = 'drawerforge:plates:v1'; +// this tab's record of a save a pasted link set aside (see pastedFrom), declared here for Start fresh +const PASTED_KEY = SAVE_KEY + ':pasted'; const saveLocal = (h) => { try { localStorage.setItem(SAVE_KEY, h); } catch (err) { /* private mode, or the quota is full — losing the save is not worth @@ -2242,11 +2246,25 @@ const readLocal = () => { try { return localStorage.getItem(SAVE_KEY) || ''; } c const isLayoutHash = (h) => /(^|&)[^&=]+=/.test(h); function startFresh() { try { localStorage.removeItem(SAVE_KEY); } catch (err) { /* nothing to clear */ } - location.href = location.origin + location.pathname; // drop the hash and reload clean + forgetPasted(); + const saving = hashReady || freshLeft; // pressed again before the page goes: as the first press found it + /* Left as Put back leaves, by leaveFor: the page runs on until the bare one arrives, and + a change that landed in between was saved after the clearing, and came back with the + note that it had been restored. */ + leaveFor(location.origin + location.pathname); // drop the hash and reload clean + freshLeft = saving; // after leaveFor, which clears it } /* Wired here, before the boot below reads any link: a link that throws there must not - also take away the button that gets you out of it, or stop the next link working. */ + also take away the button that gets you out of it, or stop the next link working. What + leaveFor stops, hashReady and hashSaveT, is declared above, so it works from here too. */ $('startFresh').addEventListener('click', startFresh); +/* Left by Start fresh and shown again from the back-forward cache, as Back from the fresh + page can be in some browsers: the page is yours again, and saves as it did before, as it + does loaded. Not after Put back or Try anyway, which leave by leaveFor too, even pressed + after Start fresh before the page has gone: loaded, that page is a link again and sets + your layout aside first, and from the cache its first save would go over the layout just + put back. */ +addEventListener('pageshow', (e) => { if (e.persisted && freshLeft) { hashReady = true; freshLeft = false; } }); /* A hash this page did not write means someone navigated to a link — pasted a share URL into the address bar, or picked a bookmark — and changing only the fragment is a same-document navigation, so nothing re-reads it and the drawer on screen stays put. @@ -2315,7 +2333,7 @@ function linkKeys(h, link) { return [...SHARED_KEYS].filter((k) => k in q && p[k] === q[k]); } function leaveFor(url) { - hashReady = false; dropSave(); // no save of this page's may land after + hashReady = false; freshLeft = false; dropSave(); // no save of this page's may land after location.href = url; } /* Swapped rather than copied over: what is here now goes aside in its place, so putting @@ -2331,6 +2349,7 @@ function putBack() { } saveLocal(prev); writeKey(LINKED_KEY, prevLinked); + forgetPasted(); leaveFor(location.href.split('#')[0]); // a bare visit restores it, and says so } function tryAnyway() { @@ -2412,11 +2431,45 @@ function saveNow() { drawer the address is at: marked before it, a reload took the save before for its own, and after another tab put the drawer back to that one, the reload wrote this page's later change back over it. */ - try { history.replaceState(drawers.stamp(h, linkedNow && bootDesc !== null), '', '#' + h); } - catch (err) { /* some browsers refuse replaceState on file:// — a lost URL is not - worth an exception that stops the rest of the page working */ } + if (!pastedOver()) { + try { history.replaceState(drawers.stamp(h, linkedNow && bootDesc !== null), '', '#' + h); } + catch (err) { /* some browsers refuse replaceState on file:// — a lost URL is not + worth an exception that stops the rest of the page working */ } + ownHash = location.hash; + } else { + try { sessionStorage.setItem(PASTED_KEY, JSON.stringify({ save: DRAWERS.fingerprint(h), + at: DRAWERS.fingerprint(ownHash) })); } + catch (err) { /* not kept, Back offers nothing: no worse than before */ } + } } } +/* The address as this page last left it: as it arrived, then as each save wrote it. One + that differs, with a layout in it, is a link gone to over this page, pasted or picked + from the bookmarks, whose hashchange (above) has not run yet: a page busy drawing comes + to a save that was waiting first. That save is still made, so the layout the link + replaces holds the change and is set aside with it, but the address is the link's. + Written back over, the hashchange found this page's design there and reloaded that, + and the link was gone. */ +let ownHash = null; +const pastedOver = () => ownHash !== null && location.hash !== ownHash && + isLayoutHash((location.hash || '').replace(/^#/, '')); +/* That save, and the address it left as it was, by fingerprint, for this tab: the layout + the link sets aside is the save, and it is later than the address, which never had the + change. Back to the address offers it, and only it (see `later` below). */ +const pastedFrom = (prev) => { + try { + const r = JSON.parse(sessionStorage.getItem(PASTED_KEY) || 'null'); + return !!r && !!prev && r.save === DRAWERS.fingerprint(prev) && + r.at === DRAWERS.fingerprint(location.hash); + } catch (err) { return false; } +}; +/* Start fresh and Put back each leave that save behind, and the record goes with them. + Kept past Start fresh, Back to a page at the same address offered the save as the later + layout, though Start fresh came after it. Start fresh works from before the boot reads a + link, so PASTED_KEY is declared with SAVE_KEY, above it. */ +function forgetPasted() { + try { sessionStorage.removeItem(PASTED_KEY); } catch (err) { /* nothing kept to forget */ } +} /* A reload takes the address as it stands when it starts, and the page runs on until the new one arrives. A save still waiting would land in that gap and record in the saved drawer a design the reloaded page did not arrive with, and the page came back unsaved. @@ -2851,17 +2904,30 @@ let arrivedWith = ''; // the design string this page was opened with, if it s layout was set aside and offered a Put back that brought nothing back. */ let keptAside = false; if (aside) { + const asideLinked = linkKeys(saved, linked).length ? linked : ''; writeKey(PREV_KEY, saved); keptAside = readKey(PREV_KEY) === saved; - if (keptAside) writeKey(PREV_LINKED_KEY, linkKeys(saved, linked).length ? linked : ''); + if (keptAside) writeKey(PREV_LINKED_KEY, asideLinked); + /* With the record of whether it is a link's refused, the one left from the layout set + aside before would answer for it. That goes, and put back, this one is yours: still + better than not setting it aside (unkept), which keeps it only until the first + change made on the link. */ + if (keptAside && readKey(PREV_LINKED_KEY) !== asideLinked) writeKey(PREV_LINKED_KEY, ''); /* Not kept, it is not written over either (unkept), unless a hand-over of your own brings on anything the other page sets: then the save holds the drawer, bed or the other page's settings from before, and a bare visit took those back to the other page. One still carrying someone's link is that link, and your layout is kept. */ - else unkept = !handOver || handOver.link.length > 0 || drawers.onlyMine(saved, src); + if (!keptAside) unkept = !handOver || handOver.link.length > 0 || drawers.onlyMine(saved, src); } + /* Back to your own earlier page over a link's layout, untouched, sets nothing aside: what + the link replaced is aside already. That can be later than the page Back brings: a change + whose save came due as the link was pasted is aside, and in no earlier address (see + pastedOver). So that layout is offered, if it is the one aside and this is the address it + came from, and no other: one aside for any other reason can be older than this page, and + Put back went further back, not on. */ + const later = back && savedLinked && pastedFrom(readKey(PREV_KEY)) ? readKey(PREV_KEY) : ''; const canPutBack = (replaces && !kept && (keptAside || (savedLinked && !!readKey(PREV_KEY)))) || - (back && keptAside); + (back && (keptAside || (!!later && !sameDesign(later, src)))); if (stalled) { showSetAside('This layout did not finish loading last time, so the page has started ' + 'from its defaults rather than try it again.', canPutBack, true); @@ -2889,6 +2955,7 @@ let arrivedWith = ''; // the design string this page was opened with, if it s } } hashReady = true; // loadFromHash has had its say; ours may start +ownHash = location.hash; recomputeLayout(); autoFrame(); bootDesc = encodeDesc(descriptor()); diff --git a/sw.js b/sw.js index a298dd2..fea3fab 100644 --- a/sw.js +++ b/sw.js @@ -52,7 +52,7 @@ load from this site, and the app's icons and manifest, as paths from the root. VERSION is a hash of all of those files, names and bytes, and of this script as it is served, FILES filled in and everything else but VERSION itself. */ -const VERSION = "698fc6a0470c"; +const VERSION = "2f013a52cdc1"; const FILES = [ "./", "bins/", diff --git a/test/ui/drawers.spec.js b/test/ui/drawers.spec.js index d54ccd0..d0a1bf8 100644 --- a/test/ui/drawers.spec.js +++ b/test/ui/drawers.spec.js @@ -245,7 +245,8 @@ for (const tool of ['bins', 'plates']) { and the drawer still has the save before both. The reload took the drawer for newer than the page and reopened onto that older save, and the page's next save wrote it over the change everywhere. Now it keeps the address, and the later change, which the reload - never saw, is set aside. */ + never saw, is set aside. The change before has a size in it too, which the next save + writes: counted from the design the reload took, it was taken for the drawer's. */ for (const tool of ['bins', 'plates']) { const ready = tool === 'bins' ? binsReady : platesReady; const [field, key, before, refused, raced] = tool === 'bins' ? ['gap', 'bgap', '6', '4', '7'] @@ -265,6 +266,7 @@ for (const tool of ['bins', 'plates']) { return write.apply(this, arguments); }; }); + await H.setField(page, 'drawerW', '410'); if (tool === 'bins') await H.setField(page, field, refused); else await page.selectOption('#' + field, refused); await expect(page.locator('#drawerName')).toHaveText('not saving · Kitchen'); @@ -284,9 +286,10 @@ for (const tool of ['bins', 'plates']) { await ready(page); await expect(page.locator('#drawerName')).toHaveText('Kitchen'); await expect(page.locator('#' + field)).toHaveValue(refused); + await expect(page.locator('#drawerW')).toHaveValue('410'); await expect(page.locator('#setAsideMsg')).toHaveText('The layout you had here is set aside.'); await settle(page); - expect((await stored(page)).Kitchen[key], 'the drawer takes it now').toBe(refused); + expect((await stored(page)).Kitchen, 'the drawer takes it now').toMatchObject({ [key]: refused, w: '410' }); await page.click('#putBack'); await expect.poll(() => page.inputValue('#' + field).catch(() => ''), { message: 'and Put back brings the later change', timeout: 20000 }).toBe(raced); @@ -429,6 +432,119 @@ test('with storage full, a size changed on the other page outlives the save Bins expect(errors).toEqual([]); }); +/* With the drawer's saves refused, a size changed on one page goes to the other in the + address alone, and the drawer still has the size from before. The page at the other + end caught up with the drawer on the way in, as it does when another tab has moved the + drawer on, and the size went back. Here nothing has moved the drawer on: it has both + halves as the page that handed over last saved them. */ +for (const tool of ['bins', 'plates']) { + test(`with storage full, a size changed on ${tool} is the size on the other page`, async ({ page }) => { + await page.addInitScript(fullStorage); + const errors = await openPlates(page); + await H.setField(page, 'drawerW', '400'); + await saveAs(page, 'Kitchen'); + // there and back first, so each page's own save already has the keys a trip brings + await toBins(page); + await toPlates(page); + if (tool === 'bins') await toBins(page); + await settle(page); + await page.evaluate(() => sessionStorage.setItem('full', '1')); + await H.setField(page, 'drawerW', '410'); // the same length, so the page's own save fits + await expect(page.locator('#drawerName')).toHaveText('not saving · Kitchen'); + if (tool === 'bins') await toPlates(page); else await toBins(page); + expect(await page.inputValue('#drawerW'), 'on the other page').toBe('410'); + // reloaded there, and shown again from the back-forward cache: the drawer has not moved on + await page.reload(); + await (tool === 'bins' ? platesReady : binsReady)(page); + expect(await page.inputValue('#drawerW'), 'reloaded').toBe('410'); + const stayed = await page.evaluate(() => { + dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true })); + return !!(history.state && history.state.drawerforge); // catching up clears it to reload + }); + expect(stayed, 'shown again from the cache, it stays').toBe(true); + if (tool === 'bins') await toBins(page); else await toPlates(page); + expect(await page.inputValue('#drawerW'), 'and back').toBe('410'); + await expect(page.locator('#setAside')).toBeHidden(); + // and Back to the other page, a page of its own come back + await page.goBack(); + await (tool === 'bins' ? platesReady : binsReady)(page); + expect(await page.inputValue('#drawerW'), 'Back on the other page').toBe('410'); + /* The size is still to be saved there. With room again, the next change saves it into + the drawer: counted from the size the page arrived with, the save kept the drawer's. */ + await page.evaluate(() => sessionStorage.setItem('full', '0')); + if (tool === 'bins') await page.selectOption('#connector', 'hclip'); + else await H.setField(page, 'gap', '4'); + await expect.poll(() => stored(page).then((s) => s.Kitchen), + { message: 'the drawer has the size', timeout: 20000 }) + .toMatchObject(tool === 'bins' ? { w: '410', cn: 'hclip' } : { w: '410', bgap: '4' }); + await expect(page.locator('#drawerName')).toHaveText('Kitchen'); + expect(errors).toEqual([]); + }); +} + +/* So it is on the page that made the change, reloaded, when that page's tool alone has + saved into the drawer. With no mark of the other page's in it, the drawer was taken to + have moved on, and the size went back. */ +for (const tool of ['bins', 'plates']) { + test(`with storage full, a size changed on ${tool} is still there after a reload, ` + + `in a drawer only ${tool} has saved into`, async ({ page }) => { + const ready = tool === 'bins' ? binsReady : platesReady; + await page.addInitScript(fullStorage); + const errors = []; + page.on('pageerror', (e) => errors.push(String(e))); + await page.goto(base + (tool === 'bins' ? 'bins/' : '')); + await ready(page); + await H.setField(page, 'drawerW', '400'); + await saveAs(page, 'Kitchen'); + await settle(page); + expect(await page.evaluate(() => JSON.parse(localStorage.getItem('drawerforge:drawers:v1')) + .drawers.map((d) => Object.keys(d.marks).join()))).toEqual([tool]); + await page.evaluate(() => sessionStorage.setItem('full', '1')); + await H.setField(page, 'drawerW', '410'); + await expect(page.locator('#drawerName')).toHaveText('not saving · Kitchen'); + await settle(page); + await page.reload(); + await ready(page); + await settle(page); + expect(await page.inputValue('#drawerW'), 'reloaded').toBe('410'); + await expect(page.locator('#drawerName')).toHaveText('not saving · Kitchen'); + expect(errors).toEqual([]); + }); +} + +/* A layout set aside with the storage full, where the layout fits and the record of whether + it is a link's does not: the record of the layout set aside before was left beside it, + to say so for the wrong layout. Here that one is planted: a long layout, so the next + fits in its place, with a short record, so the next does not. */ +test('with storage full, a layout set aside is not given the record of the one before', + async ({ page }) => { + await page.addInitScript(fullStorage); + const errors = []; + page.on('pageerror', (e) => errors.push(String(e))); + const KEY = 'drawerforge:bins:v1'; + await page.goto(base + 'bins/#w=444&d=444&bl=0-0-1-1-3'); // someone's link + await binsReady(page); + await H.setField(page, 'gap', '6'); // changed, still their drawer + await settle(page); + const edited = await page.evaluate((k) => localStorage.getItem(k), KEY); + expect(edited).toContain('bgap=6'); + await page.evaluate((k) => { + localStorage.setItem(k + ':prev', 'v=2&' + 'x'.repeat(4000)); + localStorage.setItem(k + ':prev:linked', 'v=2&w=300'); + sessionStorage.setItem('full', '1'); + }, KEY); + + await page.goto('about:blank'); + await page.goto(base + 'bins/#w=555&bl=2-2-1-1-3'); // a second link + await binsReady(page); + await expect(page.locator('#putBack')).toBeVisible(); + const kept = await page.evaluate((k) => [localStorage.getItem(k + ':prev'), + localStorage.getItem(k + ':prev:linked')], KEY); + expect(kept[0], 'the changed link set aside').toBe(edited); + expect(kept[1], 'and not with the record before it').toBeNull(); + expect(errors).toEqual([]); + }); + /* The same reload with no save landing. The page is your own drawer handed over, and the reload is that page again. Onto a layout another drawer holds, it used to say someone's link had replaced your layout, set that aside, and count the drawer's settings as the @@ -870,6 +986,717 @@ for (const tool of ['plates', 'bins']) { }); } +// a change to a page's own half alone: the field, the value it is changed to, and its key +const ownChange = (tool) => (tool === 'bins' ? ['gap', '4', 'bgap'] : ['connector', 'hclip', 'cn']); +// and a second, no longer, so the page's own save of it still fits with the storage full +const ownChange2 = (tool) => (tool === 'bins' ? '5' : 'snap'); +async function changeOwn(page, tool, to) { + const [field, v] = ownChange(tool); + if (tool === 'bins') await H.setField(page, field, to || v); + else await page.selectOption('#' + field, to || v); +} +// Kitchen at 400, with both pages' marks in it, open in this tab on `tool` +async function kitchenOn(page, tool) { + const errors = await openPlates(page); + await H.setField(page, 'drawerW', '400'); + await saveAs(page, 'Kitchen'); + await toBins(page); + await toPlates(page); + if (tool === 'bins') await toBins(page); + await settle(page); + return errors; +} +// another tab of `tool`, on Kitchen, makes `change` to it +async function inOtherTab(context, tool, errors, change) { + const other = await context.newPage(); + other.on('pageerror', (e) => errors.push(String(e))); + await other.goto(base + (tool === 'bins' ? 'bins/' : '')); + await (tool === 'bins' ? binsReady : platesReady)(other); + await expect(other.locator('#drawerName')).toHaveText('Kitchen'); + await change(other); + await settle(other); + await other.close(); +} +// moves its size to 420, and changes that page's own half too +async function moveKitchen(context, tool, errors, own) { + await inOtherTab(context, tool, errors, async (other) => { + await H.setField(other, 'drawerW', '420'); + if (own) await changeOwn(other, tool); + }); +} +// with the storage full from here on, the page's size changed to 410, which the drawer refuses +async function refuseSize(page) { + await page.evaluate(() => sessionStorage.setItem('full', '1')); + await H.setField(page, 'drawerW', '410'); + await expect(page.locator('#drawerName')).toHaveText('not saving · Kitchen'); + await settle(page); +} + +/* And when the first tab saves a change of its own before it comes back. Its save keeps the + other tab's size, which it never changed (see mergeDesign in drawers.js), and sets its + mark all the same, so the drawer had the marks the first tab last knew. Taken for a size + the drawer had refused, the old size stayed: on the page, in its downloads and in what it + handed over. Reloaded, and shown again from the back-forward cache. */ +for (const tool of ['plates', 'bins']) for (const how of ['reloaded', 'shown again from the cache']) { + test(`a ${tool} tab that saves after another tab moved its drawer on catches up, ${how}`, + async ({ page, context }) => { + const ready = tool === 'plates' ? platesReady : binsReady; + const errors = await kitchenOn(page, tool); + await moveKitchen(context, tool, errors, false); + expect(await page.inputValue('#drawerW')).toBe('400'); + await changeOwn(page, tool); + const [field, v, key] = ownChange(tool); + await expect.poll(() => stored(page).then((s) => s.Kitchen), + { message: 'its change is saved, beside the other tab\'s size', timeout: 20000 }) + .toMatchObject({ w: '420', [key]: v }); + + if (how === 'reloaded') await page.reload(); + else await page.evaluate(() => dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true }))); + await expect.poll(() => page.inputValue('#drawerW').catch(() => ''), + { message: 'caught up with the other tab', timeout: 20000 }).toBe('420'); + await ready(page); + await expect(page.locator('#drawerName')).toHaveText('Kitchen'); + expect(await page.inputValue('#' + field), 'with its own change').toBe(v); + await settle(page); + expect((await stored(page)).Kitchen).toMatchObject({ w: '420', [key]: v }); + expect(errors).toEqual([]); + }); +} + +/* A hand-over onto a drawer whose other half another tab has moved on, with its size: the + page there takes that half from the drawer (restore, in drawers.js), reloading with the + drawer's mark for it, and the drawer then had the marks that reload knew. Taken for a + size the drawer had refused, the old size stayed, handed over and reloaded. */ +for (const tool of ['plates', 'bins']) { + test(`a hand-over from ${tool} that takes the other page's half from the drawer catches up its size`, + async ({ page, context }) => { + const there = tool === 'plates' ? 'bins' : 'plates'; + const ready = there === 'plates' ? platesReady : binsReady; + const errors = await kitchenOn(page, tool); + await moveKitchen(context, there, errors, true); + expect(await page.inputValue('#drawerW')).toBe('400'); + await page.click(there === 'bins' ? '#navBins' : '#navPlates'); + const [field, v] = ownChange(there); + for (const step of ['handed over', 'reloaded']) { + if (step === 'reloaded') await page.reload(); + await expect.poll(() => page.inputValue('#drawerW').catch(() => ''), + { message: step, timeout: 20000 }).toBe('420'); + await ready(page); + expect(await page.inputValue('#' + field), `${step}, with the other tab's change there`).toBe(v); + await expect(page.locator('#drawerName')).toHaveText('Kitchen'); + await settle(page); + } + expect(errors).toEqual([]); + }); +} + +/* As above, with the storage full by the time the first tab comes back: its save that went + through kept the other tab's size, and a change after it was refused, so the address is + the one copy of that change. Counted from the drawer's settings, which the page took for + its own when it came back, the change took in the old size the page still had, and once + there was room it wrote that over the other tab's. It is counted from what the page last + saved, and the size the other tab moved on since is caught up: reloaded, and handed over, + then the change taken back to the first page. */ +for (const tool of ['plates', 'bins']) for (const how of ['reloaded', 'handed over']) { + test(`a ${tool} tab whose save kept another tab's size, then had a change refused, catches up, ${how}`, + async ({ page, context }) => { + const there = tool === 'plates' ? 'bins' : 'plates'; + const now = how === 'reloaded' ? tool : there; + const [field, v, key] = ownChange(tool); + await page.addInitScript(fullStorage); + const errors = await kitchenOn(page, tool); + await moveKitchen(context, tool, errors, false); + await changeOwn(page, tool); + await expect.poll(() => stored(page).then((s) => s.Kitchen), + { message: 'its change is saved, beside the other tab\'s size', timeout: 20000 }) + .toMatchObject({ w: '420', [key]: v }); + await page.evaluate(() => sessionStorage.setItem('full', '1')); + await changeOwn(page, tool, ownChange2(tool)); + await expect(page.locator('#drawerName')).toHaveText('not saving · Kitchen'); + await settle(page); + + if (how === 'reloaded') await page.reload(); + else await page.click(there === 'bins' ? '#navBins' : '#navPlates'); + await expect.poll(() => page.inputValue('#drawerW').catch(() => ''), + { message: 'caught up with the other tab', timeout: 20000 }).toBe('420'); + await (now === 'bins' ? binsReady : platesReady)(page); + if (how === 'reloaded') { + expect(await page.inputValue('#' + field), 'with the change').toBe(ownChange2(tool)); + } + await settle(page); + // with room again, the next change saves into the drawer, and keeps the other tab's size + await page.evaluate(() => sessionStorage.setItem('full', '0')); + const [, first, nowKey] = ownChange(now); + const next = now !== tool ? first : tool === 'bins' ? '6' : 'bowtie'; + await changeOwn(page, now, next); + await expect.poll(() => stored(page).then((s) => s.Kitchen), + { message: 'the next change is saved', timeout: 20000 }).toMatchObject({ [nowKey]: next }); + expect((await stored(page)).Kitchen.w, 'the other tab\'s size').toBe('420'); + await expect(page.locator('#drawerName')).toHaveText('Kitchen'); + if (how === 'handed over') { + await (tool === 'bins' ? toBins : toPlates)(page); + expect(await page.inputValue('#' + field), 'the change, back where it was made').toBe(ownChange2(tool)); + await expect.poll(() => stored(page).then((s) => s.Kitchen), + { message: 'and saved there', timeout: 20000 }).toMatchObject({ w: '420', [key]: ownChange2(tool) }); + } + expect(errors).toEqual([]); + }); +} + +/* With the storage full, a size changed and refused, then another tab on the other page + changes the depth, and the page comes back, reloaded or from the back-forward cache. It + catches up the depth and keeps the size, still to be saved. Reloaded, the catch-up was + counted from the design, so the size was taken for the drawer's and went back; from the + cache, the reload it took lost that the size was refused, and the next save kept the + drawer's old one. */ +for (const tool of ['plates', 'bins']) for (const how of ['reloaded', 'shown again from the cache']) { + test(`with storage full, a size changed on ${tool} outlives catching up another tab's depth, ${how}`, + async ({ page, context }) => { + const there = tool === 'plates' ? 'bins' : 'plates'; + await page.addInitScript(fullStorage); + const errors = await kitchenOn(page, tool); + await refuseSize(page); + await inOtherTab(context, there, errors, (other) => H.setField(other, 'drawerD', '555')); + + if (how === 'reloaded') await page.reload(); + else await page.evaluate(() => dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true }))); + await expect.poll(() => page.inputValue('#drawerD').catch(() => ''), + { message: 'caught up with the other tab', timeout: 20000 }).toBe('555'); + await (tool === 'bins' ? binsReady : platesReady)(page); + expect(await page.inputValue('#drawerW'), 'with the size changed').toBe('410'); + await settle(page); + await page.evaluate(() => sessionStorage.setItem('full', '0')); + await changeOwn(page, tool); + const [, v, key] = ownChange(tool); + await expect.poll(() => stored(page).then((s) => s.Kitchen), + { message: 'with room again, the next change saves the size too', timeout: 20000 }) + .toMatchObject({ w: '410', d: '555', [key]: v }); + await expect(page.locator('#drawerName')).toHaveText('Kitchen'); + expect(errors).toEqual([]); + }); +} + +/* And handed over, onto a page whose own half another tab has moved on, and nothing else: + the page there takes that half from the drawer (restore), and the reload that takes it + lost that the size was refused, so the drawer's older size came back over it. */ +for (const tool of ['plates', 'bins']) { + test(`with storage full, a size changed on ${tool} is the size on the other page as it takes its half ` + + 'from the drawer', async ({ page, context }) => { + const there = tool === 'plates' ? 'bins' : 'plates'; + const [field, v, key] = ownChange(there); + await page.addInitScript(fullStorage); + const errors = await kitchenOn(page, tool); + await inOtherTab(context, there, errors, (other) => changeOwn(other, there)); + await refuseSize(page); + await page.click(there === 'bins' ? '#navBins' : '#navPlates'); + for (const step of ['handed over', 'reloaded']) { + if (step === 'reloaded') await page.reload(); + await expect.poll(() => page.inputValue('#' + field).catch(() => ''), + { message: `${step}, with the other tab's change`, timeout: 20000 }).toBe(v); + await (there === 'bins' ? binsReady : platesReady)(page); + expect(await page.inputValue('#drawerW'), step).toBe('410'); + await settle(page); + } + await page.evaluate(() => sessionStorage.setItem('full', '0')); + await changeOwn(page, there, ownChange2(there)); + await expect.poll(() => stored(page).then((s) => s.Kitchen), + { message: 'with room again, the next change saves the size too', timeout: 20000 }) + .toMatchObject({ w: '410', [key]: ownChange2(there) }); + await expect(page.locator('#drawerName')).toHaveText('Kitchen'); + expect(errors).toEqual([]); + }); +} + +/* A refused size handed over is saved on the other page once there is room, and then set + back there, before Back to the page that made it. That page's address still says the + size was refused, counted from the size the drawer has again, so it took the size for a + change still to save, and its first save wrote it over the one set back, with nothing + done on it. The refusal has landed since, so the page is a page of yours come back, and + catches up with the drawer. The room comes, and the size is saved: + - on the other page, by setting it back; + - there, by a change of that page's own, before it is set back; + - as the other page arrives, by the save it makes then; + - before the hand-over, by the save this page makes as it leaves, after which its + address's mark no longer says the size was refused. That one passes with no ids at + all, and is here to keep it so. */ +for (const tool of ['plates', 'bins']) { + for (const [room, saved] of [['set back', 'there as it is set back'], + ['a change first', 'there by a change first'], ['arriving', 'there as that page arrives'], + ['before the hand-over', 'here as it leaves for that page']]) { + test(`Back to a ${tool} page whose refused size was saved, then set back on the other page, ` + + `is the size set back, saved ${saved}`, async ({ page }) => { + const there = tool === 'plates' ? 'bins' : 'plates'; + await page.addInitScript(fullStorage); + // room from the next page's first line, before it saves on arriving + await page.addInitScript(() => { + if (sessionStorage.getItem('roomNext') !== '1') return; + sessionStorage.removeItem('roomNext'); + sessionStorage.setItem('full', '0'); + }); + const errors = await kitchenOn(page, tool); + await refuseSize(page); + if (room === 'before the hand-over') await page.evaluate(() => sessionStorage.setItem('full', '0')); + if (room === 'arriving') await page.evaluate(() => sessionStorage.setItem('roomNext', '1')); + await page.click(there === 'bins' ? '#navBins' : '#navPlates'); + await (there === 'bins' ? binsReady : platesReady)(page); + expect(await page.inputValue('#drawerW'), 'handed over').toBe('410'); + await page.evaluate(() => sessionStorage.setItem('full', '0')); + if (room === 'a change first') await changeOwn(page, there); + if (room !== 'set back') { + await expect.poll(() => stored(page).then((s) => s.Kitchen.w), + { message: 'the size saved', timeout: 20000 }).toBe('410'); + } + await H.setField(page, 'drawerW', '400'); + await expect.poll(() => stored(page).then((s) => s.Kitchen.w), + { message: 'set back there', timeout: 20000 }).toBe('400'); + await settle(page); + + await page.goBack(); + await expect.poll(() => page.inputValue('#drawerW').catch(() => ''), + { message: 'Back, caught up', timeout: 20000 }).toBe('400'); + await (tool === 'bins' ? binsReady : platesReady)(page); + await settle(page); + expect((await stored(page)).Kitchen.w, 'the size set back stays').toBe('400'); + await expect(page.locator('#drawerName')).toHaveText('Kitchen'); + expect(errors).toEqual([]); + }); + } +} + +/* A catch-up for a size the page already has: another tab set the size this page holds + refused. Nothing on the page changes, so it is not reloaded, and the size is the + drawer's from then on, not a change still to save. */ +for (const tool of ['plates', 'bins']) { + test(`a ${tool} page holding a refused size another tab has saved since is not reloaded to catch up`, + async ({ page, context }) => { + const there = tool === 'plates' ? 'bins' : 'plates'; + await page.addInitScript(fullStorage); + const errors = await kitchenOn(page, tool); + await refuseSize(page); + await inOtherTab(context, there, errors, (other) => H.setField(other, 'drawerW', '410')); + const stayed = await page.evaluate(() => { + window.notReloaded = true; + dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true })); + return !!(history.state && history.state.drawerforge); // catching up clears it to reload + }); + expect(stayed, 'shown again from the cache, it stays').toBe(true); + await settle(page); + expect(await page.evaluate(() => window.notReloaded === true), 'not reloaded').toBe(true); + await page.evaluate(() => sessionStorage.setItem('full', '0')); + await changeOwn(page, tool); + const [, v, key] = ownChange(tool); + await expect.poll(() => stored(page).then((s) => s.Kitchen), + { message: 'with room again, the next change saves', timeout: 20000 }) + .toMatchObject({ w: '410', [key]: v }); + expect(errors).toEqual([]); + }); +} + +/* And its address's mark says the size is the drawer's too. Left saying the size was + refused from the size before, a reload after another tab set the size back took the + page's size for its own change still to save, and wrote it over the one set back once + there was room. */ +for (const tool of ['plates', 'bins']) { + test(`a ${tool} page that caught up a refused size another tab saved, reloaded after that tab ` + + 'set it back, has the size set back', async ({ page, context }) => { + const there = tool === 'plates' ? 'bins' : 'plates'; + await page.addInitScript(fullStorage); + const errors = await kitchenOn(page, tool); + await refuseSize(page); + await inOtherTab(context, there, errors, (other) => H.setField(other, 'drawerW', '410')); + await page.evaluate(() => dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true }))); + await settle(page); + await inOtherTab(context, there, errors, (other) => H.setField(other, 'drawerW', '400')); + await page.evaluate(() => sessionStorage.setItem('full', '0')); + await page.reload(); + await expect.poll(() => page.inputValue('#drawerW').catch(() => ''), + { message: 'reloaded, caught up', timeout: 20000 }).toBe('400'); + await (tool === 'bins' ? binsReady : platesReady)(page); + await settle(page); + expect((await stored(page)).Kitchen.w, 'the size set back stays').toBe('400'); + expect(errors).toEqual([]); + }); +} + +/* Two pages, each holding a change the drawer refused: the size here, then the depth on + the other page it was handed over to. Back here, with room again, a change saves the + size. Forward to the other page still has its depth to save: that save had only this + page's change in it. With one id for the refusals of both pages, the save here counted + the depth as landed too, and Forward showed the drawer's depth. */ +for (const tool of ['plates', 'bins']) { + test(`Forward to the page a ${tool} page handed its refused size to keeps a depth refused there, ` + + 'after the size is saved on Back', async ({ page }) => { + const there = tool === 'plates' ? 'bins' : 'plates'; + const ready = (t) => (t === 'bins' ? binsReady : platesReady); + await page.addInitScript(fullStorage); + const errors = await kitchenOn(page, tool); + await refuseSize(page); + await page.click(there === 'bins' ? '#navBins' : '#navPlates'); + await ready(there)(page); + expect(await page.inputValue('#drawerW'), 'handed over').toBe('410'); + await H.setField(page, 'drawerD', '510'); + await expect(page.locator('#drawerName')).toHaveText('not saving · Kitchen'); + await settle(page); + + await page.goBack(); + await ready(tool)(page); + expect(await page.inputValue('#drawerW'), 'Back').toBe('410'); + await page.evaluate(() => sessionStorage.setItem('full', '0')); + await changeOwn(page, tool); + await expect.poll(() => stored(page).then((s) => s.Kitchen.w), + { message: 'the size saved here', timeout: 20000 }).toBe('410'); + await settle(page); + + await page.goForward(); + await ready(there)(page); + await settle(page); + expect(await page.inputValue('#drawerD'), 'the depth refused there').toBe('510'); + expect(await page.inputValue('#drawerW')).toBe('410'); + await changeOwn(page, there); + await expect.poll(() => stored(page).then((s) => s.Kitchen), + { message: 'saved with the next change', timeout: 20000 }).toMatchObject({ w: '410', d: '510' }); + expect(errors).toEqual([]); + }); +} + +/* And the size, saved on Back and then set back there, is not a change of the later page's. + That page's own save as it arrived was refused too, so it holds a refusal of its own, + still to save, with the size in what it arrived with. Counted from the first page's base, + the size stayed its change, and Forward to it wrote the size back over the one set back. */ +for (const tool of ['plates', 'bins']) { + test(`Forward to the page a ${tool} page handed its refused size to has the size set back on Back ` + + 'since', async ({ page }) => { + const there = tool === 'plates' ? 'bins' : 'plates'; + const ready = (t) => (t === 'bins' ? binsReady : platesReady); + await page.addInitScript(fullStorage); + const errors = await kitchenOn(page, tool); + await refuseSize(page); + await page.click(there === 'bins' ? '#navBins' : '#navPlates'); + await ready(there)(page); + expect(await page.inputValue('#drawerW'), 'handed over').toBe('410'); + await expect(page.locator('#drawerName')).toHaveText('not saving · Kitchen'); + await settle(page); // its save as it arrives, refused + + await page.goBack(); + await ready(tool)(page); + await page.evaluate(() => sessionStorage.setItem('full', '0')); + await changeOwn(page, tool); + await expect.poll(() => stored(page).then((s) => s.Kitchen.w), + { message: 'the size saved here', timeout: 20000 }).toBe('410'); + await H.setField(page, 'drawerW', '400'); + await expect.poll(() => stored(page).then((s) => s.Kitchen.w), + { message: 'and set back', timeout: 20000 }).toBe('400'); + await settle(page); + + await page.goForward(); + await expect.poll(() => page.inputValue('#drawerW').catch(() => ''), + { message: 'Forward, the size set back', timeout: 20000 }).toBe('400'); + await ready(there)(page); + await changeOwn(page, there); + const [, v, key] = ownChange(there); + await expect.poll(() => stored(page).then((s) => s.Kitchen), + { message: 'the next change keeps it', timeout: 20000 }).toMatchObject({ w: '400', [key]: v }); + expect(errors).toEqual([]); + }); +} + +/* A page holding a size the drawer refused, saved as another drawer, where a change is + refused and then saved. Back to the page that made the size, still Kitchen's, keeps the + size: it went into the other drawer, never Kitchen. The refusal in the other drawer + took the id of Kitchen's, and its landing counted Kitchen's size as saved, so Back showed + Kitchen's size from before. */ +for (const tool of ['plates', 'bins']) { + test(`Back to a ${tool} page whose refused size went on into another drawer keeps the size`, + async ({ page }) => { + const there = tool === 'plates' ? 'bins' : 'plates'; + const ready = (t) => (t === 'bins' ? binsReady : platesReady); + await page.addInitScript(fullStorage); + const errors = await kitchenOn(page, tool); + await refuseSize(page); + await page.click(there === 'bins' ? '#navBins' : '#navPlates'); + await ready(there)(page); + expect(await page.inputValue('#drawerW'), 'handed over').toBe('410'); + await settle(page); // its save as it arrives refused too, so the size never reaches Kitchen + await page.evaluate(() => sessionStorage.setItem('full', '0')); + await saveAs(page, 'Pantry'); + expect((await stored(page)).Kitchen.w, 'Kitchen as it was').toBe('400'); + await page.evaluate(() => sessionStorage.setItem('full', '1')); + await changeOwn(page, there); + await expect(page.locator('#drawerName')).toHaveText('not saving · Pantry'); + await settle(page); + await page.evaluate(() => sessionStorage.setItem('full', '0')); + await changeOwn(page, there, ownChange2(there)); + const [, , key] = ownChange(there); + await expect.poll(() => stored(page).then((s) => s.Pantry), + { message: 'saved into the other drawer', timeout: 20000 }).toMatchObject({ [key]: ownChange2(there) }); + await settle(page); + + await page.goBack(); + await ready(tool)(page); + await settle(page); + expect(await page.inputValue('#drawerW'), 'Back, the size kept').toBe('410'); + await changeOwn(page, tool); + await expect.poll(() => stored(page).then((s) => s.Kitchen.w), + { message: 'and saved into Kitchen, with room', timeout: 20000 }).toBe('410'); + expect(errors).toEqual([]); + }); +} + +/* A long run of hand-overs with the storage full, each page's save as it arrives refused, so + each holds a refusal of its own: more than the 32 ids a page keeps. The last page still + counts the first page's size as a change, and saves it with room. Set back there, Back to + the page before it, which holds the first id, has the size set back: the page that saved + held the ids after it, with its change. Counted from the first id it kept, the last page + took the size for none of its own, and with the first id still to land, Back to the page + before wrote the size over the one set back. */ +test('after more hand-overs than a page keeps ids for, a refused size is saved, and stays set back', + async ({ page }) => { + test.setTimeout(300000); + await page.addInitScript(fullStorage); + const errors = await kitchenOn(page, 'plates'); + await refuseSize(page); + let tool = 'plates'; + for (let i = 0; i < 33; i += 1) { + tool = tool === 'plates' ? 'bins' : 'plates'; + await page.click(tool === 'bins' ? '#navBins' : '#navPlates'); + await (tool === 'bins' ? binsReady : platesReady)(page); + await expect(page.locator('#drawerName'), 'its save refused').toHaveText('not saving · Kitchen'); + } + expect(await page.inputValue('#drawerW')).toBe('410'); + await page.evaluate(() => sessionStorage.setItem('full', '0')); + await changeOwn(page, tool); + await expect.poll(() => stored(page).then((s) => s.Kitchen.w), + { message: 'the size saved, with room', timeout: 20000 }).toBe('410'); + await H.setField(page, 'drawerW', '400'); + await expect.poll(() => stored(page).then((s) => s.Kitchen.w), + { message: 'and set back', timeout: 20000 }).toBe('400'); + await settle(page); + + const before = tool === 'plates' ? 'bins' : 'plates'; + await page.goBack(); + await expect.poll(() => page.inputValue('#drawerW').catch(() => ''), + { message: 'Back, the size set back', timeout: 20000 }).toBe('400'); + await (before === 'bins' ? binsReady : platesReady)(page); + await changeOwn(page, before); + const [, v, key] = ownChange(before); + await expect.poll(() => stored(page).then((s) => s.Kitchen), + { message: 'the next change keeps it', timeout: 20000 }).toMatchObject({ w: '400', [key]: v }); + expect(errors).toEqual([]); + }); + +/* The refusals' ids are only what the page makes, however a record or the tab's note has + them. A mark whose ids are not, landed in the tab's note as they are, is a refused size + still to save, and so after the page's own refused save, reloaded again, with none of + those ids, a long one among them, in its mark since. So is one whose bases are not lists, + with far more ids landed than the tab keeps. No error, and with room the size is saved, + and the tab keeps the last 128 landed. */ +test('a refused size outlives refusal ids and bases that are not what the page writes', async ({ page }) => { + await page.addInitScript(fullStorage); + const errors = await kitchenOn(page, 'plates'); + await refuseSize(page); + const reloaded = async (why) => { + await page.reload(); + await platesReady(page); + await settle(page); + expect(await page.inputValue('#drawerW'), why).toBe('410'); + await expect(page.locator('#drawerName')).toHaveText('not saving · Kitchen'); + }; + const spoil = (bad) => page.evaluate((bad) => { + const st = history.state.drawerforge; + const K = 'drawerforge:drawers:tab'; + const n = JSON.parse(sessionStorage.getItem(K) || '{}'); + if (bad === 'ids') { + const rids = ['Zz', '__proto__', 5, null, 'z'.repeat(1000000)]; + history.replaceState({ drawerforge: { ...st, rids, bases: 'x' } }, ''); + n.landed = ['Zz', '__proto__', '5', 'null']; + } else { + history.replaceState({ drawerforge: { ...st, bases: [{}, 'x', [[1, 2]]] } }, ''); + n.landed = Array.from({ length: 100000 }, (_, i) => 'z' + i); + } + sessionStorage.setItem(K, JSON.stringify(n)); + }, bad); + await spoil('ids'); + await reloaded('ids that are not'); + await reloaded('and again, after its own save refused'); + expect(await page.evaluate(() => JSON.stringify(history.state).length), 'its mark').toBeLessThan(10000); + await spoil('bases'); + await reloaded('bases that are not'); + await page.evaluate(() => sessionStorage.setItem('full', '0')); + await changeOwn(page, 'plates'); + await expect.poll(() => stored(page).then((s) => s.Kitchen.w), + { message: 'saved, with room', timeout: 20000 }).toBe('410'); + const landed = await page.evaluate(() => JSON.parse(sessionStorage.getItem('drawerforge:drawers:tab')).landed); + expect(landed, 'the last 128 landed').toHaveLength(128); + expect(errors).toEqual([]); +}); + +/* Back from the back-forward cache, for real: the page does not load again, and only its + pageshow sees the return. The browser the tests are given has the cache turned off, and + the headless shell it runs keeps nothing in it, so these launch the full Chromium build + with the cache on. `run` gets a page in it, which counts each return from the cache. */ +async function withCache(playwright, launchOptions, run) { + const opts = { ...launchOptions, ignoreDefaultArgs: ['--disable-back-forward-cache'] }; + if (!opts.executablePath) opts.channel = 'chromium'; + const browser = await playwright.chromium.launch(opts); + try { + const context = await browser.newContext({ serviceWorkers: 'block', + viewport: { width: 1440, height: 1000 } }); + const page = await context.newPage(); + await page.addInitScript(() => addEventListener('pageshow', (e) => { + if (!e.persisted) return; + sessionStorage.setItem('cached', String(Number(sessionStorage.getItem('cached') || 0) + 1)); + })); + await run(page); + } finally { + await browser.close(); + } +} +// Back from the cache, or Forward: by the page's own history, as a return from it fires no load +async function backFromCache(page, forward) { + const count = () => page.evaluate(() => Number(sessionStorage.getItem('cached') || 0)).catch(() => -1); + const was = await count(); + await page.evaluate((f) => (f ? history.forward() : history.back()), !!forward); + await expect.poll(count, { message: 'shown again from the cache', timeout: 20000 }).toBe(was + 1); +} + +/* The size refused here is saved on the other page and set back there, as in the tests + above, and the page comes Back from the cache. Its refusal has landed since, so it is a + page of yours come back and catches up with the drawer. It took the size for a change of + its own still to save, and saved it over the one set back at its next change. */ +for (const tool of ['plates', 'bins']) { + test(`Back from the cache to a ${tool} page whose refused size was saved, then set back on the ` + + 'other page, is the size set back', async ({ playwright, launchOptions }) => { + await withCache(playwright, launchOptions, async (page) => { + const there = tool === 'plates' ? 'bins' : 'plates'; + await page.addInitScript(fullStorage); + const errors = await kitchenOn(page, tool); + await refuseSize(page); + await page.click(there === 'bins' ? '#navBins' : '#navPlates'); + await (there === 'bins' ? binsReady : platesReady)(page); + expect(await page.inputValue('#drawerW'), 'handed over').toBe('410'); + await page.evaluate(() => sessionStorage.setItem('full', '0')); + await H.setField(page, 'drawerW', '400'); + await expect.poll(() => stored(page).then((s) => s.Kitchen.w), + { message: 'saved there, set back', timeout: 20000 }).toBe('400'); + await settle(page); + + await backFromCache(page); + await expect.poll(() => page.inputValue('#drawerW').catch(() => ''), + { message: 'Back, caught up', timeout: 20000 }).toBe('400'); + await (tool === 'bins' ? binsReady : platesReady)(page); + await changeOwn(page, tool); + const [, v, key] = ownChange(tool); + await expect.poll(() => stored(page).then((s) => s.Kitchen), + { message: 'the next change keeps the size set back', timeout: 20000 }) + .toMatchObject({ w: '400', [key]: v }); + await expect(page.locator('#drawerName')).toHaveText('Kitchen'); + expect(errors).toEqual([]); + }); + }); +} + +/* And when a change to the page's own half was refused with the size. The other page + saves the size, not that change, so the page come Back from the cache still says it is + not saving into the drawer, until its next change saves it. It said the drawer had its + changes, while the drawer had its own half from before. */ +for (const tool of ['plates', 'bins']) { + test(`Back from the cache to a ${tool} page whose refused size was saved on the other page, but not ` + + 'its own refused change, still says it is not saving', async ({ playwright, launchOptions }) => { + await withCache(playwright, launchOptions, async (page) => { + const there = tool === 'plates' ? 'bins' : 'plates'; + const [field, v, key] = ownChange(tool); + await page.addInitScript(fullStorage); + const errors = await kitchenOn(page, tool); + const was = (await stored(page)).Kitchen[key]; + await page.evaluate(() => sessionStorage.setItem('full', '1')); + await changeOwn(page, tool); + await refuseSize(page); + await page.click(there === 'bins' ? '#navBins' : '#navPlates'); + await (there === 'bins' ? binsReady : platesReady)(page); + await page.evaluate(() => sessionStorage.setItem('full', '0')); + await changeOwn(page, there); + await expect.poll(() => stored(page).then((s) => s.Kitchen.w), + { message: 'the size saved there', timeout: 20000 }).toBe('410'); + await settle(page); + + await backFromCache(page); + await settle(page); + await expect(page.locator('#drawerName')).toHaveText('not saving · Kitchen'); + expect(await page.inputValue('#' + field), 'its own change').toBe(v); + expect((await stored(page)).Kitchen[key], 'not in the drawer').toBe(was); + await H.setField(page, 'drawerD', '420'); + await expect.poll(() => stored(page).then((s) => s.Kitchen), + { message: 'saved with the next change', timeout: 20000 }) + .toMatchObject({ w: '410', d: '420', [key]: v }); + await expect(page.locator('#drawerName')).toHaveText('Kitchen'); + expect(errors).toEqual([]); + }); + }); +} + +/* A refusal made after the page came back from the cache is another, with an id of its own, + counted from the page as it came back: its records so far went on with the hand-over, and + the other page holds them. Under the id that page held, its save counted this page's later + size as saved, and Back to it caught up with that page's. And with the first id landed, + counted from that one's base, the size had moved on since, and was caught up the same. */ +for (const tool of ['plates', 'bins']) { + test(`Back from the cache to a ${tool} page keeps a size refused after the cache gave it back, ` + + 'once the other page saves the one before', async ({ playwright, launchOptions }) => { + await withCache(playwright, launchOptions, async (page) => { + const there = tool === 'plates' ? 'bins' : 'plates'; + await page.addInitScript(fullStorage); + const errors = await kitchenOn(page, tool); + await refuseSize(page); + await page.click(there === 'bins' ? '#navBins' : '#navPlates'); + await (there === 'bins' ? binsReady : platesReady)(page); + await expect(page.locator('#drawerName')).toHaveText('not saving · Kitchen'); + await settle(page); + + await backFromCache(page); + await H.setField(page, 'drawerW', '420'); + await expect(page.locator('#drawerName')).toHaveText('not saving · Kitchen'); + await settle(page); + await backFromCache(page, true); + await page.evaluate(() => sessionStorage.setItem('full', '0')); + await changeOwn(page, there); + await expect.poll(() => stored(page).then((s) => s.Kitchen.w), + { message: 'the size saved there', timeout: 20000 }).toBe('410'); + await settle(page); + + await backFromCache(page); + await settle(page); + expect(await page.inputValue('#drawerW'), 'the size refused here').toBe('420'); + await changeOwn(page, tool); + await expect.poll(() => stored(page).then((s) => s.Kitchen.w), + { message: 'saved with the next change', timeout: 20000 }).toBe('420'); + expect(errors).toEqual([]); + }); + }); +} + +/* And from the cache after its drawer was deleted on the other page: it is not saved, and + the bar says so, as it does loaded. It still named the drawer. */ +for (const tool of ['plates', 'bins']) { + test(`Back from the cache to a ${tool} page whose drawer was deleted on the other page says it is ` + + 'not saved', async ({ playwright, launchOptions }) => { + await withCache(playwright, launchOptions, async (page) => { + const there = tool === 'plates' ? 'bins' : 'plates'; + const errors = await kitchenOn(page, tool); + await page.click(there === 'bins' ? '#navBins' : '#navPlates'); + await (there === 'bins' ? binsReady : platesReady)(page); + await openDialog(page); + await page.getByRole('button', { name: 'Delete Kitchen', exact: true }).click(); + await page.getByRole('button', { name: 'Really delete? Kitchen', exact: true }).click(); + await closeDialog(page); + await expect(page.locator('#drawerName')).toHaveText('not saved'); + + await backFromCache(page); + await expect(page.locator('#drawerName')).toHaveText('not saved'); + expect(errors).toEqual([]); + }); + }); +} + /* Each page saves its whole half of the drawer, so one whose half is older than the drawer's would write it back: a reload of a tab after another tab of the same tool changed the drawer, or Back to a page of yours that a later page has moved on. Both diff --git a/test/ui/hostile-links.spec.js b/test/ui/hostile-links.spec.js index 4be1890..b02ec6f 100644 --- a/test/ui/hostile-links.spec.js +++ b/test/ui/hostile-links.spec.js @@ -29,6 +29,14 @@ const platesUrl = () => site.base; const binsUrl = () => site.base + 'bins/'; const settle = (page) => page.waitForTimeout(900); // past the 400 ms save debounce +/* Until the page's save has landed: no edit still waiting to be read in (the bins page's + fields are read in a moment after they change, `timer`), and this browser's save is the + design on the page. Going on to another address drops a save still waiting (see + dropSave), and a fixed wait for it was now and then too short for a page still drawing. */ +const saved = (page) => expect.poll(() => page.evaluate(() => + (typeof timer === 'undefined' || timer === null) && + localStorage.getItem(SAVE_KEY) === encodeDesc(descriptor())), { message: 'the page has saved' }) + .toBe(true); const PLATES = 'drawerforge:plates:v1'; const BINS = 'drawerforge:bins:v1'; @@ -127,7 +135,7 @@ test('following a link puts the layout it replaced aside, with a way back', async ({ page }) => { await H.openPlates(page, platesUrl()); await H.setField(page, 'drawerW', '512'); - await settle(page); + await saved(page); await arrive(page, platesUrl() + '#w=333'); expect(await page.inputValue('#drawerW')).toBe('333'); // the link still wins @@ -141,7 +149,7 @@ test('following a link puts the layout it replaced aside, with a way back', test('a save nobody has touched is not offered back', async ({ page }) => { await H.openPlates(page, platesUrl()); - await settle(page); // the defaults are saved + await saved(page); // the defaults are saved await arrive(page, platesUrl() + '#w=333'); await expect(page.locator('#setAside')).toBeHidden(); expect(await stored(page, PLATES + ':prev')).toBeNull(); @@ -205,7 +213,7 @@ test('a saved layout that did not finish loading is still declined after a reloa test('a second link does not push your own layout out of the backup', async ({ page }) => { await H.openPlates(page, platesUrl()); await H.setField(page, 'drawerW', '512'); - await settle(page); + await saved(page); await arrive(page, platesUrl() + '#w=333'); await arrive(page, platesUrl() + '#w=444'); await expect(page.locator('#putBack')).toBeVisible(); @@ -220,13 +228,13 @@ test('a second link does not push your own layout out of the backup', async ({ p test('changing a linked layout takes the offer to put yours back away', async ({ page }) => { await H.openPlates(page, platesUrl()); await H.setField(page, 'drawerW', '512'); - await settle(page); + await saved(page); await arrive(page, platesUrl() + '#w=333'); await expect(page.locator('#setAside')).toBeVisible(); await page.waitForTimeout(600); // the boot's own save is no edit await expect(page.locator('#setAside')).toBeVisible(); await H.setField(page, 'drawerW', '340'); - await settle(page); + await saved(page); await expect(page.locator('#setAside')).toBeHidden(); // and that edited layout is yours now: the next link sets it aside await arrive(page, platesUrl() + '#w=444'); @@ -480,7 +488,7 @@ test('bed, infill and gap survive a trip through baseplates and back', async ({ await H.openBins(page, binsUrl()); const want = [['bedW', '200'], ['bedD', '210'], ['bedH', '220'], ['infill', '35'], ['gap', '6']]; for (const [id, v] of want) await H.setField(page, id, v); - await settle(page); + await saved(page); // each page's own link, as the page means it await arrive(page, await page.evaluate(() => new URL(platesHref(), location.href).href)); @@ -520,7 +528,7 @@ test('following a link puts the bins it replaced aside, with a way back', async await H.openBins(page, binsUrl()); await H.dragCells(page, [0, 0], [1, 1]); await H.dragCells(page, [3, 3], [3, 3]); - await settle(page); + await saved(page); await arrive(page, binsUrl() + '#bl=0-0-1-1-3'); expect(await binsIn(page)).toBe(1); @@ -635,7 +643,7 @@ test("someone's bins link, edited, carried to baseplates still keeps your drawer '&bl=0-0-1-1-3'; await arrive(page, binsUrl() + '#' + theirs); await H.setField(page, 'gap', '6'); // changed, but still their drawer - await settle(page); + await saved(page); await arrive(page, binsUrl()); // and a reload does not make it yours await viaButton(page, '#navPlates', platesUrl()); @@ -674,7 +682,7 @@ for (const [id, value] of [['infill', '20'], ['bedH', '200'], ['drawerD', '300'] test("an edited link put back is still the link's", async ({ page }) => { await theirBinsLink(page); await H.setField(page, 'gap', '6'); - await settle(page); + await saved(page); await arrive(page, binsUrl() + '#bl=2-2-1-1-3'); // sets the edited one aside await clickAndLoad(page, '#putBack'); expect(await page.inputValue('#gap')).toBe('6'); @@ -693,7 +701,7 @@ test("your own layout put back is not the link's, even in the same drawer", await viaButton(page, '#navBins', binsUrl()); await H.dragCells(page, [0, 0], [0, 0]); await H.setField(page, 'drawerW', '400'); - await settle(page); + await saved(page); const mine = await stored(page, BINS); await arrive(page, binsUrl() + '#' + mine.replace(/(^|&)bl=[^&]*/, '$1bl=2-2-1-1-3')); await clickAndLoad(page, '#putBack'); @@ -712,7 +720,7 @@ test("your own layout put back is not the link's, even in the same drawer", test("someone's drawer changed on baseplates comes back to bins as yours", async ({ page }) => { await H.openBins(page, binsUrl()); await H.dragCells(page, [0, 0], [1, 1]); - await settle(page); + await saved(page); const mine = await stored(page, BINS); await arrive(page, binsUrl() + '#w=333&bl=0-0-1-1-3'); await H.setField(page, 'gap', '6'); @@ -740,7 +748,7 @@ test("your own drawer on someone's link is not recorded as theirs", async ({ pag expect(theirs).toContain('bw=220'); await arrive(page, binsUrl()); await H.dragCells(page, [0, 0], [1, 1]); // your own bins - await settle(page); + await saved(page); const mine = await stored(page, BINS); await arrive(page, binsUrl() + '#' + theirs); @@ -752,7 +760,7 @@ test("your own drawer on someone's link is not recorded as theirs", async ({ pag await arrive(page, binsUrl()); await H.setField(page, 'drawerW', '600'); - await settle(page); + await saved(page); await arrive(page, platesUrl()); await viaButton(page, '#navBins', binsUrl()); expect(await page.inputValue('#drawerW')).toBe('500'); @@ -771,7 +779,7 @@ for (const reload of [false, true]) { await H.setField(page, 'drawerD', '400'); await H.setField(page, 'bedW', '220'); await page.selectOption('#connector', 'snap'); - await settle(page); + await saved(page); const mine = await stored(page, PLATES); await arrive(page, binsUrl() + '#w=333&d=333&bw=250&bd=250&bl=0-0-1-1-3'); @@ -798,9 +806,11 @@ test('a page that declined a link goes on from its defaults, not the link', asyn await page.evaluate(([k, v]) => localStorage.setItem(k, v), [BINS + ':loading', save]); await arrive(page, binsUrl()); await expect(page.locator('#setAside')).toContainText(/did not finish loading/); + expect(await stored(page, BINS + ':linked'), 'declined, the link is still recorded').not.toBeNull(); await H.dragCells(page, [0, 0], [0, 0]); // the edit's save, however long a busy page takes to it - await expect.poll(() => stored(page, BINS + ':linked')).toBeNull(); + await expect.poll(() => stored(page, BINS + ':linked'), { message: 'the edit ends the record' }) + .toBeNull(); }); test('the guide passes a layout on without its own anchors in the way', async ({ page }) => { @@ -815,8 +825,12 @@ test('the guide passes a layout on without its own anchors in the way', async ({ const layout = await page.evaluate(() => location.hash); expect(layout).toMatch(/(^#|&)ph=/); - // a guide link with an anchor of its own carries the layout, not "#heights#w=…" - await page.goto(site.base + 'guide/drawer-sizes/' + layout); + // on from the guide to one of its own pages, which carries it too + await Promise.all([page.waitForEvent('load'), page.click('a[href="drawer-sizes/"]')]); + expect(page.url().split('#')[0]).toBe(site.base + 'guide/drawer-sizes/'); + expect(await page.evaluate(() => location.hash)).toBe(layout); + + // and a link there with an anchor of its own carries the layout, not "#heights#w=…" await Promise.all([page.waitForEvent('load'), page.click('a[href="../#heights"]')]); expect(page.url().split('#')[0]).toBe(site.base + 'guide/'); expect(await page.evaluate(() => location.hash)).toBe(layout); @@ -830,7 +844,7 @@ test('looking at a linked layout differently is not changing it', async ({ page await H.openBins(page, binsUrl()); await H.dragCells(page, [0, 0], [1, 1]); await H.dragCells(page, [3, 3], [3, 3]); - await settle(page); + await saved(page); await arrive(page, binsUrl() + '#bl=0-0-1-1-3'); await expect(page.locator('#putBack')).toBeVisible(); @@ -850,7 +864,7 @@ test('a link with your bins in a drawer of another size still offers yours back' async ({ page }) => { await H.openBins(page, binsUrl()); await H.dragCells(page, [0, 0], [1, 1]); - await settle(page); + await saved(page); const save = await stored(page, BINS); await arrive(page, binsUrl() + '#' + save.replace(/(^|&)w=\d+/, '$1w=500')); expect(await page.evaluate(() => state.drawerW)).toBe(500); @@ -902,3 +916,280 @@ test('a layout that will not write is not saved as something else', async ({ pag await settle(page); expect(await stored(page, BINS)).toBe(save); }); + +/* A link pasted over the page as an edit's save comes due. The paste puts the link in the + address at once and its hashchange, which reloads onto it, comes after; a page still + drawing the edit comes to the waiting save first. That save wrote the page's own design + back over the link, the hashchange then found that and reloaded it, and the link was + gone, with nothing said. Here the save runs in the same task as the paste, as it did. */ +for (const [tool, key] of [['plates', PLATES], ['bins', BINS]]) { + test(`a link pasted over ${tool} as an edit's save comes due is the link`, async ({ page }) => { + const errors = watch(page); + await arrive(page, tool === 'bins' ? binsUrl() : platesUrl()); + const before = await page.inputValue('#drawerW'); + // the edit, its save still waiting when the paste lands, all in one task + await Promise.all([page.waitForEvent('load'), page.evaluate(() => { + const e = document.getElementById('drawerW'); + e.value = '412'; + e.dispatchEvent(new Event('input', { bubbles: true })); + e.dispatchEvent(new Event('change', { bubbles: true })); + if (typeof landEdit === 'function') landEdit(); // the edit read in, as a save does + location.hash = '#w=333&d=444&v=2'; + saveNow(); + })]); + await ready(page); + expect(await page.inputValue('#drawerW')).toBe('333'); + await expect(page.locator('#setAsideMsg')).toHaveText('This link replaced the layout you had here.'); + // the edit was saved, and is what the link set aside + expect(await stored(page, key + ':prev')).toMatch(/(^|&)w=412(&|$)/); + + /* Back goes to the address before the paste, which never had the edit: it is aside, and + in no earlier address, so it is offered there too. */ + await page.goBack(); + await ready(page); + expect(await page.inputValue('#drawerW')).toBe(before); + await expect(page.locator('#setAsideMsg')) + .toHaveText('This page went back to an earlier layout of yours. The later one is set aside.'); + await clickAndLoad(page, '#putBack'); + expect(await page.inputValue('#drawerW')).toBe('412'); + expect(errors).toEqual([]); + }); +} + +/* And only that save. A layout aside for any other reason can be older than the page Back + brings: someone's link kept as a drawer of yours, a second link over it, then Back to the + first. That offered "the later one", and Put back brought the layout from before the + first link, with the second gone from Forward. */ +for (const tool of ['plates', 'bins']) { + test(`Back to a link kept as a drawer on ${tool}, over a second link, offers nothing older`, + async ({ page }) => { + const errors = watch(page); + const url = tool === 'bins' ? binsUrl() : platesUrl(); + await arrive(page, url); + await H.setField(page, 'drawerW', '400'); + await saved(page); + const paste = async (h) => { + await Promise.all([page.waitForEvent('load'), page.evaluate((x) => { location.hash = x; }, h)]); + await ready(page); + }; + await paste('#w=333&d=444&v=2'); + await page.click('#drawersBtn'); + await page.fill('#drawersNewName', 'Kit'); + await page.press('#drawersNewName', 'Enter'); + await expect(page.locator('#drawersMsg')).toContainText('Saved as “Kit”'); + await page.click('#drawersClose'); + await saved(page); + await paste('#w=355&d=466&v=2'); + await expect(page.locator('#setAsideMsg')).toHaveText('This link replaced the layout you had here.'); + + await page.goBack(); + await ready(page); + expect(await page.inputValue('#drawerW')).toBe('333'); + await expect(page.locator('#drawerName')).toHaveText('Kit'); + await expect(page.locator('#setAside'), 'nothing is offered').toBeHidden(); + await page.goForward(); + await ready(page); + expect(await page.inputValue('#drawerW'), 'and the second link is still Forward').toBe('355'); + expect(errors).toEqual([]); + }); +} + +/* ---------- Start fresh ----------------------------------------------------- */ + +/* Start fresh clears this browser's save and loads the bare page, and the page runs on + until that one arrives. A change that landed in between was saved after the clearing, + and the bare page came back with it, saying it had been restored. Here the bare page is + slow to come, and the change lands 50 ms after the press: on Baseplates a field's + change, on Bins its input, which Bins reads in 180 ms on. Both pages are covered. */ +for (const tool of ['plates', 'bins']) { + test(`Start fresh on ${tool} is not undone by a change that lands as the page goes`, async ({ page }) => { + const errors = watch(page); + const url = tool === 'bins' ? binsUrl() : platesUrl(); + await arrive(page, url + '#w=333&d=444&v=2'); + await page.route((u) => u.href === url, async (route) => { + await new Promise((r) => setTimeout(r, 1500)); + await route.continue(); + }); + await Promise.all([page.waitForEvent('load'), page.evaluate((ev) => { + document.getElementById('startFresh').click(); + setTimeout(() => { + const e = document.getElementById('drawerW'); + e.value = '345'; + e.dispatchEvent(new Event(ev, { bubbles: true })); + }, 50); + }, tool === 'bins' ? 'input' : 'change')]); + await ready(page); + expect(await page.inputValue('#drawerW')).not.toBe('345'); + await expect(page.locator('#restored')).toBeHidden(); + expect(await stored(page, tool === 'bins' ? BINS : PLATES)).not.toMatch(/(^|&)w=345(&|$)/); + expect(errors).toEqual([]); + }); +} + +/* And the button is wired before the boot reads a link, so a link that throws partway + through the boot does not take it away: Start fresh still clears the save and loads the + bare page with the defaults, though the page never got as far as letting saves start. + The links that used to throw no longer do, so the page is made to throw here, after it + has read a link carrying `boom`. The note the button sits in is shown later in the + boot, so it is pressed from script. */ +for (const tool of ['plates', 'bins']) { + test(`Start fresh on ${tool} still clears the save when a link throws in the boot`, async ({ page }) => { + const url = tool === 'bins' ? binsUrl() : platesUrl(); + await arrive(page, url); + await H.setField(page, 'drawerW', '451'); + await saved(page); + await page.route((u) => u.href === url, async (route) => { + const res = await route.fetch(); + await route.fulfill({ response: res, body: (await res.text()).replace('loadFromHash(src);', + "loadFromHash(src); if (/(^|&)boom=/.test(src)) throw new Error('boom');") }); + }); + const thrown = []; + page.on('pageerror', (e) => thrown.push(String(e))); + await arrive(page, url + '#w=345&d=444&boom=1&v=2'); + expect(thrown.join(), 'the boot threw').toContain('boom'); + await Promise.all([page.waitForEvent('load'), + page.evaluate(() => document.getElementById('startFresh').click())]); + await ready(page); + expect(await page.evaluate(() => new URL(performance.getEntriesByType('navigation')[0].name).hash), + 'the bare page').toBe(''); + expect(await page.inputValue('#drawerW')).not.toBe('451'); + expect(await page.inputValue('#drawerW')).not.toBe('345'); + await expect(page.locator('#restored')).toBeHidden(); + expect(thrown.filter((e) => !/boom/.test(e))).toEqual([]); + }); +} + +/* However early the boot stops, Start fresh also ends the record of an edit a pasted link + set aside (see the paste tests above). The record's key is declared with the save's: declared + where the record is read, further on, it was not there yet for a boot stopped before + that, and the record stayed. The page is made to throw just after the button is wired. */ +for (const tool of ['plates', 'bins']) { + test(`Start fresh on ${tool} ends the pasted-link record when the boot stops early`, async ({ page }) => { + const url = tool === 'bins' ? binsUrl() : platesUrl(); + const key = (tool === 'bins' ? BINS : PLATES) + ':pasted'; + await arrive(page, url); + await page.evaluate((k) => sessionStorage.setItem(k, JSON.stringify({ save: 'a', at: 'b' })), key); + const wired = "$('startFresh').addEventListener('click', startFresh);"; + await page.route((u) => u.href === url, async (route) => { + const res = await route.fetch(); + await route.fulfill({ response: res, body: (await res.text()).replace(wired, + (m) => m + " if (/(^|&)boom=/.test(location.hash)) throw new Error('boom');") }); + }); + const thrown = []; + page.on('pageerror', (e) => thrown.push(String(e))); + await arrive(page, url + '#w=345&d=444&boom=1&v=2'); + expect(thrown.join(), 'the boot threw').toContain('boom'); + await Promise.all([page.waitForEvent('load'), + page.evaluate(() => document.getElementById('startFresh').click())]); + await ready(page); + expect(await page.evaluate((k) => sessionStorage.getItem(k), key), 'the record').toBeNull(); + expect(thrown.filter((e) => !/boom/.test(e))).toEqual([]); + }); +} + +/* And it ends the offer of an edit a pasted link set aside (see the paste tests above). The + edit was offered on Back, and left; then a bare visit, and Start fresh there. The record + of the edit's save stayed, and the fresh page is at the address it names: another link + pasted over it, then Back to it, offered the edit as the later layout, and Put back + brought it, though Start fresh came after it. Both pages are covered. */ +for (const tool of ['plates', 'bins']) { + test(`Start fresh on ${tool} ends the offer of an edit a pasted link set aside`, async ({ page }) => { + const errors = watch(page); + const url = tool === 'bins' ? binsUrl() : platesUrl(); + await arrive(page, url); + await saved(page); + const paste = async (h, edit) => { + await Promise.all([page.waitForEvent('load'), page.evaluate(([h, edit]) => { + if (edit) { + const e = document.getElementById('drawerW'); + e.value = edit; + e.dispatchEvent(new Event('input', { bubbles: true })); + e.dispatchEvent(new Event('change', { bubbles: true })); + if (typeof landEdit === 'function') landEdit(); + } + location.hash = h; + if (edit) saveNow(); + }, [h, edit])]); + await ready(page); + }; + await paste('#w=333&d=444&v=2', '412'); + await page.goBack(); + await ready(page); + await expect(page.locator('#setAsideMsg')) + .toHaveText('This page went back to an earlier layout of yours. The later one is set aside.'); + + await arrive(page, url); + await clickAndLoad(page, '#startFresh'); + await saved(page); + await paste('#w=355&d=466&v=2'); + await page.goBack(); + await ready(page); + expect(await page.inputValue('#drawerW'), 'the fresh page').not.toBe('355'); + await expect(page.locator('#setAside'), 'nothing is offered').toBeHidden(); + expect(errors).toEqual([]); + }); +} + +/* Start fresh stops the page's saves as it goes, and a browser that keeps the page in its + back-forward cache can show it again on Back. Shown again, it is a page of yours, and its + changes save, as they did before Start fresh and as they do when it is loaded again. + Chromium does not keep it, so here the page is stopped before the fresh one arrives and + shown again as the cache would. Both pages are covered, and so is Start fresh pressed twice + before the page goes. The second press found saves already stopped by the first, and the + page shown again from the cache did not save. */ +for (const tool of ['plates', 'bins']) for (const presses of [1, 2]) { + test(`a ${tool} page left by Start fresh${presses === 2 ? ', pressed twice,' : ''} and shown again from ` + + 'the cache saves again', async ({ page }) => { + const errors = watch(page); + const url = tool === 'bins' ? binsUrl() : platesUrl(); + await arrive(page, url); + await H.setField(page, 'drawerW', '451'); + await saved(page); + await arrive(page, url); // a bare visit, restoring it, which offers Start fresh + await page.route((u) => u.href === url, async (route) => { + await new Promise((r) => setTimeout(r, 5000)); + await route.continue().catch(() => {}); + }); + await page.evaluate((presses) => { + for (let i = 0; i < presses; i += 1) document.getElementById('startFresh').click(); + window.stop(); // the fresh page never arrives + dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true })); + }, presses); + await H.setField(page, 'drawerW', '377'); + await saved(page); + expect(await stored(page, tool === 'bins' ? BINS : PLATES)).toMatch(/(^|&)w=377(&|$)/); + expect(errors).toEqual([]); + }); +} + +/* Not once Put back is pressed after it, before the fresh page arrives: Put back leaves last, + and that page, shown again from the cache, would save over the layout just put back. */ +for (const tool of ['plates', 'bins']) { + test(`a ${tool} page left by Start fresh, then Put back, and shown again from the cache does not save`, + async ({ page }) => { + const errors = watch(page); + const url = tool === 'bins' ? binsUrl() : platesUrl(); + const key = tool === 'bins' ? BINS : PLATES; + await arrive(page, url); + await H.setField(page, 'drawerW', '451'); + await saved(page); + await arrive(page, url + '#w=333&d=444&v=2'); // a link, which sets that layout aside + await expect(page.locator('#putBack')).toBeVisible(); + await page.route((u) => u.href === url, async (route) => { + await new Promise((r) => setTimeout(r, 5000)); + await route.continue().catch(() => {}); + }); + await page.evaluate(() => { + document.getElementById('startFresh').click(); + document.getElementById('putBack').click(); + window.stop(); // neither page arrives + dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true })); + }); + const put = await stored(page, key); + expect(put, 'the layout put back').toMatch(/(^|&)w=451(&|$)/); + await H.setField(page, 'drawerW', '377'); + await settle(page); + expect(await stored(page, key), 'still the layout put back').toBe(put); + expect(errors).toEqual([]); + }); +} diff --git a/test/ui/persist.spec.js b/test/ui/persist.spec.js index 071e87b..edd646c 100644 --- a/test/ui/persist.spec.js +++ b/test/ui/persist.spec.js @@ -42,8 +42,8 @@ async function openBins(page) { const settle = (page) => page.waitForTimeout(900); // past the 400 ms debounce /* Until this browser holds the save `re` matches. A page still busy drawing the edit comes to its save late, and a fixed wait was now and then too short for it. */ -const savedAs = (page, key, re) => - expect.poll(() => page.evaluate((k) => localStorage.getItem(k), key)).toMatch(re); +const savedAs = (page, key, re) => expect.poll(() => + page.evaluate((k) => localStorage.getItem(k) || '', key), { message: `${key} is saved` }).toMatch(re); test('the baseplates page comes back the way you left it', async ({ page }) => { await openPlates(page);