PlotDirector/PlotLine/wwwroot/js/desktop-promotion.js
Nick Beckley e48889ac05 Complete desktop workspaces, context menus and plot health
Commit the pending application, help and browser regression work. Pin the patched PKCS dependency for the production release.
2026-10-31 09:27:04 +00:00

129 lines
10 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* Device-local, account-scoped promotion. Uses the parser-established application mode. */
(() => {
const user = document.body.dataset.desktopUser;
if (!user) return;
const mode = () => window.PlotDirectorPwa?.standalone === true;
const key = `plotdirector.desktop.v1.${user}`;
const period = 30 * 86400000;
let state = {}, persistent = true;
try { state = JSON.parse(localStorage.getItem(key) || '{}') || {}; } catch { persistent = false; }
const save = patch => {
Object.assign(state, patch);
try { localStorage.setItem(key, JSON.stringify(state)); } catch { persistent = false; }
};
let dialog, previous, hint, reminder, interacted = false;
const installed = () => mode() || window.PlotDirectorInstall?.installed || state.installed;
function close() { dialog?.close(); }
function instructions() {
const ua = navigator.userAgent;
if (/iPhone|iPad|iPod/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1))
return 'In Safari, open Share → Add to Home Screen. Enable Open as Web App if offered, then tap Add.';
if (/Edg\//.test(ua)) return 'In Edge, open … → More tools → Apps → Install this site as an app. You may also see an app icon in the address bar.';
if (/Android/.test(ua)) return 'Open your browser menu → Install app or Add to Home screen, if offered. Confirm installation in the browser.';
if (/Chrome\//.test(ua)) return 'In Chrome, open ⋮ → Cast, save, and share → Install page as app… You may also see an install icon in the address bar.';
if (/Safari\//.test(ua) && /Macintosh/.test(ua)) return 'In Safari on macOS Sonoma or later, choose File → Add to Dock, then Add.';
return 'Installation options vary by browser and operating system. For the desktop installation experience, open PlotDirector in current Chrome or Edge and choose the app installation option in the browser menu.';
}
function ready() {
save({ installed: true });
reminder?.remove();
if (!dialog?.open) return;
dialog.querySelector('[data-install-status]').textContent = 'PlotDirector Desktop is ready. Open PlotDirector from your Start menu, taskbar or application launcher.';
dialog.querySelector('[data-desktop-install]').hidden = true;
dialog.querySelector('[data-desktop-continue]').textContent = 'Continue working';
}
function open(manual = false) {
if (mode() || window.PlotDirectorInstall?.installed) return;
if (dialog?.open) return;
previous = document.activeElement;
if (!dialog) {
dialog = document.createElement('dialog');
dialog.className = 'pd-desktop-promotion';
dialog.setAttribute('aria-labelledby', 'desktop-promotion-title');
dialog.innerHTML = `
<button type="button" class="pd-desktop-close" aria-label="Continue in browser">×</button>
<header><p class="pd-desktop-eyebrow">PLOTDIRECTOR DESKTOP</p>
<h1 id="desktop-promotion-title">PlotDirector is better as a desktop app</h1>
<p class="pd-desktop-tagline">The same PlotDirector. Less browser.</p></header>
<div class="pd-desktop-labels"><span>DESKTOP APP</span><span>BROWSER</span></div>
<div class="pd-desktop-viewport"><div class="pd-desktop-comparison" style="--split:68%">
<img src="/images/desktop/browser.png" width="1710" height="919" alt="Browser Timeline with tabs, address bar and page heading taking space above the story workspace." draggable="false">
<img class="pd-desktop-after" src="/images/desktop/desktop.png" width="1710" height="920" alt="Desktop Timeline with compact application ribbon and more room for scenes." draggable="false">
<div class="pd-desktop-divider" aria-hidden="true"><span>↔</span></div>
</div></div>
<label class="pd-desktop-slider-label" for="desktop-comparison">Drag to compare · Desktop workspace revealed</label>
<input id="desktop-comparison" type="range" min="0" max="100" value="68" aria-label="Desktop workspace revealed" aria-valuetext="68% Desktop, 32% Browser">
<div class="pd-desktop-benefits"><p><strong>More workspace</strong>Less browser-style page clutter.</p><p><strong>Desktop controls</strong>Contextual ribbon and right-click actions.</p><p><strong>Same projects and data</strong>Nothing to move or transfer.</p><p><strong>Always current</strong>No traditional software update cycle.</p></div>
<footer><button type="button" class="btn btn-primary" data-desktop-install>Install PlotDirector Desktop</button><button type="button" class="btn btn-link" data-desktop-continue>Continue in browser</button></footer>
<p role="status" data-install-status></p>
<p class="pd-desktop-note">An internet connection is required. <a href="/help/workspace/desktop">Installation help</a></p>`;
document.body.append(dialog);
dialog.addEventListener('keydown', event => {
if (event.key !== 'Tab') return;
const items = [...dialog.querySelectorAll('button, input, a[href]')].filter(e => !e.disabled && !e.hidden && e.getClientRects().length);
const first = items[0], last = items.at(-1);
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
});
const range = dialog.querySelector('input');
const frame = dialog.querySelector('.pd-desktop-comparison');
const set = value => {
range.value = Math.max(0, Math.min(100, value));
frame.style.setProperty('--split', `${range.value}%`);
range.setAttribute('aria-valuetext', `${range.value}% Desktop, ${100 - range.value}% Browser`);
};
const stopHint = () => { clearTimeout(hint); frame.classList.remove('pd-desktop-hint'); interacted = true; };
range.addEventListener('input', () => { stopHint(); set(range.value); });
let dragging = false;
const move = event => { if (dragging) { const rect = frame.getBoundingClientRect(); set((event.clientX - rect.left) / rect.width * 100); } };
frame.addEventListener('pointerdown', event => { if (event.button !== 0) return; event.preventDefault(); stopHint(); dragging = true; frame.setPointerCapture(event.pointerId); range.focus({ preventScroll: true }); move(event); });
frame.addEventListener('pointermove', move);
frame.addEventListener('pointerup', () => dragging = false);
frame.addEventListener('pointercancel', () => dragging = false);
dialog.querySelector('.pd-desktop-close').onclick = close;
dialog.querySelector('[data-desktop-continue]').onclick = close;
dialog.addEventListener('close', () => { clearTimeout(hint); save({ dismissedAt: Date.now() }); previous?.focus(); });
dialog.querySelector('[data-desktop-install]').onclick = async () => {
const button = dialog.querySelector('[data-desktop-install]');
button.disabled = true;
const result = await window.PlotDirectorInstall.request();
button.disabled = false;
// An accepted prompt alone does not prove installation completed.
dialog.querySelector('[data-install-status]').textContent = result === 'unavailable'
? instructions() + ' If it is already installed, open it from your application launcher. Private browsing or organisation policies may restrict installation.'
: result === 'accepted' ? 'Follow your browser’s installation flow. Once installed, open PlotDirector from your application launcher.' : 'Installation cancelled. You can try again or continue in browser.';
};
if (!state.shownAt && !matchMedia('(prefers-reduced-motion: reduce)').matches) {
set(60);
hint = setTimeout(() => { if (!interacted && dialog.open) { frame.classList.add('pd-desktop-hint'); set(68); setTimeout(() => frame.classList.remove('pd-desktop-hint'), 500); } }, 500);
}
}
save({ shownAt: state.shownAt || Date.now(), manuallyReopenedAt: manual ? Date.now() : state.manuallyReopenedAt });
reminder?.remove();
dialog.showModal();
dialog.querySelector('[data-desktop-install]').focus();
}
window.PlotDirectorDesktop = { open };
window.addEventListener('appinstalled', ready);
window.addEventListener('plotdirector:pwa-mode-changed', () => { if (mode()) { close(); reminder?.remove(); save({ installed: true }); } });
if (mode()) { save({ installed: true }); return; }
if (installed() || !persistent || document.body.dataset.desktopEligible !== 'true') return;
// Existing authorised project AND book, on a substantive workspace. No new analytics or database state.
if (!/^\/(Timeline|PlotLineWorkspace|StoryBible|Writer|StoryCalendar|StoryPoint|Characters|Locations|StoryAssets)(\/|$)/i.test(location.pathname)) return;
const last = Math.max(Number(state.dismissedAt) || 0, Number(state.shownAt) || 0, Number(state.remindedAt) || 0);
if (!last) {
setTimeout(() => {
if (!mode() && !document.hidden && !document.querySelector('dialog[open], .modal.show') && !document.querySelector('[data-story-intelligence-has-active-work="true"]')) open();
}, 1800);
} else if (Date.now() - last >= period) {
reminder = document.createElement('aside');
reminder.className = 'pd-desktop-reminder';
reminder.setAttribute('aria-label', 'PlotDirector Desktop');
reminder.innerHTML = '<strong>Still using PlotDirector in a browser?</strong><p>See how much more workspace the desktop app gives you.</p><button type="button" class="btn btn-primary">Compare</button> <button type="button" class="btn btn-link">Dismiss</button>';
reminder.querySelector('.btn-primary').onclick = () => open(true);
reminder.querySelector('.btn-link').onclick = () => { save({ dismissedAt: Date.now() }); reminder.remove(); };
document.body.append(reminder);
save({ remindedAt: Date.now() });
}
})();