create-pmos 0.611.0 → 0.613.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/package.json +105 -27
  2. package/payload/KIT-VERSION +2 -2
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/payload/state/log.md +1 -1
  7. package/workspace/briefing-premium-board-test.js +1 -1
  8. package/workspace/briefing-premium-calendar-2-test.js +3 -2
  9. package/workspace/briefing-premium-calendar-3-test.js +1 -1
  10. package/workspace/briefing-premium-calendar-test.js +1 -1
  11. package/workspace/briefing-premium-insights-test.js +1 -1
  12. package/workspace/briefing-premium-test.js +1 -1
  13. package/workspace/changelog.json +104 -0
  14. package/workspace/guide/layout.md +52 -18
  15. package/workspace/guide/programs.md +3 -3
  16. package/workspace/guide/routine.md +28 -13
  17. package/workspace/guide/settings-and-switches.md +1 -1
  18. package/workspace/lib/board-premium.js +12 -4
  19. package/workspace/lib/cos-chat.js +1 -0
  20. package/workspace/lib/doc-library.js +43 -12
  21. package/workspace/lib/doc-path.js +30 -0
  22. package/workspace/lib/engine/boards.js +4 -2
  23. package/workspace/lib/events-place.js +190 -38
  24. package/workspace/lib/events-stated.js +129 -0
  25. package/workspace/lib/initiative-chat.js +1 -0
  26. package/workspace/lib/insights-premium.js +13 -1
  27. package/workspace/lib/library-find.js +162 -0
  28. package/workspace/lib/library-items.js +196 -24
  29. package/workspace/lib/notes.js +3 -0
  30. package/workspace/lib/plan-items.js +17 -3
  31. package/workspace/lib/routes-artefacts.js +5 -2
  32. package/workspace/lib/routes-boards.js +6 -2
  33. package/workspace/lib/routes-doc-sheet.js +1 -0
  34. package/workspace/lib/routes-events-place.js +47 -10
  35. package/workspace/lib/routes-library.js +74 -8
  36. package/workspace/lib/routes-report-setups.js +13 -2
  37. package/workspace/lib/routine-reports.js +36 -4
  38. package/workspace/lib/status-when.js +36 -0
  39. package/workspace/lib/task-items.js +5 -3
  40. package/workspace/package-lock.json +2 -2
  41. package/workspace/package.json +1 -1
  42. package/workspace/premium-vw-meet-test.js +2 -1
  43. package/workspace/premium-vw-notes-test.js +3 -2
  44. package/workspace/public/pm/artefact-kind.js +87 -0
  45. package/workspace/public/pm/bd-ini-panel.js +6 -6
  46. package/workspace/public/pm/bd-span.js +7 -1
  47. package/workspace/public/pm/bd-work.css +62 -0
  48. package/workspace/public/pm/bd-work.js +195 -68
  49. package/workspace/public/pm/cozy-bar.css +11 -0
  50. package/workspace/public/pm/cozy-bar.js +99 -0
  51. package/workspace/public/pm/cozy-day-pick.css +27 -0
  52. package/workspace/public/pm/cozy-day-pick.js +97 -0
  53. package/workspace/public/pm/cozy-ev.css +0 -4
  54. package/workspace/public/pm/cozy-events-view.js +165 -33
  55. package/workspace/public/pm/cozy-events.css +75 -3
  56. package/workspace/public/pm/cozy-events.js +86 -18
  57. package/workspace/public/pm/cozy-goals.css +172 -0
  58. package/workspace/public/pm/cozy-library.css +106 -17
  59. package/workspace/public/pm/cozy-nav.js +2 -3
  60. package/workspace/public/pm/cozy-pick.css +3 -0
  61. package/workspace/public/pm/cozy-pop-work.css +83 -24
  62. package/workspace/public/pm/cozy-pop-work.js +313 -72
  63. package/workspace/public/pm/cozy-popup.css +11 -2
  64. package/workspace/public/pm/cozy-popup.js +67 -9
  65. package/workspace/public/pm/cozy-routine-job.js +203 -0
  66. package/workspace/public/pm/cozy-routine-model.js +139 -31
  67. package/workspace/public/pm/cozy-routine-pop.js +164 -42
  68. package/workspace/public/pm/cozy-routine.css +61 -8
  69. package/workspace/public/pm/cozy-routine.js +207 -28
  70. package/workspace/public/pm/cozy-settings.js +1 -5
  71. package/workspace/public/pm/cozy-status-when.js +48 -0
  72. package/workspace/public/pm/cozy-viewer.js +19 -8
  73. package/workspace/public/pm/cozy-vw-mtg.css +39 -0
  74. package/workspace/public/pm/goals-model.js +205 -0
  75. package/workspace/public/pm/goals-open.js +124 -0
  76. package/workspace/public/pm/home-chat.js +4 -2
  77. package/workspace/public/pm/home-ini.js +8 -6
  78. package/workspace/public/pm/ini-edit.js +3 -1
  79. package/workspace/public/pm/ini-view-model.js +1 -1
  80. package/workspace/public/pm/library-model.js +170 -42
  81. package/workspace/public/pm/library-open.js +8 -5
  82. package/workspace/public/pm/page-chat.js +12 -2
  83. package/workspace/public/pm/pop-work-model.js +199 -41
  84. package/workspace/public/pm/premium-board.js +108 -43
  85. package/workspace/public/pm/premium-goals.js +213 -0
  86. package/workspace/public/pm/premium-library.js +376 -62
  87. package/workspace/public/pm/premium-shell.js +1 -1
  88. package/workspace/public/pm/premium-vw-mtg.js +79 -1
  89. package/workspace/public/pm/scope-chip.js +207 -0
  90. package/workspace/public/premium-events.html +3 -1
  91. package/workspace/public/premium-goals.html +37 -0
  92. package/workspace/public/premium-library.html +15 -7
  93. package/workspace/public/premium-routine.html +2 -0
  94. package/workspace/server.js +2 -1
  95. package/workspace/test-lists/doc-path.json +9 -0
  96. package/workspace/test-lists/goals-place.json +9 -0
  97. package/workspace/test-lists/status-when.json +9 -0
@@ -28,7 +28,7 @@ import { quietPlace } from './quiet-place.js'; // onboarding B3: before three
28
28
  import { mountLivePill } from './cozy-live-pill.js';
29
29
  import { stepsHelpHtml } from './bd-stages.js';
30
30
  import { msMode } from './bd-pins.js';
31
- import { timelineHtml, legendHtml, hasHold, planKeys, gapKeys, plainGaps, skipsOf, skipWords, gapWords, SPANS, md, fcRange } from './bd-span.js';
31
+ import { timelineHtml, legendHtml, hasHold, planKeys, gapKeys, plainGaps, skipsOf, skipWords, gapWords, SPANS, md, fcRange, rowBar } from './bd-span.js';
32
32
  import * as FCC from './bd-fc-card.js'; // the forecast card under a hatched range (FcBoard)
33
33
  import * as TL from './bd-scroll.js';
34
34
  import './readonly.js'; // the read-only mode of a published board: nothing happens unless the page was opened with ?pack= (board-publish)
@@ -62,6 +62,7 @@ import { narrowForm } from './pn-narrow.js';
62
62
  import * as BP2 from './bd-pane.js';
