Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## 6.10.2

- Performance: paint visited markers and keyword tinting as soon as the local working copy is read, without waiting for sync configuration, recovery journals, or DOMContentLoaded. Observe newly inserted tiles during page loading too.
- Read independent storage values in parallel. Reconcile journals before enabling controls or writing history, then refresh the early tile display with recovered settings and visits.
- Add startup tests for pending sync configuration, pending journal reads, and tiles arriving before DOMContentLoaded.
- The worker version moves to 6.10.2 with the userscript; worker behavior is unchanged.

## 6.10.1

- Fix: tile links with a literal `#` inside an item filename now encode it as `%23`, so the server receives the complete path instead of returning a 404. This applies to existing tiles and dynamically added or changed tiles, including links opened through the browser's context menu.
Expand Down
43 changes: 33 additions & 10 deletions javstore-full-layout-cleanup.user.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// ==UserScript==
// @name JavStore Full Layout Cleanup - No Sidebars + Mosaic Overlay
// @namespace http://tampermonkey.net/
// @version 6.10.1
// @version 6.10.2
// @description Clean up JavStore's layout, filter keyword-matched thumbnails, and track visited items with private, configurable controls.
// @homepageURL https://github.com/jitdor/userscript-javstore
// @supportURL https://github.com/jitdor/userscript-javstore/issues
Expand Down Expand Up @@ -29,7 +29,7 @@
(function () {
'use strict';

const SCRIPT_VERSION = '6.10.1';
const SCRIPT_VERSION = '6.10.2';
// The same address as @downloadURL: opening it hands the newest release to the
// userscript manager, which offers to install it.
const INSTALL_URL = 'https://github.com/jitdor/userscript-javstore/releases/latest/download/javstore-full-layout-cleanup.user.js';
Expand Down Expand Up @@ -365,17 +365,22 @@
));
}

