diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ac3c3b..a1fece9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,64 @@ All notable changes to this project are documented here. Format: [Keep a Changel ### Added +- **Two indicator views, one button** (31 Oct). The operator picked both mock-ups and kept both, with Quick as the + default. + - **Quick** (`picker.js`) is a dropdown under the Indicators button: + - type straight away, and search covers LuxAlgo scripts and built-ins together; initials count, so "rsi" finds + Relative Strength Index first; + - categories on the left, yours first (Recent, Favourites, On chart), then the library's families, then the + built-ins; + - results in the middle, and a preview with the picture and the write-up's first lines on the right; + - keyboard: ↑ ↓ move, ↵ runs, → opens Details, Esc closes; + - in a narrow Hermes pane the categories become chips and the preview stays, as a strip above the list. + - **Panel** (`drawer.js`) is the slide-in panel, reorganised: + - "On chart" first, then "Recently used", then all scripts; + - two-line names, family as a coloured tag, a ☆ that shows only when it means something; + - search matches highlighted, and the same keys as Quick. + - **The switch.** Each view has a Quick | Panel switch, and the choice is remembered per browser. The narrow + pane's Scripts button follows it too. + - **Wording.** A LuxAlgo script says **Run**: one at a time, it replaces the last one. A built-in says **Add**: + it stacks. + - **Shared logic.** The dropdown owns no data and no actions: it reads the drawer's rows and acts through the + drawer, so a run is the same run from either view, and the agent's `indicators` door still drives the panel. + - **Every built-in has a real preview.** Vela ships no picture for its 77 built-ins, so each preview is the study + itself: its own descriptor's `compute()` with default settings, on the open chart's last bars. Overlays (moving + averages, Bollinger Bands, SuperTrend, ZigZag…) are drawn over the candles; oscillators (RSI, MACD, Stochastic, + Aroon…) get a pane under them; Volume and the volume profile come from the candles. The previews show in + Quick's preview pane and as each built-in's tile in the Panel. Nothing is fetched. LuxAlgo scripts keep the + picture from LuxAlgo's catalogue. + - **The preview is the focus, and says what the study is for.** The dropdown is larger (up to 880 × 540), the + preview column is 300–360 px wide and its picture 236 px tall. Under the name, one plain sentence under + "What it's for": each of the 77 built-ins has its own (`PURPOSE` in `picker.js`, e.g. RSI "Measures momentum + on a 0–100 scale; above 70 is often read as overbought and below 30 as oversold."), and a LuxAlgo script + shows the first sentence of its own write-up. The same lines feed search in both views, so "overbought" finds + RSI, Stochastic, Williams %R and Money Flow Index. + - Pinned by `test_indicator_views.py`. Verified in Chromium at 1280 and 620 px, dark and light: open, search, + keyboard run, Recent and On chart filling in, a built-in added, Esc and click-away, and the switch both ways + surviving a reload. + +### Fixed + +- **The scripts list behind Indicators** (31 Oct). Six faults from a screenshot review: + - **A row whose preview picture failed collapsed.** The `` was deleted, the row's grid shifted one + column left, and the name landed in the 52 px picture slot ("Indic…"). That is every row without a + catalogue picture, and every row offline. The picture is now swapped for a tile with the name's + first letter, and each part of a row owns its grid column. + - **Built-in rows** had the ƒ in the corner of its tile, and their Run button sat 12 px left of every + other Run. Both are aligned now. + - **The detail view said only "Failed / No live MCP session".** It now says the LuxAlgo Library isn't + connected, what that means, and offers Try again. The server's message stays, smaller. + - **The search box always said "Search 800 scripts".** The number is gone. + - **The family chips were cut at the edge** with no sign there were more. A fade marks the side that + scrolls, and the mouse wheel scrolls them. + - **The footer's theme switch** was a tiny dim ◐ that read as a broken glyph. It is now the sun/moon + icon the Edge Stats sheet uses, on a 28 px target. + + Pinned by `test_lib_drawer_polish.py`. Verified in Chromium with a third of the previews failing: every + name gets the same width and every Run lines up, in dark and light. + +### Added + - **`AGENTS.md`: give an agent the repo link and it installs the plugin** (30 Oct). A file written for AI agents and signposted at the top of the README ("If you are an AI agent ..."). It covers: - telling the user what will happen, before running anything; diff --git a/console/backend/tests/test_indicator_views.py b/console/backend/tests/test_indicator_views.py new file mode 100644 index 0000000..89078ae --- /dev/null +++ b/console/backend/tests/test_indicator_views.py @@ -0,0 +1,188 @@ +"""Two views of the indicators, one door (31 Oct). + +The operator picked both mock-ups and kept both: the quick-add dropdown ("Quick", picker.js) is what +the Indicators button opens by default, and the slide-in panel ("Panel", drawer.js) is the other view. +Each carries a switch to the other, and the choice is remembered. Neither owns data or actions: the +dropdown reads the drawer's rows and acts through the drawer, so a run is the same run from either. +""" + +import re +import unittest +from pathlib import Path + +FRONT = Path(__file__).resolve().parents[2] / "frontend" +PICKER = (FRONT / "picker.js").read_text(encoding="utf-8") +DRAWER = (FRONT / "drawer.js").read_text(encoding="utf-8") +WS = (FRONT / "workspace.js").read_text(encoding="utf-8") +APP = (FRONT / "app.js").read_text(encoding="utf-8") +HTML = (FRONT / "index.html").read_text(encoding="utf-8") +CSS = (FRONT / "styles.css").read_text(encoding="utf-8") + + +class OneDoorTwoViews(unittest.TestCase): + def test_the_picker_loads_after_the_drawer(self): + self.assertLess(HTML.index('src="./drawer.js"'), HTML.index('src="./picker.js"')) + + def test_the_indicators_button_opens_the_chosen_view(self): + self.assertIn("window.taIndicators.toggle()", WS) + self.assertIn("window.libDrawer.toggle()", WS, "without picker.js the panel is still the door") + + def test_quick_is_the_default(self): + self.assertIn("read(VIEW_KEY, 'quick') === 'panel' ? 'panel' : 'quick'", PICKER) + + def test_the_choice_is_remembered(self): + self.assertIn("const VIEW_KEY = 'ta-indicators-view'", PICKER) + self.assertIn("write(VIEW_KEY", PICKER) + + def test_each_view_switches_to_the_other(self): + self.assertIn('data-view="panel"', PICKER) + self.assertIn("switchToPanel", PICKER) + self.assertIn('data-view="quick"', HTML) + self.assertIn("window.taIndicators.setView('quick')", DRAWER) + + def test_the_narrow_panes_scripts_button_follows_the_choice_too(self): + block = DRAWER[DRAWER.index("if (fallback) fallback.addEventListener('click'"):][:300] + self.assertIn("window.taIndicators.toggle()", block) + + +class TheDropdownOwnsNothing(unittest.TestCase): + def test_rows_and_actions_come_from_the_drawer(self): + self.assertIn("window.libDrawer.items()", PICKER) + self.assertIn("window.libDrawer.act(", PICKER) + self.assertNotIn("api('/api/source'", PICKER, "a run must go through the drawer's one run path") + self.assertIn("items, act,", DRAWER) + + def test_the_drawer_still_writes_no_storage(self): + # favourites have one store (app.js); recents and the view live in picker.js + self.assertNotIn("localStorage.setItem", DRAWER) + + +class WhatItShows(unittest.TestCase): + def test_yours_first(self): + for cat in ("'recent'", "'fav'", "'on'", "'all'", "'builtin'"): + self.assertIn(cat, PICKER) + self.assertIn("st.cat = recent().length ? 'recent' : 'all'", PICKER) + + def test_a_run_is_remembered_for_recent(self): + self.assertIn("ti().noteRecent(slug)", DRAWER) + self.assertIn("noteRecent('builtin:' + nat.type)", DRAWER) + + def test_the_panel_groups_on_chart_and_recent_first(self): + for label in ("'On chart · '", "'Recently used'", "'All scripts'"): + self.assertIn(label, DRAWER) + + def test_initials_find_the_classic(self): + # "rsi" is Relative Strength Index before Connors RSI + self.assertIn("initials(x.name) === q.replace", PICKER) + + def test_matches_are_highlighted_safely(self): + self.assertIn("'' + esc(", PICKER) + + def test_luxalgo_scripts_say_run_and_built_ins_say_add(self): + # one LuxAlgo script at a time replaces the last; a built-in stacks — the words must not blur that + self.assertIn("ICON.run + 'Run'", PICKER) + self.assertIn("ICON.plus + 'Add'", PICKER) + self.assertIn("r.__native ? 'Add' : 'Run'", DRAWER) + + +class ItBehaves(unittest.TestCase): + def test_keyboard(self): + for key in ("'ArrowDown'", "'ArrowUp'", "'Enter'", "'ArrowRight'", "'Escape'"): + self.assertIn(key, PICKER) + for key in ("'ArrowDown'", "'ArrowUp'", "'ArrowRight'"): + self.assertIn(key, DRAWER) + + def test_escape_reaches_it_from_anywhere(self): + self.assertIn("window.closePickerIfOpen", PICKER) + self.assertLess(APP.index("window.closePickerIfOpen()"), APP.index("window.closeDrawerIfOpen()")) + + def test_it_is_a_listbox_for_screen_readers(self): + self.assertIn('role="listbox"', PICKER) + self.assertIn('role="option"', PICKER) + self.assertIn("aria-activedescendant", PICKER) + + def test_the_global_search_style_does_not_draw_inside_it(self): + self.assertIn('.qp__search input[type="search"]:focus', CSS) + + def test_motion_is_opacity_and_transform(self): + rule = re.search(r"\.qp \{([^}]*)\}", CSS).group(1) + self.assertIn("transition: opacity", rule) + self.assertNotRegex(rule, r"transition:[^;]*\b(width|height|top|left)\b") + self.assertIn(".qp { transition: none; }", CSS) + + def test_a_narrow_pane_gets_chips_and_keeps_the_preview(self): + # 31 Oct, the operator: "make the preview pane larger a bit. That's the focus". The Hermes + # pane is narrow, so there the preview stays, as a strip above the list, instead of folding away. + self.assertIn("el.classList.toggle('is-narrow', narrow)", PICKER) + rule = re.search(r"\.qp\.is-narrow \.qp__prev \{([^}]*)\}", CSS).group(1) + self.assertIn("display: grid", rule) + self.assertNotRegex(CSS, r"\.qp\.is-narrow \.qp__prev[^{]*\{[^}]*display: none") + + +class EveryBuiltInHasARealPreview(unittest.TestCase): + """31 Oct, the operator: "there must be preview of each indicator". Vela ships no picture for its + built-ins, so each preview is the study itself — its own descriptor's compute(), default inputs, on + the open chart's last bars. Nothing is fetched and nothing is drawn by hand.""" + + def test_the_preview_runs_the_studys_own_maths(self): + self.assertIn("v.getNativeIndicator(type)", PICKER) + self.assertIn("d.create().spec.compute(bars, d.defaultInputs ? d.defaultInputs() : {})", PICKER) + self.assertIn("window.chartBars()", PICKER) + + def test_overlays_and_oscillators_are_drawn_differently(self): + self.assertIn("const sub = !r.overlay", PICKER) + for part in ("out.bands", "out.levels", "out.polylines", "'columns'"): + self.assertIn(part, PICKER) + + def test_volume_and_the_profile_come_from_the_candles(self): + self.assertIn("r.type === 'vpvr'", PICKER) + self.assertIn("r.type === 'volume'", PICKER) + + def test_both_views_draw_them(self): + self.assertIn('data-native-preview="${esc(x.slug)}"', PICKER) + self.assertIn('data-native-preview="${esc(r.slug)}"', DRAWER) + self.assertIn("ti().drawNativeTiles(list)", DRAWER) + + def test_a_long_list_is_drawn_a_few_at_a_time(self): + self.assertIn("tiles.splice(0, 6)", PICKER) + self.assertIn("requestAnimationFrame(step)", PICKER) + + +class ThePreviewIsTheFocus(unittest.TestCase): + """31 Oct, the operator: "make the preview pane larger a bit. That's the focus... and then just a + simple, minor explanation of what the indicator is for".""" + + PURPOSE = re.search(r"const PURPOSE = \{(.*?)\n \};", PICKER, re.S).group(1) + KEYS = re.findall(r"^ '([a-z0-9-]+)': '", PURPOSE, re.M) + + def test_the_pane_and_the_picture_are_larger(self): + self.assertIn("const width = Math.min(880, W - 16);", PICKER) + self.assertIn("Math.min(540, H - top - 12)", PICKER) + self.assertIn("minmax(300px, 360px)", CSS) + self.assertIn(".qp__shot { width: 100%; height: 236px;", CSS) + + def test_every_built_in_says_what_it_is_for(self): + # Vela 0.8.3 ships 77 built-ins; each one gets its own sentence, and each key is a real type id. + self.assertEqual(len(self.KEYS), 77) + self.assertEqual(len(set(self.KEYS)), 77) + vela = "".join(p.read_text(encoding="utf-8", errors="replace") + for p in (FRONT / "vendor" / "vela" / "dist").glob("chunk-*.js")) + missing = [k for k in self.KEYS if f'"{k}"' not in vela and f"'{k}'" not in vela] + self.assertEqual(missing, [], "PURPOSE keys that are not Vela built-in types") + + def test_one_plain_sentence_each(self): + for line in re.findall(r"^ '[a-z0-9-]+': '(.*)',$", self.PURPOSE, re.M): + self.assertLess(len(line), 140, line) + self.assertNotIn("<", line) + + def test_a_luxalgo_script_uses_its_own_write_up(self): + self.assertIn("return firstSentence(x.description);", PICKER) + self.assertIn("What it’s for", PICKER) + self.assertIn("${esc(why)}", PICKER) + + def test_the_panel_finds_built_ins_by_what_they_do(self): + self.assertIn("ti().purpose({ native: true, slug: n.type })", DRAWER) + + +if __name__ == "__main__": + unittest.main() diff --git a/console/backend/tests/test_lib_drawer_polish.py b/console/backend/tests/test_lib_drawer_polish.py new file mode 100644 index 0000000..3d8e382 --- /dev/null +++ b/console/backend/tests/test_lib_drawer_polish.py @@ -0,0 +1,83 @@ +"""The scripts list behind Indicators: six faults found in a screenshot review (31 Oct). + +1. a row whose preview picture failed collapsed: the was deleted, the row's grid shifted one + column left, the name landed in the 52 px picture slot ("Indic…") and the ☆ got the name's room; +2. built-in rows: the ƒ sat in the corner of its tile, and Run sat 12 px left of every other Run + (no ☆ in those rows, so Run took the ☆'s column); +3. the detail view said only "Failed / No live MCP session" — no reason in words, no way to retry; +4. the search box always said "Search 800 scripts" (the header said 120, or 77); +5. the family chips were cut at the edge ("Mom") with nothing saying they scroll; +6. the theme switch in the footer was a tiny dim ◐ that read as a broken glyph. +""" + +import re +import unittest +from pathlib import Path + +FRONT = Path(__file__).resolve().parents[2] / "frontend" +CSS = (FRONT / "styles.css").read_text(encoding="utf-8") +JS = (FRONT / "drawer.js").read_text(encoding="utf-8") +APP = (FRONT / "app.js").read_text(encoding="utf-8") +HTML = (FRONT / "index.html").read_text(encoding="utf-8") + + +def rule(selector: str) -> str: + m = re.search(re.escape(selector) + r"\s*\{([^}]*)\}", CSS) + assert m, f"no CSS rule for {selector}" + return m.group(1) + + +class ARowKeepsItsShape(unittest.TestCase): + def test_each_part_owns_its_column(self): + # a missing tile or a missing ☆ can no longer move what comes after it + for sel, col in ((".drow > .drow__main", "2"), (".drow > .drow__star", "3"), (".drow > .drow__run", "4")): + self.assertRegex(rule(sel), rf"grid-column:\s*{col}\b", sel) + + def test_a_failed_picture_becomes_a_tile_not_a_hole(self): + self.assertIn("img.replaceWith(", JS) + self.assertIn("drow__shot--none", JS) + self.assertNotIn("img.remove()", JS) + + def test_placeholder_tiles_centre_their_glyph(self): + r = rule(".drow__shot--native,\n.drow__shot--none") + self.assertIn("place-items: center", r) + + +class TheDetailSaysWhatWentWrong(unittest.TestCase): + def test_api_errors_carry_their_code(self): + self.assertIn("err.code = payload.code", APP) + + def test_an_offline_library_is_said_in_words_with_a_retry(self): + self.assertIn("mcp_unavailable", APP) + self.assertIn("The LuxAlgo Library isn't connected", APP) + self.assertIn("data-detail-retry", APP) + self.assertNotIn('

Failed

', APP) + + +class TheSearchDoesNotMakeUpACount(unittest.TestCase): + def test_no_fixed_number_in_the_placeholder(self): + self.assertNotRegex(HTML, r'placeholder="Search \d+ scripts') + + +class TheChipsSayTheyScroll(unittest.TestCase): + def test_overflow_is_marked_and_faded(self): + self.assertIn("dataset.more", JS) + self.assertIn('.drawer__fams[data-more', CSS) + self.assertIn("mask-image", CSS.split(".drawer__fams[data-more", 1)[1][:400]) + + +class TheThemeSwitchIsAnIcon(unittest.TestCase): + def test_sun_and_moon_not_a_glyph(self): + btn = HTML[HTML.index('id="theme-toggle"') - 80: HTML.index('id="theme-toggle"') + 900] + self.assertIn("i-sun", btn) + self.assertIn("i-moon", btn) + self.assertNotIn(">◐<", btn) + + def test_it_is_a_real_target(self): + r = rule(".drawer__theme") + self.assertRegex(r, r"width:\s*28px") + self.assertRegex(r, r"height:\s*28px") + + +if __name__ == "__main__": + unittest.main() diff --git a/console/backend/tests/test_preview_cache.py b/console/backend/tests/test_preview_cache.py index 210e207..516b486 100644 --- a/console/backend/tests/test_preview_cache.py +++ b/console/backend/tests/test_preview_cache.py @@ -241,7 +241,9 @@ def test_a_row_without_a_picture_loses_its_img_not_its_tile(self): drawer = read(DRAWER) self.assertIn("list.addEventListener('error'", drawer, "a 404 preview must not leave the browser's broken-image glyph behind") - self.assertIn("if (img && img.tagName === 'IMG') img.remove();", drawer) + # 31 Oct: the is swapped for a placeholder tile, not deleted — deleting it shifted the + # row's grid one column left and squeezed the name into the 52 px picture slot ("Indic…") + self.assertIn("img.replaceWith(", drawer) if __name__ == "__main__": diff --git a/console/frontend/app.js b/console/frontend/app.js index 606b471..ff3e1cd 100644 --- a/console/frontend/app.js +++ b/console/frontend/app.js @@ -370,7 +370,11 @@ async function api(path, params = {}) { Object.entries(params).forEach(([k, v]) => { if (v !== '' && v != null) url.searchParams.set(k, v); }); const res = await fetch(url); const payload = await res.json().catch(() => ({ ok: false, error: `bad JSON (HTTP ${res.status})` })); - if (!payload.ok) throw new Error(payload.error || `HTTP ${res.status}`); + if (!payload.ok) { + const err = new Error(payload.error || `HTTP ${res.status}`); + err.code = payload.code; // e.g. mcp_unavailable — the detail view says it in words + throw err; + } return payload.data; } @@ -1012,8 +1016,18 @@ async function openResult(row, button) { checkHealth(); // the concept fetch moved the counter — refresh the pill } catch (err) { if (mySeq !== openSeq) return; - el.detail.innerHTML = `

Failed

${esc(err.message)}

`; - toast('Could not load detail: ' + err.message, true); + /* What went wrong, in words, and a way to try again (31 Oct: it said only "Failed / No live MCP + session"). The server's own message stays, smaller, for whoever reads the logs. */ + const offline = err.code === 'mcp_unavailable'; + el.detail.innerHTML = ` +

${offline ? "The LuxAlgo Library isn't connected" : "This script didn't load"}

+

${offline + ? "The console can't reach LuxAlgo's server right now, so this script's write-up and Pine source can't be fetched. Check the network — the console reconnects on its own." + : 'Something went wrong fetching it. Try again in a moment.'}

+

${esc(err.message)}

+

`; + el.detail.querySelector('[data-detail-retry]')?.addEventListener('click', () => openResult(row, button)); + toast(offline ? 'LuxAlgo Library not connected — try again in a moment' : 'Could not load detail: ' + err.message, true); } } @@ -1236,7 +1250,8 @@ window.scriptPane = { skipping then meant Escape no longer closed the pane (measured 5 Oct, caught by an A/B run). */ function escapeKeydown(ev) { if (ev.key !== 'Escape') return; - const closed = (typeof window.closeDrawerIfOpen === 'function' && window.closeDrawerIfOpen()) + const closed = (typeof window.closePickerIfOpen === 'function' && window.closePickerIfOpen()) + || (typeof window.closeDrawerIfOpen === 'function' && window.closeDrawerIfOpen()) || (typeof window.closeScriptLayerIfOpen === 'function' && window.closeScriptLayerIfOpen()); if (closed) { ev.preventDefault(); return; } if (el.main && el.main.dataset.detail === 'on') { diff --git a/console/frontend/drawer.js b/console/frontend/drawer.js index c8c4ac1..f3e9c54 100644 --- a/console/frontend/drawer.js +++ b/console/frontend/drawer.js @@ -15,7 +15,7 @@ const SLICE = 60; /* rows painted at once; search still sees all 800 */ const st = { - open: false, q: '', family: '', shown: SLICE, + open: false, q: '', family: '', shown: SLICE, focus: -1, detail: false, /* the drawer's second view: the picked result (3 Oct) */ busy: '', /* slug currently running */ result: {}, /* slug → {ok, text} of its last run here */ @@ -55,6 +55,8 @@ return (indState.natives || []).map((n) => ({ slug: n.type, name: n.title, family: '__builtin', cluster: n.supported === false ? 'not supported here' : (n.present ? 'on chart' : ''), __native: true, present: n.present, supported: n.supported !== false, + /* what it is for (picker.js), so a search for "overbought" or "trailing stop" finds it */ + description: ti().purpose ? ti().purpose({ native: true, slug: n.type }) : '', })); } @@ -91,6 +93,7 @@ + chip('__fav', '★ Favourites', favN) + groups.filter((g) => !q || n(g.key) > 0 || st.family === g.key) .map((g) => chip(g.key, g.name, q ? n(g.key) : g.count)).join(''); + markMore(); } /* What is on the chart, by name — the landasan's own list. The row that matches says so and its @@ -100,22 +103,29 @@ return names.map((n) => String(n).trim().toLowerCase()); } + const ti = () => window.taIndicators || {}; + const toneOf = (key) => (ti().tone ? ti().tone(key) : 'var(--lx-fg-muted)'); + const mark = (text) => (ti().highlight ? ti().highlight(text, st.q) : esc(text)); + function rowHtml(r, i, on) { const starred = !r.__native && isFavourite('library', r.slug); const res = st.result[r.slug]; const running = st.busy === r.slug; const isOn = !r.__native && on.includes(String(r.name || r.slug).trim().toLowerCase()); - const meta = r.__native ? ['built-in', r.cluster].filter(Boolean).join(' · ') - : [famLabel(r.family || 'unfiled'), r.cluster].filter(Boolean).join(' · '); + /* The family is a coloured tag (the same hue in both views); the cluster stays plain text. */ + const tag = r.__native + ? 'Built-in' + : `${esc(famLabel(r.family || 'unfiled'))}`; + const meta = [r.cluster].filter(Boolean).join(' · '); /* 160 is not a taste: it is the width the boot warmer caches (server.py WARM_WIDTH), and test_preview_cache pins the two numbers together. A mismatch is not a smaller picture — it is every open paying S3 for all sixty rows (measured 15 Oct: 2.7 s to fill the first screen). */ - return `
  • - ${r.__native ? '' + return `
  • + ${r.__native ? `` : ``} ${r.__native ? '' : `` : ``} + aria-label="${r.__native ? 'Add to the chart' : 'Run on the chart'}">${running ? '' : (r.__native ? '+' : '▶')}${r.__native ? 'Add' : 'Run'}`}
  • `; } @@ -141,12 +151,42 @@ paintFamilies(); const all = rows(); count.textContent = all.length + ' script' + (all.length === 1 ? '' : 's'); - const shown = all.slice(0, st.shown); const on = onNames(); - list.innerHTML = shown.length - ? shown.map((r, i) => rowHtml(r, i, on)).join('') + (all.length > shown.length - ? `
  • ` : '') + const sec = (label) => ``; + let head = '', rest = all; + /* Browsing everything (no search, no family): what is ON the chart first, then what you used lately, + then the whole library — the operator's two most common moves are one glance away (31 Oct). */ + if (!st.q.trim() && !st.family) { + const isOn = (r) => on.includes(String(r.name || r.slug).trim().toLowerCase()); + const onRows = all.filter(isOn); + const rec = (ti().recent ? ti().recent() : []).map((id) => all.find((r) => r.slug === id)).filter((r) => r && !isOn(r)); + const pinned = new Set([...onRows, ...rec]); + rest = all.filter((r) => !pinned.has(r)); + head = (onRows.length ? sec('On chart · ' + onRows.length) + onRows.map((r, i) => rowHtml(r, i, on)).join('') : '') + + (rec.length ? sec('Recently used') + rec.map((r, i) => rowHtml(r, i, on)).join('') : '') + + (head || onRows.length || rec.length ? sec('All scripts') : ''); + } else if (st.q.trim()) { + head = sec(all.length + (all.length === 1 ? ' result' : ' results')); + } + const shown = rest.slice(0, st.shown); + list.innerHTML = all.length + ? head + shown.map((r, i) => rowHtml(r, i, on)).join('') + (rest.length > shown.length + ? `
  • ` : '') : `
  • ${st.family === '__fav' ? 'No favourites yet — tap ☆ on a script.' : 'Nothing matches “' + esc(st.q) + '”.'}
  • `; + if (st.focus >= 0) setFocus(st.focus, false); + /* Built-ins have no catalogue picture: each tile draws the study itself on this chart (picker.js). */ + if (ti().drawNativeTiles) ti().drawNativeTiles(list); + } + + /* Keyboard: ↑/↓ move a highlight through the rows, Enter runs it, → opens its write-up. The box keeps + the caret, so typing never stops working (31 Oct). */ + function rowEls() { return Array.from(list.querySelectorAll('.drow[data-slug]')); } + function setFocus(i, scroll) { + const els = rowEls(); + if (!els.length) { st.focus = -1; return; } + st.focus = Math.max(0, Math.min(els.length - 1, i)); + els.forEach((li, n) => li.classList.toggle('is-focus', n === st.focus)); + if (scroll) els[st.focus].scrollIntoView({ block: 'nearest' }); } /* One small helper for both slide-over sheets (this drawer and the Edge Stats sheet). They look modal (a scrim covers the @@ -181,6 +221,7 @@ function setOpen(on) { drawer.setAttribute('aria-hidden', String(!st.open)); if (fallback) { fallback.setAttribute('aria-expanded', String(st.open)); fallback.classList.toggle('is-on', st.open); } if (st.open) { + st.focus = -1; st.opener = document.activeElement && document.activeElement !== document.body ? document.activeElement : null; if (window.taModal) window.taModal.enter(drawer); if (indState.cat.state === 'idle' || indState.cat.state === 'error') { @@ -216,12 +257,12 @@ function setOpen(on) { box.focus({ preventScroll: true }); }); - async function run(slug) { + async function run(slug, opts) { if (st.busy) return; const nat = (indState.natives || []).find((n) => n.type === slug); - if (st.family === '__builtin' && nat) { - mountNative(nat.type, nat.title); /* toasts + counts itself; asks the chart, so re-read below */ - loadNatives().then(paint); + if (nat && ((opts && opts.native) || st.family === '__builtin')) { + if (mountNative(nat.type, nat.title) !== false && ti().noteRecent) ti().noteRecent('builtin:' + nat.type); + loadNatives().then(paint); /* toasts + counts itself; asks the chart, so re-read */ return; } const row = (indState.cat.rows || []).find((r) => r.slug === slug) || { slug, name: slug }; @@ -251,6 +292,7 @@ function setOpen(on) { ? { ok: true, text: 'on chart · ' + r.ms + ' ms' } : { ok: false, text: 'ran, but nothing to draw on this market' }; toast(painted ? '“' + label + '” is on the chart' : '“' + label + '” ran — nothing landed', !painted); + if (ti().noteRecent) ti().noteRecent(slug); if (painted) { if (typeof flashChart === 'function') flashChart(); noteActivity('ran “' + label + '” from the drawer', 'drawer'); @@ -265,28 +307,68 @@ function setOpen(on) { } } - /* A row whose picture the catalogue does not carry answers 404. Drop the instead of leaving - the browser's broken-image glyph in the row: no picture is a fact, a broken icon looks like a bug - (the ⌗ modal's lesson, 26 Sep — the drawer inherits the rows). Capture phase: `error` from an - does not bubble. */ + /* A row whose picture the catalogue does not carry answers 404 (and offline, every row does). The + becomes a tile with the name's first letter: no picture is a fact, a broken icon looks like a + bug (the ⌗ modal's lesson, 26 Sep). It is swapped, never deleted: deleting it shifted the row's + grid and squeezed the name into the 52 px picture slot ("Indic…", 31 Oct). Capture phase: `error` + from an does not bubble. */ list.addEventListener('error', (ev) => { const img = ev.target; - if (img && img.tagName === 'IMG') img.remove(); + if (!img || img.tagName !== 'IMG') return; + const tile = document.createElement('span'); + tile.className = 'drow__shot drow__shot--none'; + tile.setAttribute('aria-hidden', 'true'); + const name = img.closest('.drow')?.querySelector('.drow__name'); + tile.textContent = ((name && name.textContent.trim()) || '·').charAt(0).toUpperCase(); + img.replaceWith(tile); }, true); - if (fallback) fallback.addEventListener('click', () => setOpen(!st.open)); + /* The family chips scroll sideways; a fade on the side that has more says so (31 Oct: they were cut + at the edge, "Mom", with nothing to show there was more). A mouse wheel scrolls them too. */ + function markMore() { + const max = fams.scrollWidth - fams.clientWidth; + fams.dataset.more = max <= 1 ? '' : fams.scrollLeft <= 1 ? 'right' : fams.scrollLeft >= max - 1 ? 'left' : 'both'; + } + fams.addEventListener('scroll', markMore, { passive: true }); + fams.addEventListener('wheel', (ev) => { + if (fams.scrollWidth <= fams.clientWidth || Math.abs(ev.deltaX) >= Math.abs(ev.deltaY)) return; + fams.scrollLeft += ev.deltaY; + ev.preventDefault(); + }, { passive: false }); + window.addEventListener('resize', markMore); + + /* The narrow pane's Scripts button opens whichever view the operator chose, like Vela's Indicators. */ + if (fallback) fallback.addEventListener('click', () => { + if (window.taIndicators && window.taIndicators.toggle) window.taIndicators.toggle(); else setOpen(!st.open); + }); + const viewSwitch = drawer.querySelector('.ta-viewswitch'); + if (viewSwitch) viewSwitch.addEventListener('click', (ev) => { + const b = ev.target.closest('[data-view]'); + if (!b || b.dataset.view !== 'quick' || !window.taIndicators) return; + window.taIndicators.setView('quick'); + setOpen(false); + window.taIndicators.open(); + }); scrim.addEventListener('click', () => setOpen(false)); $id('drawer-close').addEventListener('click', () => setOpen(false)); let debounce = null; box.addEventListener('input', () => { clearTimeout(debounce); - debounce = setTimeout(() => { st.q = box.value; st.shown = SLICE; paint(); list.scrollTop = 0; }, 120); + debounce = setTimeout(() => { st.q = box.value; st.shown = SLICE; st.focus = st.q.trim() ? 0 : -1; paint(); list.scrollTop = 0; }, 120); }); box.addEventListener('keydown', (ev) => { + if (ev.key === 'ArrowDown') { ev.preventDefault(); setFocus(st.focus + 1, true); return; } + if (ev.key === 'ArrowUp') { ev.preventDefault(); setFocus(st.focus - 1, true); return; } if (ev.key === 'Enter') { - const first = list.querySelector('.drow'); - if (first) run(first.dataset.slug); + const li = rowEls()[st.focus >= 0 ? st.focus : 0]; + if (li) run(li.dataset.slug, { native: li.dataset.builtin === '1' }); + return; + } + if (ev.key === 'ArrowRight' && box.selectionStart === box.value.length && st.focus >= 0) { + const li = rowEls()[st.focus]; + const open = li && li.querySelector('[data-open]'); + if (open) { ev.preventDefault(); open.click(); } } }); @@ -333,9 +415,9 @@ function setOpen(on) { if (!li || !li.dataset.slug) return; const slug = li.dataset.slug; if (ev.target.closest('[data-remove]')) { clearChart(); return; } - if (ev.target.closest('[data-native]')) { run(slug); return; } + if (ev.target.closest('[data-native]')) { run(slug, { native: true }); return; } const row = (indState.cat.rows || []).find((r) => r.slug === slug) || { slug, name: slug }; - if (ev.target.closest('[data-run]')) { run(slug); return; } + if (ev.target.closest('[data-run]')) { run(slug, { native: li.dataset.builtin === '1' }); return; } if (ev.target.closest('[data-star]')) { toggleFavourite('library', slug, (row.name || slug).trim(), row.image_url); paint(); @@ -383,8 +465,35 @@ function setOpen(on) { return { slug: id, starred: isFavourite('library', id), favourites: readFavourites().length }; } + /* Every row both views can show, in one shape: the LuxAlgo catalogue, then the chart's built-ins. */ + function items() { + const on = onNames(); + const lib = (indState.cat.rows || []).map((r) => { + const name = String(r.name || r.slug).trim(); + return { id: r.slug, slug: r.slug, name, family: r.family || 'unfiled', famLabel: famLabel(r.family || 'unfiled'), + cluster: r.cluster || '', description: r.description || '', image_url: r.image_url, + native: false, supported: true, on: on.includes(name.toLowerCase()), starred: isFavourite('library', r.slug) }; + }); + const nat = nativeRows().map((r) => ({ id: 'builtin:' + r.slug, slug: r.slug, name: r.name, family: '__builtin', + famLabel: 'Built-in', cluster: '', description: r.description || '', native: true, supported: r.supported, + on: Boolean(r.present), starred: false })); + return lib.concat(nat); + } + + /* The dropdown's actions, through the same paths the panel's own buttons take. */ + function act(item, what) { + if (!item) return; + if (what === 'remove') { clearChart(); return; } + if (what === 'run') { run(item.slug, { native: item.native }); return; } + if (what === 'star' && !item.native) { star('library:' + item.slug, !isFavourite('library', item.slug)); return; } + if (what === 'details' && !item.native) { + const row = (indState.cat.rows || []).find((r) => r.slug === item.slug) || { slug: item.slug, name: item.name }; + openResult({ ...row, kind: 'indicator' }, null); + } + } + window.libDrawer = { - open: setOpen, toggle: () => setOpen(!st.open), run, star, reveal, clear: clearChart, + open: setOpen, toggle: () => setOpen(!st.open), run, star, reveal, clear: clearChart, items, act, detail: (on) => { if (on !== false) setOpen(true); showDetail(on !== false); }, search: (q) => { st.q = String(q == null ? '' : q).trim(); diff --git a/console/frontend/index.html b/console/frontend/index.html index 5407693..a69c6a5 100644 --- a/console/frontend/index.html +++ b/console/frontend/index.html @@ -32,16 +32,16 @@ -