diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml
index a3d3bb5..43152b2 100644
--- a/.github/workflows/pages.yml
+++ b/.github/workflows/pages.yml
@@ -38,6 +38,10 @@ jobs:
- run: pnpm build
+ # Open tabs fetch version.json (with a cache-busting query) to learn about a new deploy.
+ - name: Check the build id is in index.html and version.json
+ run: grep -q "\"build\":\"$(grep -o 'kandle-build" content="[0-9a-f]*' dist/index.html | cut -d'"' -f3)\"" dist/version.json
+
- uses: actions/configure-pages@v5
- uses: actions/upload-pages-artifact@v3
diff --git a/README.md b/README.md
index 662dd09..e45a2ac 100644
--- a/README.md
+++ b/README.md
@@ -719,6 +719,15 @@ No. The chart is stored after the `#` in the link, and browsers do not send that
+
+How do I get a new version?
+
+
+
+Reload the page. A tab that stays open checks for a new version when you come back to it and every 30 minutes, and shows **Kandle was updated** with a **Reload** button. Your layout, drawings, scripts, watchlist and alerts are saved as you go, so a reload keeps them. If you are in bar replay or looking at a shared chart you have not kept, it says so before reloading. Embedded charts do not check.
+
+
+
Why is Finnhub not a data source?
diff --git a/src/app.ts b/src/app.ts
index aedf5a7..9a9172c 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -28,6 +28,7 @@ import { scriptRows } from './ui/scriptInputs';
import type { ScriptPanel } from './ui/scriptPanel';
import type { SharedView } from './share/view';
import { createKeyCover, keyGate } from './share/keyGate';
+import { createUpdateBanner } from './update';
const DRAWINGS_GROUP = 'drawings';
const CANDLE_PANE = 'candle_pane';
@@ -664,6 +665,26 @@ export class App {
setTimeout(() => t.remove(), kind === 'error' ? 6000 : 3000);
}
+ /** Shows the banner for a newer build (src/update.ts) above the toasts. */
+ offerUpdate(): void {
+ if (this.el.toasts.querySelector('.update-banner')) return;
+ this.el.toasts.prepend(createUpdateBanner({ beforeReload: () => this.prepareReload() }));
+ }
+
+ /**
+ * Before a reload into a new build: saves the drawings and the script draft now (they are
+ * otherwise saved a moment after each change) and returns what a reload would still lose.
+ * Layouts, indicators, scripts on the chart, the watchlist and alerts are saved as they change.
+ */
+ prepareReload(): string[] {
+ this.saveDrawings();
+ this.scriptPanel?.saveDraft();
+ const lost: string[] = [];
+ if (this.shared?.storage.temporary) lost.push('This shared chart opens again as the link has it, without your changes. Use Keep it to save it as your chart first.');
+ if (this.features.replayActive()) lost.push('Bar replay ends.');
+ return lost;
+ }
+
private persistLayout(): void {
if (!this.store.saveLayout(this.layout)) this.toast('Could not save layout to browser storage', 'error');
}
diff --git a/src/features/index.ts b/src/features/index.ts
index 5fd9579..2ea0155 100644
--- a/src/features/index.ts
+++ b/src/features/index.ts
@@ -67,6 +67,8 @@ export interface Features {
onLiveCandle(candle: Candle): void;
/** Call after window.kandle exists. Builds the UI and connects everything. */
start(): void;
+ /** True while bar replay runs (a reload ends it). */
+ replayActive(): boolean;
}
const DRAWINGS_GROUP = 'drawings';
@@ -244,6 +246,8 @@ export function createFeatures(deps: FeatureDeps): Features {
if (mainPane) onPaneCandle(mainPane, candle);
},
+ replayActive: () => replay?.active ?? false,
+
start() {
if (!loader) throw new Error('wrapLoader must be called before start');
const switching = loader;
diff --git a/src/main.ts b/src/main.ts
index e9346b3..d80b253 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -7,6 +7,7 @@ import { keyGate, keyedSources } from './share/keyGate';
import { openSharedView, type SharedView } from './share/view';
import { browserStorage, type KeyValueStorage } from './store/layout';
import { h } from './ui/dom';
+import { watchForUpdates } from './update';
const root = document.getElementById('app');
if (!root) throw new Error('Missing #app element');
@@ -68,6 +69,8 @@ if (embed.embed) {
const app = new App(root, view?.storage ?? storage, view);
await app.start();
if (error) app.toast(error, 'error');
+ // A tab left open learns about a new deploy; embeds and framed pages never check.
+ watchForUpdates(() => app.offerUpdate());
})
.catch(failed);
}
diff --git a/src/styles.css b/src/styles.css
index c2941d3..58dde9f 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -878,6 +878,41 @@ kbd {
border-color: var(--down);
}
+/* A newer build is deployed (src/update.ts). */
+.update-banner {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 8px 8px 8px 14px;
+}
+
+.ub-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+
+.ub-text {
+ flex: 1;
+}
+
+.ub-actions {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+}
+
+.ub-end {
+ justify-content: flex-end;
+ padding-bottom: 2px;
+}
+
+.ub-lost {
+ margin: 0;
+ padding-left: 18px;
+ color: var(--muted);
+}
+
/* ---------------------------------------------------------------- responsive */
@media (max-width: 900px) {
diff --git a/src/ui/scriptPanel.ts b/src/ui/scriptPanel.ts
index a9347e1..69dec18 100644
--- a/src/ui/scriptPanel.ts
+++ b/src/ui/scriptPanel.ts
@@ -37,6 +37,8 @@ export interface ScriptPanel {
run(): RunScriptResult;
/** Opens the panel on the Strategy tab, showing the strategy with `id` if given. */
showStrategy(id?: string): void;
+ /** Writes the draft now instead of a moment after the last edit (before a reload). */
+ saveDraft(): void;
}
type PanelTab = 'editor' | 'strategy';
@@ -92,15 +94,18 @@ export function createScriptPanel(opts: ScriptPanelOptions): ScriptPanel {
let tab: PanelTab = draft.tab ?? 'editor';
let saveTimer: ReturnType | null = null;
+ const writeDraft = () => {
+ if (saveTimer) clearTimeout(saveTimer);
+ saveTimer = null;
+ try {
+ storage.setItem(draftKey, JSON.stringify({ source: view.state.doc.toString(), target, height, tab }));
+ } catch {
+ // storage full or blocked; the draft is a convenience only
+ }
+ };
const saveDraft = () => {
if (saveTimer) clearTimeout(saveTimer);
- saveTimer = setTimeout(() => {
- try {
- storage.setItem(draftKey, JSON.stringify({ source: view.state.doc.toString(), target, height, tab }));
- } catch {
- // storage full or blocked; the draft is a convenience only
- }
- }, 300);
+ saveTimer = setTimeout(writeDraft, 300);
};
// ------------------------------------------------------------------ DOM
@@ -353,6 +358,9 @@ export function createScriptPanel(opts: ScriptPanelOptions): ScriptPanel {
else panel.close();
},
isOpen: () => !root.hidden,
+ saveDraft: () => {
+ if (saveTimer) writeDraft();
+ },
};
refreshTargets();
setTab(tab);
diff --git a/src/update.ts b/src/update.ts
new file mode 100644
index 0000000..39ec475
--- /dev/null
+++ b/src/update.ts
@@ -0,0 +1,91 @@
+/**
+ * Tells a tab that stays open when a newer build of the app is deployed. The build writes its id
+ * into index.html () and into version.json next to it (vite.config.ts);
+ * when they differ, this tab is out of date. A reload is enough to update, since nothing caches
+ * the app, so the banner only offers one. Embeds never check (src/main.ts).
+ */
+import { APP } from './config';
+import { h, ICONS } from './ui/dom';
+
+const CHECK_EVERY_MS = 30 * 60_000;
+/** Switching tabs back and forth checks at most this often. */
+const MIN_GAP_MS = 60_000;
+
+/** The build id of the running page, or null in development. */
+export function currentBuild(doc: Document = document): string | null {
+ return doc.querySelector('meta[name="kandle-build"]')?.content || null;
+}
+
+/** The build id of the latest deploy, or null when it cannot be read (offline, for example). */
+export async function latestBuild(base: string = document.baseURI, fetcher: typeof fetch = fetch): Promise {
+ try {
+ // The query and no-store skip every cache on the way (GitHub Pages sends max-age=600).
+ const url = new URL('version.json', base);
+ url.searchParams.set('t', String(Date.now()));
+ const res = await fetcher(url, { cache: 'no-store' });
+ if (!res.ok) return null;
+ const data = (await res.json()) as { build?: unknown };
+ return typeof data.build === 'string' && data.build ? data.build : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Calls `onUpdate` once, when a build newer than this page is found. Checks when the tab becomes
+ * visible again, every 30 minutes and when the connection comes back.
+ */
+export function watchForUpdates(onUpdate: () => void): void {
+ const mine = currentBuild();
+ if (!mine) return;
+ let found = false;
+ let running = false;
+ let last = 0;
+ const check = async (force = false) => {
+ if (found || running || !navigator.onLine) return;
+ if (!force && Date.now() - last < MIN_GAP_MS) return;
+ running = true;
+ last = Date.now();
+ const latest = await latestBuild();
+ running = false;
+ if (found || !latest || latest === mine) return;
+ found = true;
+ clearInterval(timer);
+ onUpdate();
+ };
+ const timer = setInterval(() => void check(true), CHECK_EVERY_MS);
+ document.addEventListener('visibilitychange', () => {
+ if (!document.hidden) void check();
+ });
+ window.addEventListener('online', () => void check());
+}
+
+export interface UpdateBannerOptions {
+ /** Saves what is waiting to be saved and returns what a reload would still lose, as sentences. */
+ beforeReload(): string[];
+ reload?: () => void;
+}
+
+/** "Kandle was updated" with Reload. If a reload would lose something, it says what first. */
+export function createUpdateBanner(options: UpdateBannerOptions): HTMLElement {
+ const reload = options.reload ?? (() => window.location.reload());
+ const text = h('span', { class: 'ub-text' }, `${APP.name} was updated.`);
+ const reloadBtn = h('button', { class: 'btn btn-primary', type: 'button' }, 'Reload');
+ const closeBtn = h('button', { class: 'icon-btn', type: 'button', title: 'Close', 'aria-label': 'Close', html: ICONS.close });
+ const actions = h('span', { class: 'ub-actions' }, reloadBtn, closeBtn);
+ const banner = h('div', { class: 'toast update-banner', role: 'status' }, h('div', { class: 'ub-row' }, text, actions));
+ closeBtn.addEventListener('click', () => banner.remove());
+ reloadBtn.addEventListener('click', () => {
+ const lost = options.beforeReload();
+ if (lost.length === 0) return reload();
+ // Say what the reload would lose and let the user choose.
+ const anyway = h('button', { class: 'btn btn-primary', type: 'button', onclick: reload }, 'Reload anyway');
+ const later = h('button', { class: 'btn', type: 'button', onclick: () => banner.remove() }, 'Not now');
+ banner.replaceChildren(
+ h('div', { class: 'ub-row' }, h('span', { class: 'ub-text' }, `${APP.name} was updated. If you reload now:`)),
+ h('ul', { class: 'ub-lost' }, ...lost.map((l) => h('li', {}, l))),
+ h('div', { class: 'ub-row ub-end' }, later, anyway),
+ );
+ });
+ return banner;
+}
diff --git a/tests/update.test.ts b/tests/update.test.ts
new file mode 100644
index 0000000..215a0d2
--- /dev/null
+++ b/tests/update.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+import { currentBuild, latestBuild } from '../src/update';
+
+const base = 'https://example.org/kandle/';
+
+function fakeFetch(body: unknown, init: { status?: number; fail?: boolean } = {}) {
+ const calls: { url: string; init?: RequestInit }[] = [];
+ const fetcher = (async (url: URL | RequestInfo, opts?: RequestInit) => {
+ calls.push({ url: String(url), init: opts });
+ if (init.fail) throw new TypeError('offline');
+ return new Response(typeof body === 'string' ? body : JSON.stringify(body), { status: init.status ?? 200 });
+ }) as typeof fetch;
+ return { fetcher, calls };
+}
+
+const docWith = (content: string | null) =>
+ ({ querySelector: (sel: string) => (content !== null && sel === 'meta[name="kandle-build"]' ? { content } : null) }) as unknown as Document;
+
+describe('update check', () => {
+ it('reads the build id of the page from index.html', () => {
+ expect(currentBuild(docWith('abc123def456'))).toBe('abc123def456');
+ expect(currentBuild(docWith(null))).toBeNull();
+ expect(currentBuild(docWith(''))).toBeNull();
+ });
+
+ it('fetches version.json next to the page, past every cache', async () => {
+ const { fetcher, calls } = fakeFetch({ version: '0.10.1', build: 'b2' });
+ expect(await latestBuild(base, fetcher)).toBe('b2');
+ const url = new URL(calls[0].url);
+ expect(url.origin + url.pathname).toBe('https://example.org/kandle/version.json');
+ expect(url.searchParams.get('t')).toMatch(/^\d+$/);
+ expect(calls[0].init?.cache).toBe('no-store');
+ });
+
+ it('gives null when the file cannot be read', async () => {
+ expect(await latestBuild(base, fakeFetch({}, { fail: true }).fetcher)).toBeNull();
+ expect(await latestBuild(base, fakeFetch('not found', { status: 404 }).fetcher)).toBeNull();
+ expect(await latestBuild(base, fakeFetch('').fetcher)).toBeNull();
+ expect(await latestBuild(base, fakeFetch({ build: 42 }).fetcher)).toBeNull();
+ });
+});
diff --git a/vite.config.ts b/vite.config.ts
index 2027a37..344e13a 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -1,3 +1,6 @@
+import { createHash } from 'node:crypto';
+import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
+import { join, relative } from 'node:path';
import { defineConfig, type Plugin } from 'vitest/config';
import { APP } from './src/config.ts';
@@ -12,9 +15,42 @@ function appName(): Plugin {
};
}
+/**
+ * Gives every build an id, a hash of the files it is made of, so a deploy that changes nothing
+ * keeps the same id. It goes into index.html () and into version.json,
+ * which an open tab fetches to learn that a newer build is out (src/update.ts).
+ */
+function buildId(): Plugin {
+ let outDir = 'dist';
+ return {
+ name: 'build-id',
+ apply: 'build',
+ configResolved(c) {
+ outDir = c.build.outDir;
+ },
+ closeBundle() {
+ const files: string[] = [];
+ const walk = (dir: string) => {
+ for (const f of readdirSync(dir)) {
+ const p = join(dir, f);
+ if (statSync(p).isDirectory()) walk(p);
+ else files.push(relative(outDir, p).split('\\').join('/'));
+ }
+ };
+ walk(outDir);
+ const hash = createHash('sha256');
+ for (const f of files.filter((f) => f !== 'version.json').sort()) hash.update(f).update(readFileSync(join(outDir, f)));
+ const build = hash.digest('hex').slice(0, 12);
+ const index = join(outDir, 'index.html');
+ writeFileSync(index, readFileSync(index, 'utf8').replace('', ` \n `));
+ writeFileSync(join(outDir, 'version.json'), JSON.stringify({ version: APP.version, build }) + '\n');
+ },
+ };
+}
+
export default defineConfig({
base,
- plugins: [appName()],
+ plugins: [appName(), buildId()],
build: {
target: 'es2022',
chunkSizeWarningLimit: 800,