63
63
  import * as WV from './bd-work.js'; // Work, one view on a desk (slice 4 of the six-place navigation, initiative work-one-view)
64
64
  import * as LS from './load-shapes.js'; // the skeleton and the slow-case line while the board is read (page-open-speed, SpD) // the Board as the first panel: fit(), the rows that open beside, the open row's mark
65
+ import * as SWN from './cozy-status-when.js'; // the day a status move really happened, in the toast (round 3 point 18)
65
66
 
66
67
  const VIEW_KEY = 'pmos.board.view', PVIEW_KEY = 'pmos.board.pview', SPAN_KEY = 'pmos.board.span', GROUPING_KEY = 'pmos.board.grouping';
67
68
  let M = null; // the model
@@ -317,7 +318,7 @@ function drawChips() {
317
318
  TUNE = { jira, jMood };
318
319
  if (phone) { $('#bdChipset').innerHTML = need; return; }
319
320
  // Work on a desk: no count pill and no (i); the rows say late and at risk, the key is under the list, the rest is in the view menu
320
- if (workOn()) { $('#bdChipset').innerHTML = ''; if (WK_MENU) drawWorkMenu(); return; }
321
+ if (workOn()) { $('#bdChipset').innerHTML = ''; drawWorkMore(); wkCount(); if (WK_MENU) drawWorkMenu(); return; }
321
322
  // the pill's (i) (UI grill U2): the timeline's legend (PgTimeline; a program milestone only where a program is drawn and "On hold" only where a
322
323
  // hold is drawn, feedback batch 9 item 8), the sprints and releases the calendar icon opened (BdSprint), and the Jira read with its ↻
323
324
  const lo = menuOpen('bdLgdMenu');
@@ -603,26 +604,36 @@ function drawTime(L) {
603
604
  return T.html;
604
605
  }
605
606
  /* ── Work, one view on a desk (initiative work-one-view; pm/bd-work.js draws, this wires): the list, its view menu, the Stage cell ── */
606
- let WK_MENU = null, WK_HOV = null, WK_STM = null;
607
+ let WK_MENU = null, WK_STM = null;
607
608
  const wkMany = () => !!(M && M.board.all && (M.board.products || []).length > 1);
608
609
  const wkProduct = (r) => r.product || (M && M.board && (M.board.product || M.board.name)) || '';
609
610
  const wkGoalOf = (r) => { if (!GOALS) return ''; const k = (GOALS.of || {})[String(r.anchor || '')], g = k && (GOALS.goals || []).find((x) => x.key === k); return g ? g.title : ''; };
610
611
  const wkProgOf = (r) => { const p = programOf(PGS, r.ws || (M && M.board.ws) || '', r.id); return p ? p.title || p.id : ''; };
611
612
  function drawWork(L) {
612
613
  const pk = prodKey((M.board && (M.board.product || M.board.name)) || ''), lay = SO.layout();
613
- return WV.listHtml(L, { many: wkMany(), sel: peek && peek.kind === 'ini' ? peek.key : null, hov: WK_HOV, rowOf,
614
+ return WV.listHtml(L, { many: wkMany(), sel: peek && peek.kind === 'ini' ? peek.key : null, rowOf, bar: wkBar,
614
615
  product: wkProduct, goalOf: wkGoalOf, programOf: wkProgOf, order: (rows) => sortInis(pk, rows, lay, INI_ACC),
615
616
  goalGroups: (rows) => (GOALS ? GL.asGroups(rows, GOALS, (rs) => sortInis(pk, rs, lay, INI_ACC)) : null),
616
617
  canMove: (r) => !!(r.track && r.acts && (r.acts.stages || []).length > 1) });
617
618
  }
618
- /** A press in the list that is Work's own (a column title, the span, the timeline's hide, a Stage cell). → true when handled. */
619
+ /** One row's bar on Work: the Board's own (pm/bd-span.js rowBar, Wawan's round 2): done, now, planned, every milestone ◇ with its popup, the
620
+ * gap line, the late line. W: Work's window { from, to }. The track's width is measured once drawn, so close ◇s merge at about 40 px. */
621
+ let WK_TPX = 0;
622
+ function wkBar(r, W) {
623
+ const span = +W.to - +W.from || 1, X = (d) => ((+d - +W.from) / span) * 100;
624
+ const px = WK_TPX || Math.max(320, Math.round(innerWidth * 0.4)), pxDay = px / (span / 864e5);
625
+ return rowBar(r, X, new Date(), { pxPct: px / 100, reach: Math.max(1, Math.round(40 / pxDay)), mode: 'all', label: false });
626
+ }
627
+ const wkMeasure = () => { const x = $('#ibBody .wk-i .wk-bw'); const w = x ? Math.round(x.getBoundingClientRect().width) : 0; if (w && Math.abs(w - WK_TPX) > 40) { WK_TPX = w; return true; } return false; };
628
+ /** A press in the list that is Work's own (a column title, the span, the timeline's hide, a Stage cell, a bar, the closed line). → true when handled. */
619
629
  function workPress(e) {
620
630
  const p = WV.pressOf(e.target); if (!p) return false;
631
+ if (p.kind === 'inside') return true; // a press in the open stage card stays there
621
632
  if (p.kind === 'spanmenu') { spanMenu(); return true; }
622
633
  if (p.kind === 'stage') { stageMenu(rowOf(p.key), p.el); return true; }
623
634
  if (!WV.apply(p)) return false;
624
- drawInit(); if (WK_MENU) drawWorkMenu();
625
- const f = p.kind === 'sort' ? `[data-wksort="${p.k}"]` : p.kind === 'span' ? '[data-wkspan]' : p.kind === 'timeline' ? (p.on ? '[data-wktl="off"]' : '[data-wktl="on"]') : null;
635
+ drawInit(); wkCount(); if (WK_MENU) drawWorkMenu();
636
+ const f = p.kind === 'sort' ? `[data-wksort="${p.k}"]` : p.kind === 'span' ? '[data-wkspan]' : p.kind === 'timeline' ? (p.on ? '[data-wktl="off"]' : '[data-wktl="on"]') : p.kind === 'closed' ? '[data-wkclosed]' : null;
626
637
  const n = f && $('#ibBody ' + f); if (n) n.focus();
627
638
  return true;
628
639
  }
@@ -631,18 +642,22 @@ function spanMenu(open) {
631
642
  const o = open == null ? m.hidden : open; m.hidden = !o; b.setAttribute('aria-expanded', String(o));
632
643
  if (o) (m.querySelector('.on') || m.querySelector('button')).focus();
633
644
  }
634
- document.addEventListener('click', (e) => { if (!e.target.closest('.wk-spw')) { const m = $('#ibBody .wk-spm'); if (m && !m.hidden) spanMenu(false); } if (WK_STM && !e.target.closest('.wk-stm, [data-wkstage]')) closeStageMenu(); });
645
+ document.addEventListener('click', (e) => {
646
+ if (!e.target.closest('.wk-spw')) { const m = $('#ibBody .wk-spm'); if (m && !m.hidden) spanMenu(false); }
647
+ if (WK_STM && !e.target.closest('.wk-stm, [data-wkstage]')) closeStageMenu();
648
+ // the stage card closes on a press outside it and outside a bar (a bar's own press toggles it in workPress)
649
+ if (WV.cardOf() && !e.target.closest('.wk-card') && !(e.target.closest('[data-wkbar]') && e.target.closest('.tg-bar, .wk-bar')) && WV.closeCard()) drawInit();
650
+ });
635
651
  $('#ibBody').addEventListener('keydown', (e) => {
636
652
  if (curView() !== 'work') return;
637
- if (e.key === 'Escape') { const m = $('#ibBody .wk-spm'); if (m && !m.hidden) { e.stopPropagation(); spanMenu(false); $('#ibBody [data-wkspan]').focus(); } return; }
653
+ if (e.key === 'Escape') {
654
+ const m = $('#ibBody .wk-spm'); if (m && !m.hidden) { e.stopPropagation(); spanMenu(false); $('#ibBody [data-wkspan]').focus(); return; }
655
+ const k = WV.cardOf(); if (k && WV.closeCard()) { e.stopPropagation(); drawInit(); const r = $(`#ibBody .wk-i[data-key="${CSS.escape(k)}"]`); if (r) r.focus(); }
656
+ return;
657
+ }
638
658
  // a row is a button: Enter or Space opens it in the popup
639
659
  if ((e.key === 'Enter' || e.key === ' ') && e.target.matches('.wk-i[data-key]')) { e.preventDefault(); openIni(rowOf(e.target.dataset.key), e.target); }
640
660
  });
641
- // point at a row: its stages show on its bar and in a small card under it (board 4); the keyboard's focus does the same
642
- const wkHov = (k) => { if (curView() === 'work') WK_HOV = WV.hover($('#ibBody'), k, WK_HOV); };
643
- $('#ibBody').addEventListener('mouseover', (e) => { const r = e.target.closest('.wk-i[data-key]'); if (r && !e.target.closest('.wk-card')) wkHov(r.dataset.key); });
644
- $('#ibBody').addEventListener('mouseleave', () => wkHov(null));
645
- $('#ibBody').addEventListener('focusin', (e) => { const r = e.target.closest('.wk-i[data-key]'); wkHov(r ? r.dataset.key : null); });
646
661
 
647
662
  /** The Stage cell: the stages of the row's own workflow in a short list; a pick moves it (POST /api/boards/move, the By stage drag's write), with Undo. */
648
663
  function closeStageMenu() { if (WK_STM) { WK_STM.remove(); WK_STM = null; } }
@@ -664,27 +679,59 @@ function stageMenu(r, el) {
664
679
  });
665
680
  }
666
681
 
667
- /** The view menu under the tune button (board 5): Group by, the Timeline, the Columns; then what left the toolbar, so no feature is dropped. */
682
+ /** What left the toolbar goes under ⋯ on a desk (board 5: the view menu ends at "PMOS remembers this · Reset"), so no feature is dropped:
683
+ * Sort and filter, New asks, Only what waits on you, Sprints and releases, Shared with me, Read Jira again. Rows of the shell's ⋯ menu. */
668
684
  function workMore() {
669
685
  const C = (M && M.chips) || {}, J = (M && M.jira) || {}, sp = J.sprint, rel = J.release, you = youRows().length;
670
- const it = (k, icon, label, note) => `<button type="button" class="wk-mx" data-wkx="${k}">${SV(I[icon])}<span>${esc(label)}</span>${note ? `<span class="k">${esc(String(note))}</span>` : ''}</button>`;
686
+ const it = (k, label, note) => `<button type="button" role="menuitem" class="wk-xo" data-wkx="${k}">${esc(label)}${note ? `<span class="k">${esc(String(note))}</span>` : ''}</button>`;
671
687
  const sprint = [sp ? sp.name : null, rel ? rel.name : null].filter(Boolean).join(' · ');
672
- return it('filter', 'group', 'Sort and filter', filtered() ? 'on' : '')
673
- + (C.asks ? it('asks', 'note', C.asks === 1 ? 'New ask' : 'New asks', C.asks) : '')
674
- + (you ? it('you', 'flag', 'Only what waits on you', F.chips.has('you') ? 'on' : you) : '')
675
- + (!ALL && sprint ? it('sprint', 'cal', 'Sprints and releases', sprint) : '')
676
- + it('shared', 'people', tab === 'shared' ? 'Back to the initiatives' : 'Shared with me', tab === 'shared' ? '' : SH_N || '')
677
- + it('jira', 'refresh', jiraReading ? 'Reading Jira' : 'Read Jira again', TUNE.jira.replace(/^Jira · /, ''));
678
- }
688
+ // Sort and filter, and what waits on you, are in the view menu itself (round 3); ⋯ keeps the asks, the sprint, the shared and the Jira read
689
+ void you;
690
+ return (C.asks ? it('asks', C.asks === 1 ? 'New ask' : 'New asks', C.asks) : '')
691
+ + (!ALL && sprint ? it('sprint', 'Sprints and releases', sprint) : '')
692
+ + it('shared', tab === 'shared' ? 'Back to the initiatives' : 'Shared with me', tab === 'shared' ? '' : SH_N || '')
693
+ + it('jira', jiraReading ? 'Reading Jira' : 'Read Jira again', TUNE.jira.replace(/^Jira · /, ''));
694
+ }
695
+ /** The tune button's small count: how many filter values are on (round 3); none, no count (zero is silence). */
696
+ function wkCount() {
697
+ const b = $('#bdFilter'); if (!b) return;
698
+ let c = b.querySelector('.wk-fc'); const n = workOn() ? WV.filterCount() : 0;
699
+ if (!n) { if (c) c.remove(); b.setAttribute('aria-label', 'Filter, sort and view'); return; }
700
+ if (!c) { c = document.createElement('i'); c.className = 'wk-fc'; c.setAttribute('aria-hidden', 'true'); b.appendChild(c); }
701
+ c.textContent = String(n); b.setAttribute('aria-label', 'Filter, sort and view. ' + n + (n === 1 ? ' filter is on' : ' filters are on'));
702
+ }
703
+ /** Puts Work's rows at the top of ⋯, or takes them out when the page is not Work. */
704
+ function drawWorkMore() {
705
+ const menu = $('#moreMenu'); if (!menu) return;
706
+ for (const x of $$('#moreMenu > .wk-xo')) x.remove();
707
+ if (!workOn() || !M) return;
708
+ const at = $('#bdPublish') || menu.firstElementChild;
709
+ at.insertAdjacentHTML('beforebegin', workMore());
710
+ }
711
+ { const mm = $('#moreMenu'); if (mm) mm.addEventListener('click', (e) => { const x = e.target.closest('.wk-xo'); if (x) workExtra(x.dataset.wkx, $('#moreBtn')); }); }
679
712
  function drawWorkMenu(focus) {
680
713
  if (!WK_MENU) return;
681
714
  const was = focus || (WK_MENU.contains(document.activeElement) ? wkSel(document.activeElement) : null);
682
- WK_MENU.innerHTML = WV.menuHtml({ many: wkMany(), more: workMore() });
715
+ const sc = WK_MENU.firstElementChild ? WK_MENU.firstElementChild.scrollTop : 0;
716
+ WK_MENU.innerHTML = WV.menuHtml({ many: wkMany(), sprint: (M && M.jira && M.jira.sprint) || null });
683
717
  const m = WK_MENU.firstElementChild, b = WK_MENU.__btn.getBoundingClientRect();
684
- m.style.top = Math.round(b.bottom + 8) + 'px'; m.style.left = Math.max(8, Math.round(b.right - m.offsetWidth)) + 'px';
685
- const n = was && m.querySelector(was); if (n) n.focus();
686
- }
687
- const wkSel = (el) => { const x = el.closest('[data-wkgroup],[data-wkcolsw],[data-wktlsw],[data-wkreset],[data-wkx]'); if (!x) return null; for (const a of ['wkgroup', 'wkcolsw', 'wkx']) if (x.dataset[a]) return `[data-${a}="${x.dataset[a]}"]`; return x.hasAttribute('data-wktlsw') ? '[data-wktlsw]' : '[data-wkreset]'; };
718
+ const top = Math.round(b.bottom + 8);
719
+ m.style.top = top + 'px'; m.style.left = Math.max(8, Math.round(b.right - m.offsetWidth)) + 'px';
720
+ m.style.maxHeight = Math.max(240, innerHeight - top - 12) + 'px'; // it scrolls inside the window; Filter's title and Clear stay on top
721
+ m.scrollTop = sc;
722
+ const n = was && m.querySelector(was); if (n) n.focus({ preventScroll: true });
723
+ }
724
+ /** Where the focus goes back after the menu is drawn again: the same control, or the nearest one that is still there. */
725
+ const wkSel = (el) => {
726
+ const x = el.closest('[data-wkgroup],[data-wkcolsw],[data-wktlsw],[data-wkreset],[data-wkx],[data-wkf],[data-wksortp],[data-wksortx],[data-wkcols],[data-wkmore],[data-wkclear]'); if (!x) return null;
727
+ const d = x.dataset;
728
+ if (d.wkf) return `[data-wkf="${d.wkf}"][data-wkv="${CSS.escape(d.wkv)}"]`;
729
+ if (d.wksortx) return '[data-wksortp=""]';
730
+ if ('wksortp' in d) return `[data-wksortp="${d.wksortp}"]`;
731
+ if (d.wkmore) return `[data-wkf="${d.wkmore}"]`;
732
+ for (const a of ['wkgroup', 'wkcolsw', 'wkx']) if (d[a]) return `[data-${a}="${d[a]}"]`;
733
+ return x.hasAttribute('data-wktlsw') ? '[data-wktlsw]' : x.hasAttribute('data-wkcols') ? '[data-wkcols]' : x.hasAttribute('data-wkclear') ? '[data-wkcols]' : '[data-wkcols]';
734
+ };
688
735
  function closeWorkMenu(back) { if (!WK_MENU) return; const b = WK_MENU.__btn; WK_MENU.remove(); WK_MENU = null; b.setAttribute('aria-expanded', 'false'); b.classList.remove('on'); if (back) b.focus(); }