async function readStorageSnapshot() {
async function readMainState() {
let main = null;
try {
main = await loadValue(STORAGE_KEY);
storageAvailable = true;
} catch (error) {
storageAvailable = false;
console.warn('[JVS] Isolated storage could not be read.', error);
return { main: null, journals: [] };
return null;
}
return { main, journals: await readJournals() };
return main;
}

async function readStorageSnapshot() {
const [main, journals] = await Promise.all([readMainState(), readJournals()]);
return { main, journals };
}

// ------------------------------------------------------------------
Expand Down Expand Up @@ -2139,7 +2144,7 @@

function observeDynamicContent() {
observer?.disconnect();
const root = document.body;
const root = document.body || document.documentElement;
if (!root) return;
Comment on lines +2147 to 2148

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Retry observation when the root does not exist

Because this userscript runs at document-start, a manager with synchronous GM storage APIs can finish both startup reads before the parser has created either <html> or <body>. In that case this expression yields null, the function returns without installing an observer, and nothing invokes it again until onReady() after DOMContentLoaded; consequently the new early tile painting does not work in that environment. Observe document itself or arrange to retry as soon as the root element appears.

Useful? React with 👍 / 👎.

observer = new MutationObserver(mutations => {
const roots = new Set();
Expand Down Expand Up @@ -2808,10 +2813,7 @@
}
}

async function boot() {
syncConfig = await readSyncConfig();
const snapshot = await readStorageSnapshot();
const initialState = combineSnapshot(snapshot);
function initializeState(initialState) {
settings = sanitizeSettings(initialState?.settings);
visited = parseVisited(initialState?.visited);
overrides = parseOverrides(initialState?.overrides);
Expand All @@ -2823,8 +2825,29 @@
lastKnownUpdatedAt = parseTimestamp(initialState?.updatedAt);
settingsUpdatedAt = parseTimestamp(initialState?.settingsUpdatedAt) || lastKnownUpdatedAt;
settingTimes = documentSettingTimes(initialState);
}

async function boot() {
// Start independent reads together. Only the local working copy is needed
// to paint tiles; sync configuration and recovery must not hold it up.
const configPromise = readSyncConfig();
const journalsPromise = readJournals();
const main = await readMainState();
initializeState(main);
setRootState();
processAllCards();
observeDynamicContent();

// No writes or controls are enabled during the preview. Reconcile journals
// before replay/migration so stale local data cannot overwrite recovery.
const [config, journals] = await Promise.all([configPromise, journalsPromise]);
syncConfig = config;
const snapshot = { main, journals };
initializeState(combineSnapshot(snapshot));
const replayed = replayPendingVisits();
pruneVisited();
setRootState();
processAllCards();
await migrateLegacyHistory();
if (replayed || journalsAhead(snapshot)) persistState();
setRootState();
Expand Down
2 changes: 2 additions & 0 deletions tests/harness.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ export async function openTab(store, {
session = new Map(),
remote = null,
confirm = () => true,
beforeRun = () => {},
} = {}) {
const options = {
url,
Expand Down Expand Up @@ -267,6 +268,7 @@ export async function openTab(store, {
};
}

beforeRun(window);
vm.runInContext(source, dom.getInternalVMContext());
await settle();
return { dom, window, session, store, shadow: () => window.document.getElementById('jvs-controls-host').shadowRoot };
Expand Down
69 changes: 69 additions & 0 deletions tests/startup.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import test, { afterEach } from 'node:test';
import assert from 'node:assert/strict';
import { makeStore, openTab, closeTabs, listingHtml, waitFor } from './harness.mjs';

afterEach(closeTabs);
const url = 'https://javstore.net/590733-Item-pn.html';
const html = listingHtml([[url, 'Item']]);

function seededStore() {
const store = makeStore();
store.write('javstore_cleanup_state_v2', {
visited: { [url]: Date.now() - 1000 },
settings: { keywords: ['Item'], mode: 'tint' },
});
return store;
}

for (const blocked of ['config', 'journals']) {
test(`paints local tiles while ${blocked} storage is pending, then reconciles recovery`, async () => {
const store = seededStore();
const at = Date.now();
store.write('javstore_journal_v1_startup', {
visited: { 'https://javstore.net/recovered.html': at },
settings: { keywords: ['Different'], mode: 'tint' },
settingsUpdatedAt: at,
});
let release;
const gate = new Promise(resolve => { release = resolve; });
const get = store.get.bind(store);
const list = store.list.bind(store);
if (blocked === 'config') store.get = async (key, fallback) => {
if (key === 'javstore_sync_config_v1') await gate;
return get(key, fallback);
};
else store.list = async () => { await gate; return list(); };
let writes = 0;
const set = store.set.bind(store);
store.set = (...args) => { writes++; return set(...args); };
try {
const tab = await openTab(store, { html });
const tile = tab.window.document.querySelector('main .grid a');
await waitFor(() => tile.classList.contains('jvs-mode-tint'));
assert.ok(tile.classList.contains('jvs-visited'));
assert.equal(writes, 0, 'preview must not write before recovery is read');
release();
await waitFor(() => !tile.classList.contains('jvs-mode-tint'));
await waitFor(() => store.state()?.visited?.['https://javstore.net/recovered.html']);
} finally { release(); }
});
}

test('processes visible and newly inserted tiles before DOMContentLoaded', async () => {
const tab = await openTab(seededStore(), {
html,
beforeRun(window) {
Object.defineProperty(window.document, 'readyState', { configurable: true, get: () => 'loading' });
},
});
const tile = tab.window.document.querySelector('main .grid a');
await waitFor(() => tile.classList.contains('jvs-visited'));
assert.ok(tile.classList.contains('jvs-mode-tint'));
const added = tile.cloneNode(true);
added.className = '';
tile.parentElement.append(added);
await waitFor(() => added.classList.contains('jvs-visited'));
assert.ok(added.classList.contains('jvs-mode-tint'));
tab.window.document.dispatchEvent(new tab.window.Event('DOMContentLoaded'));
await waitFor(() => tab.window.document.getElementById('jvs-controls-host'));
});
2 changes: 1 addition & 1 deletion worker/src/worker.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
const STORAGE_VERSION = 3;
// Reported in every answer so the userscript can show which worker it is talking to. It
// moves in step with the userscript's own version; a test holds the two together.
export const WORKER_VERSION = '6.10.1';
export const WORKER_VERSION = '6.10.2';
const OBJECT_NAME = 'default';
const MAX_BODY_BYTES = 8 * 1024 * 1024;
const MAX_PAGE_ROWS = 2000;
Expand Down
Loading