diff --git a/engine/PROVENANCE.json b/engine/PROVENANCE.json index 139e81f..7ef558c 100644 --- a/engine/PROVENANCE.json +++ b/engine/PROVENANCE.json @@ -2,14 +2,14 @@ "schema": "cloudcell.om-engine-artifact.v1", "component": "om-engine-zig", "artifact": "engine/om_engine.wasm", - "size_bytes": 1439713, - "git_blob_sha1": "06c0e1189186a7efb606c1dde494b11608b8bb04", - "sha256": "48de5ad073c09573692feb46990ccc271cdba3e92b90d93ebcd2332cf18a5515", + "size_bytes": 1439857, + "git_blob_sha1": "7e25ccbe056a4fd881e212b66bd16c239f06f39b", + "sha256": "bba9178528c18a17430fd176f28bf93adf70566eff76b7493fc0b16d7e5f850c", "engine_repository": "cloudcell/om-engine-zig-dev", - "engine_commit": "ec66571a0a82b06ee421c3d4b2ac931d37874715", + "engine_commit": "156ca496a7b50816801c7cc46a47d54a7c081fd1", "engine_commit_verified": true, "source_provenance": "Matched local clean Zig repository build and git commit", - "ts_runtime_version": "ts_runtime 0.1.0 @ 0e50bc0 (synced 2026-11-24T04:32:43Z)", + "ts_runtime_version": "ts_runtime 0.1.0 @ 9564c6f (synced 2026-11-24T22:07:13Z)", "binary_license": "legal/ENGINE-BINARY-LICENSE.md", "third_party_notices": [ "legal/CORE-MATH-MIT.txt" diff --git a/engine/VERSION b/engine/VERSION index 100bccc..49e4403 100644 --- a/engine/VERSION +++ b/engine/VERSION @@ -1 +1 @@ -ts_runtime 0.1.0 @ 0e50bc0 (synced 2026-11-24T04:32:43Z) +ts_runtime 0.1.0 @ 9564c6f (synced 2026-11-24T22:07:13Z) diff --git a/engine/om_engine.wasm b/engine/om_engine.wasm index 06c0e11..7e25ccb 100755 Binary files a/engine/om_engine.wasm and b/engine/om_engine.wasm differ diff --git a/shared/messages.ts b/shared/messages.ts index b652f6b..7af9d9d 100644 --- a/shared/messages.ts +++ b/shared/messages.ts @@ -173,6 +173,8 @@ export interface UiOptions { docking?: boolean; /** Experimental panels: Performance Watch and Timeline in the View menu. Off by default. */ advancedPanels?: boolean; + /** Contextual first-use tips (T-tips). Managed in Tools → Options and Help → Show Tips. */ + showTips?: boolean; } /** What a fresh install uses — shown next to each control in the Options dialog. */ @@ -182,6 +184,7 @@ export const DEFAULT_OPTIONS: Required = { assistant: true, docking: true, advancedPanels: false, + showTips: true, }; /** Aggregate-sign choices offered in Tools → Options. The first entry is the default. */ @@ -193,11 +196,22 @@ export const AGGREGATE_SIGN_CHOICES: { value: string; label: string }[] = [ { value: "#", label: "# Hash" }, ]; -/** Everything the webview persists. `saveUiState` params: `{ state: UiState }`. */ +/** Contextual-tip memory: ids the user acknowledged with "Got it". Dismissed-but-unacknowledged + * tips are absent, so they may re-fire — `seen` is deliberately small. */ +export interface UiTips { + seen?: string[]; + /** First-run guided tour completed/skipped/declined — suppresses the invite. */ + tourDone?: boolean; +} + +/** Everything the webview persists. `saveUiState` params: `{ state: UiState }`. + * NOTE: every field added here must also gain a whitelist branch in the host's + * `sanitizeUiState` (src/uiState.ts) or it is silently stripped in VS Code. */ export interface UiState { layout?: UiLayout; theme?: UiTheme; options?: UiOptions; + tips?: UiTips; } /** Name of the `` tag through which the VS Code host hands the saved UiState to a new webview diff --git a/src/uiState.ts b/src/uiState.ts index 2d691fd..6179f37 100644 --- a/src/uiState.ts +++ b/src/uiState.ts @@ -2,14 +2,22 @@ // The webview is the less trusted side, so the host re-validates instead of storing whatever object it is handed. // Pure, no `vscode` import. -import type { UiState, UiLayout, UiTheme } from "../shared/messages"; +import { AGGREGATE_SIGN_CHOICES } from "../shared/messages"; +import type { UiState, UiLayout, UiTheme, UiOptions, UiTips } from "../shared/messages"; /** Hard cap on the stored JSON (a real state is ~100 bytes). */ export const UI_STATE_MAX_BYTES = 4096; -const THEMES: readonly UiTheme[] = ["light", "dark"]; -const NUMBER_FIELDS: (keyof UiLayout)[] = ["leftDockWidth", "rulePanelHeight"]; -const BOOL_FIELDS: (keyof UiLayout)[] = ["leftCollapsed", "rulePanelCollapsed"]; +/** Cap on the serialized `tips` member alone — ~100+ tip ids, effectively unlimited + * for any real registry while staying well under UI_STATE_MAX_BYTES. */ +const TIPS_MAX_BYTES = 2048; +/** Cap on the serialized `dock` member — zone/tab layout is nested but stays small. */ +const DOCK_MAX_BYTES = 3072; +const TIP_ID_MAX_CHARS = 64; const MAX_PX = 20000; +const THEMES: readonly UiTheme[] = ["light", "dark"]; +const NUMBER_FIELDS: (keyof UiLayout)[] = ["leftDockWidth", "rightDockWidth", "rulePanelHeight"]; +const BOOL_FIELDS: (keyof UiLayout)[] = ["leftCollapsed", "rightCollapsed", "rulePanelCollapsed"]; +const OPTION_BOOL_FIELDS: (keyof UiOptions)[] = ["markHardvalues", "assistant", "docking", "advancedPanels", "showTips"]; /** A clean copy with only the known, valid fields, or null when nothing usable is left or the input is not an object. */ export function sanitizeUiState(input: unknown): UiState | null { @@ -26,8 +34,34 @@ export function sanitizeUiState(input: unknown): UiState | null { if (typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= MAX_PX) (clean as any)[k] = v; } for (const k of BOOL_FIELDS) if (typeof l[k] === "boolean") (clean as any)[k] = l[k]; + // The dock-zone layout is nested; bound it by size rather than deep-whitelisting its shape. + if (l.dock && typeof l.dock === "object" && !Array.isArray(l.dock) && JSON.stringify(l.dock).length <= DOCK_MAX_BYTES) + clean.dock = l.dock as UiLayout["dock"]; if (Object.keys(clean).length) out.layout = clean; } - if (!out.theme && !out.layout) return null; + const options = src.options; + if (options && typeof options === "object" && !Array.isArray(options)) { + const o = options as Record; + const clean: UiOptions = {}; + for (const k of OPTION_BOOL_FIELDS) if (typeof o[k] === "boolean") (clean as any)[k] = o[k]; + if (typeof o.aggregateSign === "string" && AGGREGATE_SIGN_CHOICES.some((c) => c.value === o.aggregateSign)) + clean.aggregateSign = o.aggregateSign; + if (Object.keys(clean).length) out.options = clean; + } + const tips = src.tips; + if (tips && typeof tips === "object" && !Array.isArray(tips)) { + const cleanTips: UiTips = {}; + const seen = (tips as Record).seen; + if (Array.isArray(seen)) { + const clean = seen.filter((s): s is string => typeof s === "string" && s.length > 0 && s.length <= TIP_ID_MAX_CHARS); + // Bound by serialized size, not entry count — drop oldest (FIFO) until it fits. + while (clean.length && JSON.stringify(clean).length > TIPS_MAX_BYTES) clean.shift(); + if (clean.length) cleanTips.seen = clean; + } + // tourDone is only meaningful when true; absent/false both mean "not done". + if ((tips as Record).tourDone === true) cleanTips.tourDone = true; + if (Object.keys(cleanTips).length) out.tips = cleanTips; + } + if (!out.theme && !out.layout && !out.options && !out.tips) return null; return JSON.stringify(out).length <= UI_STATE_MAX_BYTES ? out : null; } diff --git a/webview/app.ts b/webview/app.ts index be9df1c..87c3c41 100644 --- a/webview/app.ts +++ b/webview/app.ts @@ -4,6 +4,8 @@ import { AppShell } from "./components/appShell"; import { applyTheme, sanitizeTheme } from "./theme"; import { parseSession } from "../shared/session"; import { alertDialog } from "./components/dialogs"; +import { initTips } from "./tips"; +import { initTour } from "./tour"; import type { Transport } from "./transport"; import "./styles.css"; @@ -35,6 +37,11 @@ export async function mount(root: HTMLElement, opts: MountOptions): Promise { if (status === "connected") { diff --git a/webview/components/appShell.ts b/webview/components/appShell.ts index 66c88cd..60f01ab 100644 --- a/webview/components/appShell.ts +++ b/webview/components/appShell.ts @@ -5,6 +5,8 @@ import { makeBundle, BUNDLE_MODEL_MEMBER, BUNDLE_EXT } from "../../shared/omz"; import { applyTheme, currentTheme } from "../theme"; import { el, clear, ICONS, NOT_IN_MVP_TITLE } from "../dom"; import { materialIconSvg as msym, brandIconSvg, type MaterialIcon } from "../menuIcons"; +import { tipsEnabled, setTipsEnabled, resetTips } from "../tips"; +import { startTour } from "../tour"; import { ModelBrowser } from "./modelBrowser"; import { MultilevelGrid } from "./multilevelGrid"; import { RulePanel } from "./rulePanel"; @@ -437,7 +439,7 @@ export class AppShell { // ---- Menu bar ---- private menuBar(): HTMLElement { - const mb = el("div", { class: "menubar" }); + const mb = el("div", { class: "menubar", "data-tour": "menubar" }); // Item lists are produced on each open so checked/disabled states reflect current store state. const menus: [string, () => MenuItem[]][] = [ ["File", () => this.fileMenuItems()], @@ -450,7 +452,7 @@ export class AppShell { ["Help", () => this.helpMenuItems()], ]; for (const [label, getItems] of menus) { - const mi = el("div", { class: "menu-item" }, [label]); + const mi = el("div", { class: "menu-item", ...(label === "Help" ? { "data-tour": "help-menu" } : {}) }, [label]); let dd = this.buildMenuList(getItems(), "menu-dropdown"); mi.appendChild(dd); const open = () => { @@ -730,7 +732,7 @@ export class AppShell { } private async openOptions() { - const result = await optionsDialog(this.store.state.options); + const result = await optionsDialog(this.store.state.options, () => resetTips()); if (result) this.store.setOptions(result); } @@ -755,6 +757,10 @@ export class AppShell { ...(this.store.api.supportsNativeExternalLinks ? [{ icon: msym("water_drop"), label: "Welcome Screen…", fn: () => window.dispatchEvent(new CustomEvent("om-show-welcome")) } as MenuItem] : []), + { icon: msym("menu_book"), label: "Take the Tour…", fn: () => startTour() }, + { icon: msym("info"), label: "Show Tips", checked: tipsEnabled(), fn: () => setTipsEnabled(!tipsEnabled()) }, + { icon: msym("refresh"), label: "Reset Tips…", fn: () => resetTips() }, + { sep: true }, { icon: msym("info"), label: "About OM Core", fn: () => alertDialog("About OM Core", "OM Core — multidimensional modeling engine GUI.\nVSCode/VSCodium extension connecting to the om-core runtime.\n\nhttps://cloudcell.github.io/om-docs/") }, ]; } @@ -947,6 +953,8 @@ export class AppShell { let skips: string[] = []; try { skips = await this.store.applySession(session, sessionPath); } catch (e: any) { await alertDialog("Open Session", e?.message || String(e)); return; } + // example-opened fires only on real apply success — errors are swallowed above (F4). + if (sessionPath?.startsWith("om-example:")) this.store.emitUiEvent("example-opened"); if (session.theme && session.theme !== currentTheme()) { applyTheme(session.theme); this.store.api.updateUiState({ theme: session.theme }); @@ -991,6 +999,7 @@ export class AppShell { const res = await this.store.api.saveBinaryFile(b.suggested, b.bytes).catch(() => null); if (res?.downloaded) await alertDialog("Saved to Downloads", "Your browser doesn't support choosing a save location — the bundle was downloaded to your default Downloads folder."); + if (res) this.store.emitUiEvent("bundle-saved"); } /** File → Share Session… (web build only — the menu item is gated on diff --git a/webview/components/dialogs.ts b/webview/components/dialogs.ts index 226461b..242f0d1 100644 --- a/webview/components/dialogs.ts +++ b/webview/components/dialogs.ts @@ -456,7 +456,7 @@ export function formDialog(title: string, fields: FormField[], opts: { okLabel?: /** Tools → Options… — display preferences, persisted in UiState. Each row shows * what the default setup uses; "Restore defaults" resets every control. * Resolves with the full options map on OK, or null on Cancel/Escape/outside click. */ -export function optionsDialog(current: Required): Promise { +export function optionsDialog(current: Required, onResetTips?: () => void): Promise { return new Promise((resolve) => { const ov = ensureOverlay(); clear(ov); @@ -537,6 +537,27 @@ export function optionsDialog(current: Required): Promise { onResetTips(); }); + dlg.appendChild(tipsReset); + } + // — Buttons — const btnRow = el("div", { style: { display: "flex", justifyContent: "flex-end", gap: "8px" } }) as HTMLElement; const resetBtn = el("button", { style: { @@ -561,6 +582,7 @@ export function optionsDialog(current: Required): Promise { @@ -569,7 +591,7 @@ export function optionsDialog(current: Required): Promise { closeOverlay(); resolve(v); }; cancelBtn.addEventListener("click", () => done(null)); - okBtn.addEventListener("click", () => done({ markHardvalues: hvCb.checked, aggregateSign: signSelect.value, assistant: aiCb.checked, docking: dockCb.checked, advancedPanels: advCb.checked })); + okBtn.addEventListener("click", () => done({ markHardvalues: hvCb.checked, aggregateSign: signSelect.value, assistant: aiCb.checked, docking: dockCb.checked, advancedPanels: advCb.checked, showTips: tipsCb.checked })); dlg.addEventListener("keydown", (e) => { if (e.key === "Escape") { e.preventDefault(); done(null); } }); diff --git a/webview/components/dockZone.ts b/webview/components/dockZone.ts index edbec10..b3b9d52 100644 --- a/webview/components/dockZone.ts +++ b/webview/components/dockZone.ts @@ -33,7 +33,7 @@ export class DockZone { constructor(readonly id: DockZoneId, private ctl: DockController) { this.el = el("div", { class: `dock-zone dock-${id}` }); - this.tabsEl = el("div", { class: "lower-tabs dock-tabs" }); + this.tabsEl = el("div", { class: "lower-tabs dock-tabs", "data-tour": "dock-tabs" }); this.bodyEl = el("div", { class: "dock-body" }); this.el.append(this.tabsEl, this.bodyEl); } diff --git a/webview/components/statusBar.ts b/webview/components/statusBar.ts index cb9ef36..d9d4d1c 100644 --- a/webview/components/statusBar.ts +++ b/webview/components/statusBar.ts @@ -79,7 +79,7 @@ export class StatusBar { } render(): HTMLElement { - const bar = el("div", { class: "statusbar" }); + const bar = el("div", { class: "statusbar", "data-tour": "statusbar" }); const focusPath = el("span", { class: "sb-section" }, ["OM Core"]); const sep1 = el("span", { class: "sb-sep" }, ["|"]); const cellAddr = el("span", { class: "sb-section" }, ["—"]); diff --git a/webview/components/viewGroups.ts b/webview/components/viewGroups.ts index 91bbbdf..7dab699 100644 --- a/webview/components/viewGroups.ts +++ b/webview/components/viewGroups.ts @@ -14,7 +14,7 @@ import { ViewTabDrag } from "./viewTabDrag"; * The tree is rebuilt ONLY when the group structure changes (signature compare) — * grids and rule panels keep living DOM/subscriptions across ordinary notifies. */ export class ViewArea { - private root = el("div", { class: "view-area" }); + private root = el("div", { class: "view-area", "data-tour": "view-area" }); private grids = new Map(); private drag: ViewTabDrag; private sig = ""; @@ -139,6 +139,7 @@ export class ViewArea { const rp = new RulePanel(this.store, gid); const rules = rp.render(); rules.classList.add("va-rules"); + rules.dataset.tour = "rules"; const layout = this.store.state.layout; const sep = new Splitter({ axis: "y", grow: -1, min: 60, collapsedSize: 28, diff --git a/webview/state.ts b/webview/state.ts index 4793e92..3193781 100644 --- a/webview/state.ts +++ b/webview/state.ts @@ -183,6 +183,11 @@ export class Store { }; api: OmApi; private listeners = new Set(); + private uiEventListeners = new Set<(name: string) => void>(); + /** Set for the whole duration of applySession — restored panes/tabs/subpanes are not + * "first use". UI-event subscribers check it to suppress tips mid-restore (T-tips). */ + private restoring = false; + isRestoring() { return this.restoring; } /** Why the in-flight notify() is running — a subscriber whose rebuild is expensive, * or whose DOM may be the target of a press in progress, can skip a reason that * cannot change what it renders. "focus" = only focusedGroup moved. Rebuilding @@ -222,6 +227,20 @@ export class Store { this.notifyReason = null; } + /** Typed UI-action events for app-level observers (T-tips onboarding): a GUI-local + * signal channel (a-07 permits it for UI-only concerns), not the engine MessageBus. + * Kebab-case names; `emitUiEvent` is fire-and-forget like `notify()` — a throwing + * subscriber is logged and dropped, it must never unwind into the caller. */ + onUiEvent(fn: (name: string) => void): () => void { + this.uiEventListeners.add(fn); + return () => this.uiEventListeners.delete(fn); + } + emitUiEvent(name: string) { + for (const l of [...this.uiEventListeners]) { + try { l(name); } catch (e) { console.error("uiEvent subscriber failed", e); } + } + } + /** While set, every subscribe() also lands in this bag. See captureSubscriptions(). */ private capture: Set<() => void> | null = null; @@ -548,6 +567,7 @@ export class Store { this.state.viewGroups.push(ng); this.splitGroupNode(targetGid, side, ng.id); this.state.focusedGroup = ng.id; + this.emitUiEvent("view-split"); } if (src && src.tabs.length === 0 && this.state.viewGroups.length > 1) this.removeGroup(src.id); this.syncViewMirror(); @@ -594,6 +614,7 @@ export class Store { if (!g) return; g.rulesOpen = !g.rulesOpen; this.notify(); + if (g.rulesOpen) this.emitUiEvent("rules-opened"); } groupRulesOpen(gid?: string): boolean { @@ -1031,6 +1052,7 @@ export class Store { async loadWorkspaceFile(path: string) { try { await this.api.loadWorkspace(path); } catch (e: any) { await alertDialog("Load failed", e?.message || String(e)); return; } await this.resetWorkspaceUi(path, true); + if (/^om-example:/.test(path)) this.emitUiEvent("example-opened"); } /** The host launched a new runtime since this page was last connected (Stop Runtime, then Start Runtime): what the page @@ -1130,8 +1152,14 @@ export class Store { /** Load the descriptor's model then overlay pane/tab/subpane/chip/selection/scroll * state. Never dirties the model; every unknown ID is skipped and reported. Returns * the skip notes (empty = fully applied). Throws on fatal model-load failures — - * the caller shows the alert. */ + * the caller shows the alert. `restoring` marks the whole duration (T-tips). */ async applySession(session: SessionDescriptor, sessionPath: string | null): Promise { + this.restoring = true; + try { return await this.applySessionBody(session, sessionPath); } + finally { this.restoring = false; } + } + + private async applySessionBody(session: SessionDescriptor, sessionPath: string | null): Promise { const skips: string[] = []; const target = this.sessionModelTarget(session, sessionPath); // A URL reaches the engine only in the browser host (fetch → bytes); the @@ -1341,6 +1369,7 @@ export class Store { toggleDock(name: keyof AppState["dockVisible"]) { this.state.dockVisible[name] = !this.state.dockVisible[name]; this.notify(); + if (name === "rules" && this.state.dockVisible.rules) this.emitUiEvent("rules-opened"); } // ---- Dock-zone layout (T-dock) ---- diff --git a/webview/styles.css b/webview/styles.css index f815ee2..ad702d2 100644 --- a/webview/styles.css +++ b/webview/styles.css @@ -858,6 +858,58 @@ body.splitter-dragging-y, body.splitter-dragging-y * { cursor: row-resize !impor } .ctx-item:hover { background: var(--selection); color: #fff; } .ctx-item.disabled { color: var(--text-disabled); cursor: default; } + +/* First-use tip toast (T-tips): non-modal, bottom-right; acknowledged only via "Got it". */ +.om-tip { + position: fixed; right: 16px; bottom: 16px; z-index: 2500; + display: flex; align-items: center; gap: 8px; + max-width: 360px; padding: 10px 12px; + background: var(--popup-bg); color: var(--text); + border: 1px solid var(--border-strong); border-radius: 10px; + box-shadow: var(--dlg-shadow); font-size: 13px; line-height: 1.4; + animation: om-tip-in .18s ease-out; +} +@keyframes om-tip-in { from { opacity: 0; transform: translateY(6px); } } +@media (prefers-reduced-motion: reduce) { .om-tip { animation: none; } } +.om-tip-icon { flex: none; display: flex; color: var(--accent); } +.om-tip-icon svg { width: 16px; height: 16px; } +.om-tip-text { flex: 1; } +.om-tip-btn { + flex: none; font: inherit; font-size: 12px; padding: 4px 10px; + border: 1px solid var(--border-strong); border-radius: 6px; + background: var(--dlg-btn-bg); color: var(--text); cursor: pointer; white-space: nowrap; +} +.om-tip-btn:hover { background: var(--hover-bg); } +.om-tip-btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; } +.om-tip-btn.primary:hover { filter: brightness(1.08); } +.om-tip-close { + flex: none; border: none; background: none; padding: 0 2px; + color: var(--text-muted); font-size: 15px; line-height: 1; cursor: pointer; +} +.om-tip-close:hover { color: var(--text); } + +/* ---- First-run guided tour: anchored callouts + target ring (non-modal) ---- */ +.om-tour { + position: fixed; z-index: 2600; + width: 280px; padding: 12px 14px; + background: var(--popup-bg); color: var(--text); + border: 1px solid var(--border-strong); border-radius: 10px; + box-shadow: var(--dlg-shadow); font-size: 13px; line-height: 1.4; + animation: om-tip-in .18s ease-out; +} +.om-tour.centered { left: 50%; top: 50%; transform: translate(-50%, -50%); } +@media (prefers-reduced-motion: reduce) { .om-tour { animation: none; } } +.om-tour-title { font-weight: 600; margin-bottom: 4px; } +.om-tour-foot { display: flex; align-items: center; gap: 6px; margin-top: 10px; } +.om-tour-count { flex: 1; color: var(--text-muted); font-size: 11px; } +.om-tour-skip { + border: none; background: none; padding: 4px 6px; + color: var(--text-muted); font: inherit; font-size: 12px; cursor: pointer; +} +.om-tour-skip:hover { color: var(--text); } +/* The highlight IS the ring — a static accent outline, no backdrop, no pulse. */ +.om-tour-mark { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 4px; } +.om-tour-invite { max-width: 460px; } .ctx-item.disabled:hover { background: transparent; color: var(--text-disabled); } .ctx-sep { height: 1px; background: var(--border); margin: 2px 0; } .ctx-submenu { position: relative; } diff --git a/webview/tips.ts b/webview/tips.ts new file mode 100644 index 0000000..329b323 --- /dev/null +++ b/webview/tips.ts @@ -0,0 +1,207 @@ +/** Contextual first-use tips (T-tips): a small non-modal toast that fires once per + * trigger until acknowledged with "Got it". Close/timer hides without marking seen, + * so nothing educational is permanently lost. Registry is append-only — an id is + * forever; renaming re-shows the tip to everyone. + * + * TipQueue is the DOM-free core (seen memory + one-visible/one-pending queue), + * unit-testable in plain Node; TipManager adds suppression checks, persistence, + * and the toast render. */ + +import type { Store } from "./state"; +import { el } from "./dom"; +import { materialIconSvg } from "./menuIcons"; + +export interface Tip { id: string; text: string; } + +export const TIPS: readonly Tip[] = [ + { id: "example-opened", text: "Explore the Rules panel to see how this model calculates its results." }, + { id: "view-split", text: "You can inspect different parts of your model side by side." }, + { id: "rules-opened", text: "Select a rule to inspect or edit the model's calculations." }, + { id: "bundle-saved", text: "Your model and workspace layout are saved together in an .omz file." }, +]; +const TIP_IDS = new Set(TIPS.map((t) => t.id)); +const TEXT_BY_ID = new Map(TIPS.map((t) => [t.id, t.text])); + +/** Seen memory + queue policy: at most one visible and one pending. push() dedupes + * (same id visible, pending, or already seen). resolve() marks seen only on + * acknowledgement; a pending tip that became seen while queued is discarded stale. */ +export class TipQueue { + private seen = new Set(); + private visible: string | null = null; + private pending: string | null = null; + + constructor(seen?: Iterable) { if (seen) for (const id of seen) this.seen.add(id); } + + isSeen(id: string) { return this.seen.has(id); } + get seenIds(): string[] { return [...this.seen]; } + get current(): string | null { return this.visible; } + get queued(): string | null { return this.pending; } + clearSeen() { this.seen.clear(); } + + /** Returns the id to render now, or null when queued/absorbed. */ + push(id: string): string | null { + if (this.seen.has(id) || this.visible === id || this.pending === id) return null; + if (this.visible) { this.pending = id; return null; } + this.visible = id; + return id; + } + + /** The visible tip ended: ack marks it seen. Returns the pending candidate to + * promote (caller re-checks suppression before rendering), or null. */ + resolve(ack: boolean): string | null { + if (!this.visible) return null; + if (ack) this.seen.add(this.visible); + this.visible = null; + const next = this.pending; + this.pending = null; + if (!next) return null; + if (this.seen.has(next)) return null; + this.visible = next; + return next; + } + + /** Drops the visible tip without marking and discards the queue (disable path). */ + cancel() { this.visible = null; this.pending = null; } +} + +const AUTO_DISMISS_MS = 8000; + +/** Onboarding-wide suppression probes shared by tips and the tour: never over + * the welcome gate, during session restore, or while any view is still loading. */ +export function suppressedForOnboarding(store: Store): boolean { + if (store.isRestoring()) return true; + if (typeof document !== "undefined" && document.querySelector(".welcome-overlay")) return true; + return Object.values(store.state.viewStates).some((v) => v.loading); +} + +/** Nested read-modify-write of `UiState.tips` — `updateUiState` shallow-merges + * top-level keys only, so the `seen` writer (tips) and the `tourDone` writer + * (tour) must go through one merge helper or they wipe each other. */ +export function updateTipsState(store: Store, patch: { seen?: string[]; tourDone?: boolean }): void { + const cur = store.api.loadUiState()?.tips ?? {}; + store.api.updateUiState({ tips: { ...cur, ...patch } }); +} + +/** Extra suppression injected by the tour module (tour running or invite up) + * — kept as a hook rather than an import so tips.ts has no dependency on tour.ts. */ +let extraSuppression: (() => boolean) | null = null; +export function setTipSuppression(fn: (() => boolean) | null): void { extraSuppression = fn; } + +export class TipManager { + private queue: TipQueue; + private toast: HTMLElement | null = null; + private timer = 0; + private timerStart = 0; + private remaining = AUTO_DISMISS_MS; + private warned = false; + private unsub: (() => void) | null = null; + + constructor(private store: Store) { + this.queue = new TipQueue(store.api.loadUiState()?.tips?.seen); + this.unsub = store.onUiEvent((name) => { if (TIP_IDS.has(name)) this.show(name); }); + } + + dispose() { this.unsub?.(); this.unsub = null; this.teardown(); } + + enabled(): boolean { return this.store.state.options.showTips !== false; } + + setEnabled(on: boolean) { + this.store.setOptions({ showTips: on }); + if (!on) { this.queue.cancel(); this.teardown(); } + } + + /** Reset = fresh onboarding: clears seen tips AND the tour-done flag, so the + * invite re-fires next run ("show me everything again" semantics). */ + reset() { this.queue.clearSeen(); updateTipsState(this.store, { seen: [], tourDone: false }); } + + /** Drops the visible tip and the queue without marking seen — used when the + * tour starts so no two floating elements collide (T5). */ + dismiss() { this.queue.cancel(); this.teardown(); } + + /** Suppression (3e): shared onboarding probes + enabled + tour/invite gate. */ + private suppressed(): boolean { + if (!this.enabled()) return true; + if (suppressedForOnboarding(this.store)) return true; + if (extraSuppression?.()) return true; + return false; + } + + show(id: string) { + if (this.suppressed()) return; + const show = this.queue.push(id); + if (show) this.render(show); + } + + /** Got it / × / timer — only "Got it" marks seen. */ + private finish(ack: boolean) { + const next = this.queue.resolve(ack); + if (ack) this.persist(); + this.teardown(); + if (next && !this.suppressed()) this.render(next); + } + + private persist() { + const seen = this.queue.seenIds; + updateTipsState(this.store, { seen }); + // Transports swallow save errors — detect failure by read-back (P2). + const rb = this.store.api.loadUiState()?.tips?.seen; + if (!this.warned && (!Array.isArray(rb) || rb.length !== seen.length)) { + this.warned = true; + console.warn("tips: seen-state could not be persisted — tips reset when this session ends"); + } + } + + private render(id: string) { + this.teardown(); + const gotIt = el("button", { class: "om-tip-btn primary", onClick: () => this.finish(true) }, ["Got it"]); + const dontShow = el("button", { class: "om-tip-btn", title: "Turn off tips (Help → Show Tips re-enables)", + onClick: () => { this.setEnabled(false); } }, ["Don't show tips"]); + const close = el("button", { class: "om-tip-close", "aria-label": "Dismiss tip", title: "Dismiss — the tip may return", + onClick: () => this.finish(false) }, ["×"]); + this.toast = el("div", { class: "om-tip", role: "status", "aria-live": "polite", + onPointerenter: () => this.pause(), onPointerleave: () => this.resume(), + onFocusin: () => this.pause(), onFocusout: () => this.resume() }, [ + el("span", { class: "om-tip-icon", html: materialIconSvg("info") }), + el("span", { class: "om-tip-text" }, [TEXT_BY_ID.get(id) ?? id]), + gotIt, dontShow, close, + ]); + document.body.appendChild(this.toast); + this.startTimer(AUTO_DISMISS_MS); + } + + private teardown() { + this.pause(); + this.toast?.remove(); + this.toast = null; + } + + private startTimer(ms: number) { + this.remaining = ms; + this.timerStart = Date.now(); + this.timer = window.setTimeout(() => this.finish(false), ms); + } + private pause() { + if (!this.timer) return; + clearTimeout(this.timer); + this.timer = 0; + this.remaining -= Date.now() - this.timerStart; + } + private resume() { + if (this.timer || !this.toast) return; + this.startTimer(Math.max(500, this.remaining)); + } +} + +let mgr: TipManager | null = null; + +/** Called once at mount; subscribes the manager to store UI events. */ +export function initTips(store: Store): TipManager { + mgr?.dispose(); + mgr = new TipManager(store); + return mgr; +} +export function tipsEnabled(): boolean { return mgr?.enabled() ?? false; } +export function setTipsEnabled(on: boolean) { mgr?.setEnabled(on); } +export function resetTips() { mgr?.reset(); } +/** Drops any visible/queued tip without marking seen — the tour calls this on start. */ +export function dismissTip() { mgr?.dismiss(); } diff --git a/webview/tour.ts b/webview/tour.ts new file mode 100644 index 0000000..b2b4551 --- /dev/null +++ b/webview/tour.ts @@ -0,0 +1,273 @@ +/** First-run guided tour (tips v2): a separate, replayable sequence of anchored + * callouts — the deliberate-review channel to the contextual tips' + * trigger-moment one. Non-modal throughout: no backdrop, no input capture, + * Esc exits; the tour and tips never interleave (suppression hook in tips.ts). + * + * placeCallout() is the DOM-free placement core (flip-on-overflow + viewport + * clamp), unit-testable in plain Node like TipQueue. */ + +import type { Store } from "./state"; +import { el } from "./dom"; +import { materialIconSvg } from "./menuIcons"; +import { dismissTip, setTipSuppression, suppressedForOnboarding, updateTipsState } from "./tips"; + +export type Placement = "bottom" | "top" | "left" | "right"; + +export interface TourStep { + id: string; + anchor?: string; // data-tour value; absent → centered step + fallbackAnchor?: string; // used when the primary anchor is absent from the DOM + place?: Placement; // preferred side (default bottom) + title: string; + text: string; +} + +export const TOUR_STEPS: readonly TourStep[] = [ + { id: "welcome", title: "Welcome to OM Core", + text: "This is your model workspace — a live view of your data." }, + { id: "menus", anchor: "menubar", place: "bottom", title: "Menus", + text: "File opens models and bundles; View, Tools, and Help hold the rest." }, + { id: "views", anchor: "view-area", place: "top", title: "Views", + text: "Each tab is a live view into the model — drag a tab to split." }, + { id: "rules", anchor: "rules", fallbackAnchor: "view-area", place: "left", title: "Rules", + text: "Rules define how cells calculate — select one to inspect or edit it." }, + { id: "status", anchor: "statusbar", place: "top", title: "Engine status", + text: "The indicator shows the engine state and current selection." }, + { id: "help", anchor: "help-menu", place: "bottom", title: "That's it", + text: "Replay this tour anytime from Help → Take the Tour." }, +]; + +export interface RectLike { x: number; y: number; w: number; h: number } + +const GAP = 10; +const MARGIN = 8; + +/** Position a callout next to an anchor rect: preferred side first, flip through + * the remaining sides on overflow, clamp inside the viewport as a last resort. + * Pure — the DOM render just applies {x,y}. */ +export function placeCallout( + anchor: RectLike, + size: { w: number; h: number }, + preferred: Placement, + viewport: { w: number; h: number }, +): { x: number; y: number; placement: Placement } { + const at = (p: Placement): { x: number; y: number } => { + const cx = anchor.x + anchor.w / 2 - size.w / 2; + const cy = anchor.y + anchor.h / 2 - size.h / 2; + switch (p) { + case "bottom": return { x: cx, y: anchor.y + anchor.h + GAP }; + case "top": return { x: cx, y: anchor.y - size.h - GAP }; + case "right": return { x: anchor.x + anchor.w + GAP, y: cy }; + case "left": return { x: anchor.x - size.w - GAP, y: cy }; + } + }; + const fits = ({ x, y }: { x: number; y: number }) => + x >= MARGIN && y >= MARGIN && x + size.w <= viewport.w - MARGIN && y + size.h <= viewport.h - MARGIN; + const order = [preferred, "bottom", "top", "right", "left"] + .filter((p, i, a): p is Placement => a.indexOf(p) === i); + for (const p of order) { + const pos = at(p); + if (fits(pos)) return { ...pos, placement: p }; + } + const { x, y } = at(preferred); + return { + x: Math.min(Math.max(MARGIN, x), Math.max(MARGIN, viewport.w - MARGIN - size.w)), + y: Math.min(Math.max(MARGIN, y), Math.max(MARGIN, viewport.h - MARGIN - size.h)), + placement: preferred, + }; +} + +export class TourManager { + private stepIndex = -1; + private callout: HTMLElement | null = null; + private markedEl: HTMLElement | null = null; + private inviteEl: HTMLElement | null = null; + private invitePoll = 0; + private startPoll = 0; + private onResize = () => { if (this.active()) this.render(); }; + + constructor(private store: Store) {} + + active(): boolean { return this.stepIndex >= 0; } + inviteVisible(): boolean { return this.inviteEl !== null; } + + /** Help → Take the Tour… / invite accept. Dismisses any visible tip first + * (two floating elements must never collide); while onboarding suppression + * is up (welcome gate, restore, views loading) the request retries briefly + * rather than appearing over a modal. */ + start() { + if (this.active()) return; + dismissTip(); + if (suppressedForOnboarding(this.store)) { this.queueStart(); return; } + this.begin(0); + } + + private queueStart() { + if (this.startPoll) return; + let tries = 0; + this.startPoll = window.setInterval(() => { + if (this.active() || ++tries > 40) { window.clearInterval(this.startPoll); this.startPoll = 0; return; } + if (suppressedForOnboarding(this.store)) return; + window.clearInterval(this.startPoll); + this.startPoll = 0; + this.begin(0); + }, 500); + } + + private begin(i: number) { + this.hideInvite(); + this.stepIndex = i; + window.addEventListener("resize", this.onResize); + this.render(); + } + + /** Completion and skip both persist tourDone — a skipped tour is a declined + * tour; replay stays one menu click away, so there is no resume state. */ + private finish() { + this.stepIndex = -1; + window.removeEventListener("resize", this.onResize); + this.teardownDom(); + updateTipsState(this.store, { tourDone: true }); + } + + private next() { + if (this.stepIndex >= TOUR_STEPS.length - 1) this.finish(); + else { this.stepIndex++; this.render(); } + } + + private prev() { if (this.stepIndex > 0) { this.stepIndex--; this.render(); } } + + private anchorEl(step: TourStep): HTMLElement | null { + if (!step.anchor) return null; + const primary = document.querySelector(`[data-tour="${step.anchor}"]`); + if (primary) return primary as HTMLElement; + if (step.fallbackAnchor) + return document.querySelector(`[data-tour="${step.fallbackAnchor}"]`) as HTMLElement | null; + return null; + } + + private render() { + this.teardownDom(); + const step = TOUR_STEPS[this.stepIndex]; + const anchor = this.anchorEl(step); + if (anchor) { anchor.classList.add("om-tour-mark"); this.markedEl = anchor; } + + const n = this.stepIndex, total = TOUR_STEPS.length, last = n === total - 1; + const nextBtn = el("button", { class: "om-tip-btn primary", onClick: () => this.next() }, + [last ? "Done" : "Next"]); + const backBtn = el("button", { class: "om-tip-btn", onClick: () => this.prev(), ...(n === 0 ? { disabled: true } : {}) }, + ["Back"]); + const skipBtn = el("button", { class: "om-tour-skip", onClick: () => this.finish() }, ["Skip tour"]); + + this.callout = el("div", { + class: "om-tour" + (anchor ? "" : " centered"), + role: "dialog", "aria-modal": "false", "aria-label": step.title, tabindex: "-1", + onKeydown: (e: KeyboardEvent) => { + if (e.key === "ArrowRight") { e.preventDefault(); this.next(); } + else if (e.key === "ArrowLeft") { e.preventDefault(); this.prev(); } + else if (e.key === "Escape") { e.preventDefault(); this.finish(); } + }, + }, [ + el("div", { class: "om-tour-title" }, [step.title]), + el("div", { class: "om-tour-text" }, [step.text]), + el("div", { class: "om-tour-foot" }, [ + el("span", { class: "om-tour-count" }, [`${n + 1} / ${total}`]), + skipBtn, backBtn, nextBtn, + ]), + ]); + document.body.appendChild(this.callout); + + if (anchor) { + const r = anchor.getBoundingClientRect(); + const c = this.callout.getBoundingClientRect(); + const pos = placeCallout( + { x: r.x, y: r.y, w: r.width, h: r.height }, + { w: c.width, h: c.height }, + step.place ?? "bottom", + { w: window.innerWidth, h: window.innerHeight }, + ); + this.callout.style.left = `${pos.x}px`; + this.callout.style.top = `${pos.y}px`; + this.callout.dataset.placement = pos.placement; + } + nextBtn.focus(); + } + + private teardownDom() { + this.callout?.remove(); + this.callout = null; + this.markedEl?.classList.remove("om-tour-mark"); + this.markedEl = null; + } + + /** First-run invite: a .om-tip-shaped toast rendered OUTSIDE TipQueue (the + * queue's seen-memory must never record the invite — tourDone is its own + * fact). Re-shown each run until Take the tour / Don't ask again. */ + maybeInvite() { + if (this.inviteEl || this.active()) return; + if (this.store.api.loadUiState()?.tips?.tourDone) return; + if (this.store.state.options.showTips === false) return; + if (suppressedForOnboarding(this.store)) { this.pollInvite(); return; } + + this.inviteEl = el("div", { class: "om-tip om-tour-invite", role: "status", "aria-live": "polite" }, [ + el("span", { class: "om-tip-icon", html: materialIconSvg("menu_book") }), + el("span", { class: "om-tip-text" }, ["New here? Take a 30-second tour."]), + el("button", { class: "om-tip-btn primary", onClick: () => this.start() }, + ["Take the tour"]), + el("button", { class: "om-tip-btn", onClick: () => this.hideInvite() }, + ["Later"]), + el("button", { class: "om-tip-btn", title: "Don't ask again (Help → Take the Tour… still works)", + onClick: () => { updateTipsState(this.store, { tourDone: true }); this.hideInvite(); } }, + ["Don't ask again"]), + ]); + document.body.appendChild(this.inviteEl); + } + + /** The welcome gate can sit up for a while — re-check once a second for up + * to two minutes, then give up for this run (invited again next run). */ + private pollInvite() { + if (this.invitePoll) return; + let tries = 0; + this.invitePoll = window.setInterval(() => { + if (++tries > 120 || this.inviteEl || this.active() + || this.store.api.loadUiState()?.tips?.tourDone + || this.store.state.options.showTips === false) { + window.clearInterval(this.invitePoll); + this.invitePoll = 0; + return; + } + if (suppressedForOnboarding(this.store)) return; + window.clearInterval(this.invitePoll); + this.invitePoll = 0; + this.maybeInvite(); + }, 1000); + } + + private hideInvite() { this.inviteEl?.remove(); this.inviteEl = null; } + + dispose() { + window.clearInterval(this.invitePoll); + window.clearInterval(this.startPoll); + this.invitePoll = 0; + this.startPoll = 0; + this.stepIndex = -1; + window.removeEventListener("resize", this.onResize); + this.teardownDom(); + this.hideInvite(); + } +} + +let mgr: TourManager | null = null; + +/** Called once at mount, beside initTips: registers the tour/invite suppression + * gate with the tips channel and fires the first-run invite. */ +export function initTour(store: Store): TourManager { + mgr?.dispose(); + mgr = new TourManager(store); + setTipSuppression(() => (mgr?.active() || mgr?.inviteVisible()) ?? false); + mgr.maybeInvite(); + return mgr; +} + +export function startTour() { mgr?.start(); } +export function tourActive(): boolean { return mgr?.active() ?? false; }