689
736
  function toggleWorkMenu(btn) {
690
737
  if (WK_MENU) { closeWorkMenu(true); return; }
@@ -693,19 +740,19 @@ function toggleWorkMenu(btn) {
693
740
  drawWorkMenu();
694
741
  const f = WK_MENU.querySelector('[data-wkgroup].on') || WK_MENU.querySelector('button'); if (f) f.focus();
695
742
  WK_MENU.addEventListener('click', (e) => {
696
- const x = e.target.closest('[data-wkx]');
697
- if (x) { workExtra(x.dataset.wkx, btn); return; }
743
+ const x = e.target.closest('[data-wkx]'); if (x) { workExtra(x.dataset.wkx, btn); return; }
698
744
  const p = WV.pressOf(e.target); if (!p || !WV.apply(p)) return;
699
- const sel = wkSel(e.target); drawInit(); drawWorkMenu(sel);
745
+ const sel = wkSel(e.target); drawInit(); wkCount(); drawWorkMenu(sel);
700
746
  });
701
747
  WK_MENU.addEventListener('keydown', (e) => { if (e.key === 'Escape') { e.stopPropagation(); closeWorkMenu(true); } });
702
748
  WV.wireDrag(WK_MENU, (k) => { drawInit(); drawWorkMenu(k ? `[data-wkcolsw="${k}"]` : null); });
703
749
  }
704
- document.addEventListener('click', (e) => { if (WK_MENU && !WK_MENU.contains(e.target) && !e.target.closest('#bdFilter')) closeWorkMenu(); });
750
+ // a press inside the menu draws it again, so its target may have left the page by now: that is not a press outside
751
+ document.addEventListener('click', (e) => { if (WK_MENU && e.target.isConnected && !WK_MENU.contains(e.target) && !e.target.closest('#bdFilter')) closeWorkMenu(); });
705
752
  function workExtra(k, btn) {
706
- if (k === 'jira') { refreshJira(null).then(() => drawWorkMenu('[data-wkx="jira"]')); drawWorkMenu('[data-wkx="jira"]'); return; }
707
- if (k === 'you') { if (F.chips.has('you')) F.chips.delete('you'); else F.chips.add('you'); drawInit(); drawWorkMenu('[data-wkx="you"]'); return; }
708
- if (k === 'shared') { setTab(tab === 'shared' ? 'ini' : 'shared'); drawWorkMenu('[data-wkx="shared"]'); return; }
753
+ if (k === 'jira') { refreshJira(null).then(() => { drawWorkMore(); drawWorkMenu(); }); drawWorkMore(); return; }
754
+ if (k === 'you') { if (F.chips.has('you')) F.chips.delete('you'); else F.chips.add('you'); drawInit(); drawWorkMore(); return; }
755
+ if (k === 'shared') { setTab(tab === 'shared' ? 'ini' : 'shared'); drawWorkMore(); return; }
709
756
  closeWorkMenu();
710
757
  if (k === 'filter') Acts.open.filter(btn);
711
758
  else if (k === 'asks') Acts.open.asks(btn);
@@ -753,6 +800,7 @@ function drawInit() {
753
800
  body.innerHTML = html + phx;
754
801
  if (fk) { const n = $$('#ibBody [data-key]').find((x) => x.dataset.key === fk); if (n) n.focus({ preventScroll: true }); }
755
802
  if (v === 'time') TL.mount(body);
803
+ if (v === 'work' && wkMeasure()) { drawInit(); return; } // the bars' ◇s merge by the track's real width: once measured, draw again
756
804
  $('#bdShowing').innerHTML = showingHtml(L.length); $('#bdShowing').hidden = !$('#bdShowing').innerHTML;
757
805
  drawViewMenu();
758
806
  document.body.dataset.bdView = v;
@@ -1039,11 +1087,27 @@ BP2.wire();
1039
1087
  /** A linked document opens in the Viewer: GET /api/doc, shown as its text, and drawn again when the file changes (pm/doc-follow.js). */
1040
1088
  document.addEventListener('click', (e) => {
1041
1089
  const d = e.target.closest('[data-doc]'); if (!d || !M) return;
1042
- const path = d.dataset.doc, ws = M.board.ws || '', inVw = !!d.closest('.cz-vw');
1090
+ // the document's own workspace: an initiative of another product on a program board reads from its repository, not the board's (round 3
1091
+ // point 17: "pmos/planning/prd/smrt-news-feed-prd.md could not be read" was read from the board's workspace)
1092
+ const path = d.dataset.doc, ws = d.dataset.docWs || M.board.ws || '', inVw = !!d.closest('.cz-vw');
1093
+ // in the popup a markdown document opens as the document page (pm/library-open.js), with its name as the title; the Viewer beside the
1094
+ // Board keeps its plain text view
1095
+ if (/\.md$/i.test(path) && (d.closest('.cz-pop') || d.dataset.docPage)) {
1096
+ const name = (d.getAttribute('aria-label') || '').replace(/^Open /, '') || d.textContent.trim().split('\n')[0] || path.split('/').pop();
1097
+ import('./library-open.js').then((L) => { if (inVw && VW.drill) VW.drill(); L.openItem({ id: 'doc:' + path, kind: 'doc', name, open: { doc: { path, ws } }, about: { ws } }); });
1098
+ return;
1099
+ }
1043
1100
  viewerOpen({ kind: 'Document', title: path.split('/').pop(), icon: 'doc', id: 'doc:' + path, back: inVw, render: async (body) => {
1044
1101
  body.innerHTML = '<p class="bd-amut">Reading the document…</p>';
1045
- await followDoc({ ws, path, alive: () => body.isConnected && !!viewerCur() && viewerCur().id === 'doc:' + path,
1046
- onText: (text) => { body.innerHTML = text == null ? `<p class="bd-amut">${esc(path)} could not be read.</p>` : `<p class="bd-amut">${esc(path)}</p><pre class="bd-doc">${esc(text)}</pre>`; } });
1102
+ const draw = () => followDoc({ ws, path, alive: () => body.isConnected && !!viewerCur() && viewerCur().id === 'doc:' + path,
1103
+ onText: async (text) => {
1104
+ if (text != null) { body.innerHTML = `<p class="bd-amut">${esc(path)}</p><pre class="bd-doc">${esc(text)}</pre>`; return; }
1105
+ // plain words with the server's reason, and Retry; never a bare path as the whole page
1106
+ const why = await fetch('/api/doc?ws=' + encodeURIComponent(ws) + '&path=' + encodeURIComponent(path), { credentials: 'same-origin' }).then((r) => (r.ok ? '' : r.text())).catch(() => 'the server did not answer');
1107
+ body.innerHTML = `<p class="bd-amut">This document could not be opened${why ? ': ' + esc(why) : ''}.</p><button type="button" class="hi-btn ghost" data-doc-retry>Retry</button>`;
1108
+ const b = body.querySelector('[data-doc-retry]'); if (b) b.onclick = () => { body.innerHTML = '<p class="bd-amut">Reading the document…</p>'; draw(); };
1109
+ } });
1110
+ await draw();
1047
1111
  } });
1048
1112
  });
1049
1113
  /* ── the tools the Agreed design draws but has no frame for: plain versions with a "Waiting for design" tag (pm/bd-acts.js) ─────────── */
@@ -1248,13 +1312,14 @@ async function loadWorkflows() {
1248
1312
  if (r && r.ok && Array.isArray(r.workflows)) { WF.setDefs(r.workflows); drawInit(); }
1249
1313
  }
1250
1314
  /** A task's state from the initiative panel (✓ on its Tasks or its stage card); Undo puts the old state back. */
1251
- async function setTask(r, uid, state) {
1252
- const k = (r.tasks || []).find((x) => x.uid === uid), body = { ws: r.ws || M.board.ws, board: r.boardId || M.board.id, task: uid };
1253
- const res = await pmPost('/api/boards/tasks/state', { ...body, state }).catch(() => null);
1315
+ async function setTask(r, uid, state, w) {
1316
+ const k = (r.tasks || []).find((x) => x.uid === uid), body = { ws: r.ws || M.board.ws, board: r.boardId || M.board.id, task: uid }, happened = (w && w.happened) || null;
1317
+ const res = await pmPost('/api/boards/tasks/state', { ...body, state, ...(happened ? { happened } : {}) }).catch(() => null);
1254
1318
  if (!res || res.ok === false) { say((res && res.error) || 'Nothing was changed.'); return; }
1255
1319
  // a breakdown item closed as Won't do is withdrawn, which the ledger cannot undo; every other change can go back (batch 9 item 5b)
1256
1320
  const undo = k && k.status !== state && !(k.item && state === "Won't do");
1257
- say(state + ': ' + (k ? k.title : uid) + '.', undo ? async () => { const u = await pmPost('/api/boards/tasks/state', { ...body, state: k.status }).catch(() => null); say(u && u.ok ? 'Back to ' + k.status + '.' : (u && u.error) || 'The undo did not land.'); load(); } : undefined);
1321
+ // the day it really happened is said too (round 3 point 18): "Done on 14 Nov, noted today: <title>."
1322
+ say((happened ? SWN.whenWords(state, happened).replace(/\.$/, '') : state) + ': ' + (k ? k.title : uid) + '.', undo ? async () => { const u = await pmPost('/api/boards/tasks/state', { ...body, state: k.status }).catch(() => null); say(u && u.ok ? 'Back to ' + k.status + '.' : (u && u.error) || 'The undo did not land.'); load(); } : undefined);
1258
1323
  load();
1259
1324
  }
1260
1325
  /** A task's start and due from the panel's Tasks (the date press, a Timeline drag), or its ◇ milestone flag (batch 11 item 3): POST
@@ -1317,7 +1382,7 @@ function nextAct(b) {
1317
1382
  else if (k === 'epic') import('./tk-send.js').then((S) => S.openSend({ ws: r.ws || M.board.ws || null, board: r.boardId || M.board.id, initiative: r.id, toast: say }));
1318
1383
  else if (k === 'jira') refreshJira(b);
1319
1384
  }
1320
- const viewDoc = (path) => { const a = document.createElement('button'); a.dataset.doc = path; a.hidden = true; document.body.appendChild(a); a.click(); a.remove(); };
1385
+ const viewDoc = (path, ws) => { const a = document.createElement('button'); a.dataset.doc = path; if (ws) a.dataset.docWs = ws; if (document.body.classList.contains('cz-pop-on')) a.dataset.docPage = '1'; a.hidden = true; document.body.appendChild(a); a.click(); a.remove(); };
1321
1386
  const anchors = async (ws, board) => { try { const r = await (await fetch('/api/boards/anchors?ws=' + encodeURIComponent(ws || M.board.ws || '') + '&board=' + encodeURIComponent(board || M.board.id || ''), { credentials: 'same-origin' })).json(); return r && r.ok ? r.anchors || [] : []; } catch { return []; } };
1322
1387
  // Find and the other jumps: on the timeline the row's bar scrolls into view and the row tints for a moment (TsCEdges 4)
1323
1388
  /** The ✦ on the forecast card (FcBoard): the initiative opens and its "Claude proposes" drill-in with it (pm/ini-props.js, the Grill's findings). */
@@ -0,0 +1,213 @@
1
+ /* pm/premium-goals.js — Goals, the place (initiative goals-place, slice 9 of the six-place navigation; boards 8, 13, 31, 32, 33 on Exploring 2,
2
+ * page "Navigation: Today, Work, Goals, Events, Library, Routine"; handover /mnt/project-files/goals-handover/).
3
+ *
4
+ * "Am I on track? What do I do?" as one hierarchy. Top: the product choice Work and Goals share (cozy-pick.js, full names) and the OKR period. Then
5
+ * the North Star card (a kept record; else PMOS's open draft with ✓ ✕; else "not set"), then one table: Objective › Key result (Actual / target,
6
+ * Left) › Levers › Initiative, a Budget row per health budget with work in it, and Unlinked, the open work no key result names. The words and
7
+ * numbers are pm/goals-model.js, which makes none up. With more than one product ticked, each product is its own block under its name.
8
+ * A press on a key result opens it in the popup (board 31); on an initiative, the initiative (slice 3's popup), or the verdict page when its
9
+ * outcome check is overdue (board 33); ⋯ › Set up opens the setup page (board 32) (pm/goals-open.js).
10
+ * Search opens Search with Goals' own rows first; Filter shows All, Slipping, Not read or Read (remembered on this device, 'pmos.goals.filt').
11
+ * ⋯ › Charts and dashboards opens the Intelligence page, where the readings, charts and dashboards stay; ⋯ › Export CSV saves the table.
12
+ * Reads GET /api/insights-premium?ws= and GET /api/metric-drafts?ws=&scope=product&id= for each ticked product, again when the tab comes back after a
13
+ * minute. Writes only the North Star draft's ✓ (POST /api/metric-drafts/keep, Undo /undo) and ✕ (/drop). */
14
+ import './fetch-share.js';
15
+ import { pmGet, pmPost } from './http.js';
16
+ import { mountNav } from './cozy-nav.js';
17
+ import { mountLivePill } from './cozy-live-pill.js';
18
+ import * as PK from './cozy-pick.js';
19
+ import './cozy-viewer.js';
20
+ import * as POP from './cozy-popup.js'; // the one popup: window.czOpenChat for the rail's chat icon, and the popup a row opens in
21
+ import * as GM from './goals-model.js';
22
+ import * as GO from './goals-open.js';
23
+ import { undoToast } from './hi-pop.js';
24
+
25
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
26
+ const SVG = (d, w = 18) => `<svg aria-hidden="true" width="${w}" height="${w}" viewBox="0 0 24 24"><path d="${d}"/></svg>`;
27
+ const I = { check: 'M5 12.5l4.5 4.5L19 7.5', x: 'M6 6l12 12M18 6L6 18', cal: 'M4 5.5h16v14H4zM4 10h16M9 3.5v4M15 3.5v4', spark: 'M12 3l1.8 4.7L18.5 9.5l-4.7 1.8L12 16l-1.8-4.7L5.5 9.5l4.7-1.8z' };
28
+ const store = { get(k) { try { return localStorage.getItem(k); } catch { return null; } }, set(k, v) { try { localStorage.setItem(k, v); } catch { /* a private window */ } } };
29
+ const todayIso = () => { const d = new Date(); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); };
30
+ const FILT = GM.FILTERS.map((f) => f[0]);
31
+ const S = { P: null, list: [], at: 0, filter: FILT.includes(store.get('pmos.goals.filt')) ? store.get('pmos.goals.filt') : 'all', error: '' };
32
+ const DEEP = new URLSearchParams(location.search).get('ws');
33
+
34
+ mountNav('insights', document, { scope: () => ({ name: 'Goals', hits: (q) => hits(q) }) });
35
+ mountLivePill();
36
+
37
+ const $ = (id) => document.getElementById(id);
38
+ const body = $('glBody');
39
+
40
+ /* ── the product choice and the period ── */
41
+ function shownPick() {
42
+ if (!S.P) return null;
43
+ if (!DEEP) return S.P;
44
+ return { ...S.P, products: S.P.products.map((p) => ({ ...p, on: p.ws === DEEP })) };
45
+ }
46
+ function drawPick() {
47
+ const P = shownPick(), host = $('glPick');
48
+ host.innerHTML = P ? PK.chipHtml(P, { id: 'glPickB', label: 'Products', names: !matchMedia('(max-width: 760px)').matches }) : '';
49
+ const chip = $('glPickB'); if (!chip) return;
50
+ const lines = (ws) => { const x = S.list.find((p) => p.ws === ws); const n = x && x.model && x.model.okrFile ? x.model.okrFile.total : 0; return n ? n + (n === 1 ? ' key result' : ' key results') : ''; };
51
+ chip.onclick = (e) => { e.stopPropagation(); closeMenus(); PK.openPicker(chip, { P: shownPick(), label: 'Products', lines, note: 'One pick for Today, Work and Goals: unticking a product here also takes it off Today.', onApply: async (on) => { const r = await PK.savePick(on); if (!r.ok) undoToast(r.error, () => {}, 4000); } }); };
52
+ }
53
+ addEventListener('pp:changed', () => { if (DEEP) { location.assign(location.pathname); return; } S.P = null; load(); });
54
+ function drawPer() {
55
+ const x = S.list.find((p) => p.model && p.model.okrFile && p.model.okrFile.period);
56
+ const per = x ? GM.periodOf(x.model.okrFile) : null, el = $('glPer');
57
+ el.hidden = !per;
58
+ if (per) el.innerHTML = `${SVG(I.cal, 16)}<b>${esc(per.label)}</b>${per.sub ? `<span>${esc(per.sub)}</span>` : ''}`;
59
+ }
60
+
61
+ /* ── the North Star card ── */
62
+ function nsHtml(p) {
63
+ const ns = p.ns;
64
+ if (ns.state === 'set') return `<div class="gl-ns set"><i class="gl-mark" aria-hidden="true">${SVG(I.spark, 14)}</i><div class="t"><div class="k">North Star</div><b>${esc(ns.title)}</b><p>${esc(ns.sub)}</p></div></div>`;
65
+ if (ns.state === 'draft') return `<div class="gl-ns"><i class="gl-mark" aria-hidden="true">${SVG(I.spark, 14)}</i><div class="t"><div class="k">North Star · not set in your OKR file</div><b>${esc(ns.title)}</b><p>${esc(ns.sub)}</p></div>`
66
+ + `<button type="button" class="gl-go" data-gl-nsdrop="${esc(p.ws)}" aria-label="No, drop this North Star" title="No">${SVG(I.x, 16)}</button><button type="button" class="gl-go" data-gl-nskeep="${esc(p.ws)}" aria-label="Approve this North Star" title="Approve this North Star">${SVG(I.check, 18)}</button></div>`;
67
+ return `<div class="gl-ns"><i class="gl-mark" aria-hidden="true">${SVG(I.spark, 14)}</i><div class="t"><div class="k">North Star · not set in your OKR file</div><b>${esc(ns.title)}</b><p>${esc(ns.sub)}</p></div>`
68
+ + `<button type="button" class="gl-go" data-gl-setup="${esc(p.ws)}" aria-label="Ask PMOS to draft the North Star" title="Ask PMOS to draft the North Star">${SVG(I.spark, 16)}</button></div>`;
69
+ }
70
+
71
+ /* ── the table ── */
72
+ const dm = (k) => (k ? `<i class="gl-dm ${k === 'rd' ? 'rd' : ''}" aria-hidden="true"></i>` : '');
73
+ const iniHtml = (p, i) => `<button type="button" class="gl-ini" data-gl-ws="${esc(p.ws)}" data-gl-ini="${esc(i.id)}"${i.verdict ? ' data-gl-verdict' : ''}><b>${esc(i.title)}</b>${i.line ? `<span class="${i.tone}">${dm(i.dm)}${esc(i.line)}</span>` : ''}</button>`;
74
+ function krHtml(p, k, first) {
75
+ const act = k.act ? `<b>${esc(k.act)}</b>${k.target ? ' / ' + esc(k.target) : ''}` : `<span class="gl-ph">—</span>${k.target ? ' / ' + esc(k.target) : ''}`;
76
+ return `<button type="button" class="gl-kr${first ? ' f' : ''}" data-gl-ws="${esc(p.ws)}" data-gl-kr="${esc(k.key)}" aria-label="${esc(k.token + ' ' + k.title + '. ' + (k.act ? 'Now ' + k.act : 'No reading') + '. ' + k.sub)}">`
77
+ + `<span class="n"><i class="gl-d ${k.dot}"></i><span><i>${esc(k.token)}</i>${esc(k.title)}<small>${esc(k.sub)}</small></span></span>`
78
+ + `<span class="a ${k.tone}">${act}</span><span class="l">${esc(k.left)}</span></button>`;
79
+ }
80
+ function objHtml(p, o) {
81
+ const n = o.krs.length;
82
+ let h = `<div class="gl-o gl-r1 gl-s${n}"><b>${esc(o.label)}</b>${o.title ? `<span>${esc(o.title)}</span>` : ''}${o.slip ? `<span class="rk">${esc(o.slip)}</span>` : ''}</div>`;
83
+ o.krs.forEach((k, i) => { h += `<div class="gl-kc gl-r${i + 1}">${krHtml(p, k, i === 0)}</div>`; });
84
+ h += `<div class="gl-lv gl-r1 gl-s${n}">${o.levers.map((l) => `<div><b>${esc(l.title)}</b><span class="${l.tone}">${esc(l.txt)}</span></div>`).join('')}</div>`;
85
+ for (const c of o.inis) h += `<div class="gl-in gl-r${c.from} gl-s${c.span}">${c.items.map((i) => iniHtml(p, i)).join('')}</div>`;
86
+ return `<div class="gl-ob" role="rowgroup">${h}</div>`;
87
+ }
88
+ function tableHtml(p) {
89
+ const T = p.T;
90
+ if (!p.model.okrFile) return `<p class="gl-none">No OKR file was found for ${esc(p.name)}, so there is no key result to show. Goals reads the OKR file in planning/okrs/.</p>`;
91
+ if (!T.objectives.length && S.filter !== 'all') return `<p class="gl-none">No key result is ${esc((GM.FILTERS.find((f) => f[0] === S.filter) || [])[1] || '').toLowerCase()} in ${esc(p.name)}.</p>`;
92
+ const hd = '<div class="gl-hd" role="row"><span>Objective</span><span class="gl-kh"><span>Key result</span><span>Actual / target</span><span>Left</span></span><span>Levers</span><span>Initiative</span></div>';
93
+ const bud = T.budgets.map((b) => `<div class="gl-ob gl-row1"><div class="gl-o"><b>Budget</b><span class="${b.over ? 'late' : ''}">${esc(b.label)}${b.share ? ' · ' + esc(b.share) : ''}</span></div><div class="gl-wide"><b>No key result: a budget that is always on</b>${b.covers ? `<span>${esc(b.covers)}</span>` : ''}</div><div class="gl-in">${b.items.map((i) => iniHtml(p, i)).join('')}</div></div>`).join('');
94
+ const un = T.unlinked.length ? `<div class="gl-ob gl-row1"><div class="gl-o"><b>Unlinked</b></div><div class="gl-wide"><span>${T.unlinked.length === 1 ? 'An initiative with no key result named' : T.unlinked.length + ' initiatives with no key result named'}</span></div><div class="gl-in">${T.unlinked.map((i) => iniHtml(p, i)).join('')}</div></div>` : '';
95
+ return `<div class="gl-card" role="table" aria-label="Goals of ${esc(p.name)}">${hd}${T.objectives.map((o) => objHtml(p, o)).join('')}${bud}${un}</div>`;
96
+ }
97
+ function draw() {
98
+ if (!S.list.length) { body.innerHTML = `<p class="gl-none">${esc(S.error ? 'Goals could not be read: ' + S.error + '.' : 'No product is ticked. Tick one in the product choice.')}</p>`; $('glNote').hidden = true; return; }
99
+ const today = todayIso(), many = S.list.length > 1;
100
+ let h = '';
101
+ for (const p of S.list) {
102
+ if (!p.model) { h += `<section class="gl-p">${many ? `<h2 class="gl-ph2">${esc(p.name)}</h2>` : ''}<p class="gl-none">${esc(p.name)} could not be read: ${esc(p.error || 'the server did not answer')}.</p></section>`; continue; }
103
+ p.T = GM.tableOf(p.model, today, S.filter);
104
+ p.ns = GM.northStarOf(p.model, p.drafts);
105
+ h += `<section class="gl-p" aria-label="${esc(p.name)}">${many ? `<h2 class="gl-ph2">${esc(p.name)}</h2>` : ''}${p.model.okrFile ? nsHtml(p) : ''}${tableHtml(p)}</section>`;
106
+ }
107
+ body.innerHTML = h;
108
+ $('glNote').hidden = false;
109
+ $('glFdot').hidden = S.filter === 'all';
110
+ drawPer();
111
+ }
112
+
113
+ /* ── load ── */
114
+ async function loadOne(ws, name) {
115
+ const q = ws ? '?ws=' + encodeURIComponent(ws) : '';
116
+ const r = await pmGet('/api/insights-premium' + q).catch((e) => ({ ok: false, error: (e && e.message) || '' }));
117
+ if (!r || !r.ok || !r.model) return { ws, name, model: null, error: (r && r.error) || 'the server did not answer' };
118
+ const w = ws || r.model.board.ws || '';
119
+ const d = w ? await pmGet('/api/metric-drafts?ws=' + encodeURIComponent(w) + '&scope=product&id=' + encodeURIComponent(w)).catch(() => null) : null;
120
+ return { ws: w, name: name || r.model.board.name || w, model: r.model, drafts: d && d.ok !== false ? d : null };
121
+ }
122
+ async function load() {
123
+ if (!S.P) { S.P = await PK.readPick().catch(() => null); drawPick(); }
124
+ const P = shownPick();
125
+ const on = P ? P.products.filter((p) => p.on).sort((a, b) => (b.primary ? 1 : 0) - (a.primary ? 1 : 0)) : [];
126
+ const want = on.length ? on.map((p) => [p.ws, p.name]) : [[DEEP || '', '']];
127
+ S.list = await Promise.all(want.map(([ws, name]) => loadOne(ws, name)));
128
+ S.error = S.list.every((p) => !p.model) ? (S.list[0] && S.list[0].error) || '' : '';
129
+ S.at = Date.now();
130
+ draw();
131
+ drawPick();
132
+ }
133
+
134
+ /* ── presses ── */
135
+ const ctxOf = (ws) => { const p = S.list.find((x) => x.ws === ws) || S.list[0]; return { model: p.model, ws: p.ws, today: todayIso(), ns: p.ns, keepNs: (row) => keepNs(p, row), dropNs: (row) => dropNs(p, row) }; };
136
+ async function keepNs(p, row) {
137
+ const base = { ws: p.ws, scope: 'product', id: p.ws, row };
138
+ const r = await pmPost('/api/metric-drafts/keep', base).catch(() => null);
139
+ if (!r || r.ok === false) { undoToast((r && r.error) || 'The North Star was not kept.', () => {}, 4000); return; }
140
+ undoToast('North Star set.', async () => { await pmPost('/api/metric-drafts/undo', base).catch(() => null); await load(); });
141
+ await load();
142
+ }
143
+ async function dropNs(p, row) {
144
+ const base = { ws: p.ws, scope: 'product', id: p.ws, row };
145
+ const r = await pmPost('/api/metric-drafts/drop', base).catch(() => null);
146
+ if (!r || r.ok === false) { undoToast((r && r.error) || 'Nothing was changed.', () => {}, 4000); return; }
147
+ undoToast('Dropped.', async () => { await pmPost('/api/metric-drafts/undo', base).catch(() => null); await load(); });
148
+ await load();
149
+ }
150
+ body.onclick = (e) => {
151
+ const t = e.target.closest('button'); if (!t) return;
152
+ const d = t.dataset;
153
+ if (d.glKr) { GO.openKr(ctxOf(d.glWs), d.glKr); return; }
154
+ if (d.glIni) { const c = ctxOf(d.glWs); if ('glVerdict' in d) GO.openVerdict(c, d.glIni); else GO.openIni(c, d.glIni); return; }
155
+ if (d.glNskeep) { const p = S.list.find((x) => x.ws === d.glNskeep); if (p && p.ns.row) { t.disabled = true; keepNs(p, p.ns.row); } return; }
156
+ if (d.glNsdrop) { const p = S.list.find((x) => x.ws === d.glNsdrop); if (p && p.ns.row) { t.disabled = true; dropNs(p, p.ns.row); } return; }
157
+ if (d.glSetup) { GO.openSetup(ctxOf(d.glSetup)); setTimeout(() => GO.toChat('Draft a North Star for this product from its key results. I approve it with a tick.'), 150); }
158
+ };
159
+
160
+ /* ── the menus: Filter and ⋯ ── */
161
+ const MENUS = [['glFilt', 'glFiltMenu'], ['glMore', 'glMoreMenu']];
162
+ function closeMenus(except) { for (const [b, m] of MENUS) if (m !== except && !$(m).hidden) { $(m).hidden = true; $(b).setAttribute('aria-expanded', 'false'); } }
163
+ function drawMenus() {
164
+ $('glFiltMenu').innerHTML = GM.FILTERS.map(([k, label]) => `<button type="button" role="menuitemradio" aria-checked="${S.filter === k}" data-gl-f="${k}">${esc(label)}</button>`).join('');
165
+ $('glMoreMenu').innerHTML = '<button type="button" role="menuitem" data-gl-m="setup">Set up</button><button type="button" role="menuitem" data-gl-m="charts">Charts and dashboards</button><button type="button" role="menuitem" data-gl-m="csv">Export CSV</button>';
166
+ }
167
+ for (const [b, m] of MENUS) {
168
+ $(b).onclick = (e) => {
169
+ e.stopPropagation(); const open = $(m).hidden; closeMenus(m); drawMenus();
170
+ $(m).hidden = !open; $(b).setAttribute('aria-expanded', String(open));
171
+ if (open) { const f = $(m).querySelector('button'); if (f) f.focus(); }
172
+ };
173
+ }
174
+ document.addEventListener('click', (e) => { for (const [b, m] of MENUS) if (!$(m).hidden && !e.target.closest('#' + m) && !e.target.closest('#' + b)) { $(m).hidden = true; $(b).setAttribute('aria-expanded', 'false'); } });
175
+ document.addEventListener('keydown', (e) => { if (e.key !== 'Escape') return; for (const [b, m] of MENUS) if (!$(m).hidden) { $(m).hidden = true; $(b).setAttribute('aria-expanded', 'false'); $(b).focus(); } });
176
+ $('glFiltMenu').onclick = (e) => {
177
+ const t = e.target.closest('[data-gl-f]'); if (!t) return;
178
+ S.filter = t.dataset.glF; store.set('pmos.goals.filt', S.filter); closeMenus(); draw();
179
+ };
180
+ $('glMoreMenu').onclick = (e) => {
181
+ const t = e.target.closest('[data-gl-m]'); if (!t) return;
182
+ closeMenus();
183
+ const k = t.dataset.glM, p = S.list.find((x) => x.model) || null;
184
+ if (k === 'setup' && p) GO.openSetup(ctxOf(p.ws));
185
+ else if (k === 'charts') location.assign('/premium-intelligence.html' + (DEEP ? '?ws=' + encodeURIComponent(DEEP) : ''));
186
+ else if (k === 'csv') exportCsv();
187
+ };
188
+ function exportCsv() {
189
+ const q = (v) => '"' + String(v == null ? '' : v).replace(/"/g, '""') + '"';
190
+ const lines = [['Product', 'Objective', 'Key result', 'Name', 'Actual', 'Target', 'Left', 'Waits on', 'Initiatives'].map(q).join(',')];
191
+ for (const p of S.list) if (p.T) for (const o of p.T.objectives) for (const k of o.krs) {
192
+ const ini = o.inis.flatMap((c) => c.items).filter((i) => k.moves.includes(i.id)).map((i) => i.title).join('; ');
193
+ lines.push([p.name, o.label + (o.title ? ': ' + o.title : ''), k.token, k.title, k.act, k.target, k.left, k.need, ini].map(q).join(','));
194
+ }
195
+ const a = document.createElement('a');
196
+ a.href = URL.createObjectURL(new Blob([lines.join('\n') + '\n'], { type: 'text/csv' }));
197
+ a.download = 'goals-' + todayIso() + '.csv'; document.body.appendChild(a); a.click(); a.remove();
198
+ }
199
+
200
+ /* ── Search: Goals' own rows first ── */
201
+ function hits(q) {
202
+ const s = String(q || '').toLowerCase().trim(); if (!s) return [];
203
+ const rows = [];
204
+ for (const p of S.list) if (p.model && p.model.okrFile) {
205
+ for (const o of p.model.okrFile.objectives) for (const k of o.krs) if ((k.token + ' ' + k.title).toLowerCase().includes(s)) rows.push({ id: 'kr:' + k.key, title: k.token + ' ' + k.title, sub: GM.objLabel(o.token) + (S.list.length > 1 ? ' · ' + p.name : ''), open: () => GO.openKr(ctxOf(p.ws), k.key) });
206
+ }
207
+ return rows.length ? [{ label: 'In Goals', rows: rows.slice(0, 8) }] : [];
208
+ }
209
+ $('glFind').onclick = () => import('./cozy-search.js').then((M) => M.openSearch({ scope: { name: 'Goals', hits } }));
210
+
211
+ document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible' && Date.now() - S.at > 60000) load(); });
212
+ void POP;
213
+ load();