create-pmos 0.443.0 → 0.445.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 (110) hide show
  1. package/package.json +25 -25
  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/adler-moments-test.js +8 -0
  8. package/workspace/adler-seasons-art-test.js +3 -0
  9. package/workspace/board-columns-test.js +168 -0
  10. package/workspace/board-programs-test.js +1 -1
  11. package/workspace/briefing-premium-board-test.js +91 -8
  12. package/workspace/briefing-premium-insights-test.js +83 -38
  13. package/workspace/briefing-premium-test.js +2 -1
  14. package/workspace/calm-timeline-test.js +3 -1
  15. package/workspace/changelog.json +24 -0
  16. package/workspace/goals-clear-ui-test.js +34 -20
  17. package/workspace/guide/home.md +5 -0
  18. package/workspace/guide/jira.md +13 -1
  19. package/workspace/guide/ready-made-dashboards.md +2 -2
  20. package/workspace/intel-report-ui-test.js +1 -1
  21. package/workspace/lib/board-fold.js +33 -5
  22. package/workspace/lib/board-premium.js +1 -1
  23. package/workspace/lib/console-state.js +5 -1
  24. package/workspace/lib/engine/boards.js +9 -2
  25. package/workspace/lib/factory-join.js +46 -14
  26. package/workspace/lib/freshness.js +14 -1
  27. package/workspace/lib/initiative-rows.js +38 -4
  28. package/workspace/lib/issues.js +8 -1
  29. package/workspace/lib/jira-cli.js +18 -2
  30. package/workspace/lib/jira-moves.js +119 -0
  31. package/workspace/lib/jira-tickets.js +23 -4
  32. package/workspace/lib/notes.js +4 -2
  33. package/workspace/lib/offloop.js +75 -29
  34. package/workspace/lib/page-build.js +97 -0
  35. package/workspace/lib/plan-items.js +24 -3
  36. package/workspace/lib/plan-tree.js +62 -9
  37. package/workspace/lib/ready-reports.js +22 -8
  38. package/workspace/lib/refresh.js +14 -2
  39. package/workspace/lib/routes-board-premium.js +9 -1
  40. package/workspace/lib/routes-boards.js +114 -16
  41. package/workspace/lib/routes-brief-page.js +3 -1
  42. package/workspace/lib/routes-calendar-import.js +13 -1
  43. package/workspace/lib/routes-ready-reports.js +28 -5
  44. package/workspace/lib/task-links.js +12 -1
  45. package/workspace/lib/workflows-store.js +14 -3
  46. package/workspace/live-pill-round-test.js +178 -0
  47. package/workspace/milestone-pins-test.js +1 -1
  48. package/workspace/okr-goals-ui-test.js +21 -19
  49. package/workspace/package-lock.json +2 -2
  50. package/workspace/package.json +1 -1
  51. package/workspace/panels-test.js +375 -0
  52. package/workspace/premium-rec-tab-test.js +2 -1
  53. package/workspace/premium-vw-item-test.js +10 -2
  54. package/workspace/premium-vw-jira-test.js +3 -0
  55. package/workspace/program-panel-test.js +6 -6
  56. package/workspace/public/pm/bd-cols.js +149 -0
  57. package/workspace/public/pm/bd-ini-panel.js +3 -2
  58. package/workspace/public/pm/bd-pane.js +41 -0
  59. package/workspace/public/pm/bd-span.js +29 -11
  60. package/workspace/public/pm/cozy-adler.js +21 -0
  61. package/workspace/public/pm/cozy-board.css +45 -0
  62. package/workspace/public/pm/cozy-divider.css +32 -0
  63. package/workspace/public/pm/cozy-divider.js +45 -0
  64. package/workspace/public/pm/cozy-insights.css +22 -0
  65. package/workspace/public/pm/cozy-live-pill.css +17 -22
  66. package/workspace/public/pm/cozy-live-pill.js +38 -18
  67. package/workspace/public/pm/cozy-panels.css +80 -0
  68. package/workspace/public/pm/cozy-panels.js +691 -0
  69. package/workspace/public/pm/cozy-viewer.js +148 -70
  70. package/workspace/public/pm/dash-view.js +5 -2
  71. package/workspace/public/pm/goals-clear.js +9 -2
  72. package/workspace/public/pm/home-app.js +30 -19
  73. package/workspace/public/pm/home-ini.js +9 -3
  74. package/workspace/public/pm/home-today.js +4 -2
  75. package/workspace/public/pm/ini-edit.js +405 -0
  76. package/workspace/public/pm/ini-tasks.js +175 -46
  77. package/workspace/public/pm/ini-versions.js +18 -4
  78. package/workspace/public/pm/ini-view-model.js +12 -7
  79. package/workspace/public/pm/ini-view.css +162 -26
  80. package/workspace/public/pm/ini-view.js +44 -13
  81. package/workspace/public/pm/ini-wf-model.js +9 -0
  82. package/workspace/public/pm/ini-wf.js +14 -9
  83. package/workspace/public/pm/ins-pane.js +55 -0
  84. package/workspace/public/pm/jira-move.js +50 -0
  85. package/workspace/public/pm/live-model.js +3 -2
  86. package/workspace/public/pm/pn-narrow.js +76 -0
  87. package/workspace/public/pm/premium-board.js +85 -32
  88. package/workspace/public/pm/premium-insights.js +211 -43
  89. package/workspace/public/pm/task-card.css +2 -0
  90. package/workspace/public/pm/task-card.js +4 -1
  91. package/workspace/public/premium-board.html +2 -0
  92. package/workspace/ready-dash-ui-test.js +4 -4
  93. package/workspace/server.js +71 -20
  94. package/workspace/skills/jira-move.skill +35 -0
  95. package/workspace/stage-card-tasks-test.js +397 -0
  96. package/workspace/stage-card-test.js +1 -1
  97. package/workspace/task-delete-test.js +9 -1
  98. package/workspace/task-links-test.js +1 -0
  99. package/workspace/task-milestones-test.js +3 -3
  100. package/workspace/task-plans-test.js +1 -1
  101. package/workspace/task-press-test.js +12 -4
  102. package/workspace/task-views-test.js +166 -13
  103. package/workspace/test-lists/batch18-live-pill-round.json +10 -0
  104. package/workspace/test-lists/batch18-panels.json +9 -0
  105. package/workspace/test-lists/board-columns.json +5 -0
  106. package/workspace/test-lists/jira-moves.json +11 -0
  107. package/workspace/test-lists/page-speed-fold.json +5 -0
  108. package/workspace/test-lists/page-speed-reads.json +5 -0
  109. package/workspace/test-lists/stage-card-tasks.json +6 -0
  110. package/workspace/timeline-holds-test.js +1 -1
@@ -16,6 +16,7 @@
16
16
  * press (pmPost). Nothing here opens the old dialog or links to the console. */
17
17
  import { mountNav } from './cozy-nav.js';
18
18
  import { mountLivePill } from './cozy-live-pill.js';
19
+ import { mountPanels } from './cozy-panels.js';
19
20
  import { ownTab, bring, tabUrl } from './rec-tab-core.js';
20
21
  import * as VW from './cozy-viewer.js';
21
22
  import * as SV from './small-vw.js'; // the small Viewers: a stakeholder, its form, a routine (batch 18 item 2-C)
@@ -161,7 +162,8 @@ async function getRetry(path, tries = 20) {
161
162
  for (let i = 0; i < tries; i++) {
162
163
  const r = await pmGet(path);
163
164
  if (!(r && (r.state === 'reading' || r.status === 202 || r.pending && !r.model))) return r;
164
- await new Promise((ok) => setTimeout(ok, 2500));
165
+ // a first read after a restart usually lands within a second: ask again soon, then less often (page-speed)
166
+ await new Promise((ok) => setTimeout(ok, Math.min(2500, 300 * 2 ** i)));
165
167
  }
166
168
  return { ok: false, error: 'still reading' };
167
169
  }
@@ -190,14 +192,13 @@ async function load() {
190
192
  D.now = Date.now();
191
193
  D.err = [brief, board].filter((x) => !x || !x.ok).map((x) => (x && x.error) || 'the server did not answer');
192
194
  const rows = H.boardRows(D);
193
- if (rows.length) {
194
- const b = (D.board && D.board.board) || {};
195
- const tr = await pmGet('/api/board-trail?ids=' + encodeURIComponent(rows.slice(0, 150).map((r) => r.id).join(',')) + (b.ws ? '&ws=' + encodeURIComponent(b.ws) : wsQ('&')) + (b.id ? '&board=' + encodeURIComponent(b.id) : boardQ('&')));
196
- D.trail = tr && tr.ok ? tr : null;
197
- }
198
- // the PMOS tasks of the board, so each sits under its initiative
199
195
  const b0 = (D.board && D.board.board) || {};
200
- const items = b0.id ? await pmGet('/api/boards/items?ws=' + encodeURIComponent(b0.ws || WS || '') + '&board=' + encodeURIComponent(b0.id)) : null;
196
+ // the trail of the rows and the PMOS tasks of the board (so each sits under its initiative), read side by side (page-speed)
197
+ const [tr, items] = await Promise.all([
198
+ rows.length ? pmGet('/api/board-trail?ids=' + encodeURIComponent(rows.slice(0, 150).map((r) => r.id).join(',')) + (b0.ws ? '&ws=' + encodeURIComponent(b0.ws) : wsQ('&')) + (b0.id ? '&board=' + encodeURIComponent(b0.id) : boardQ('&'))) : null,
199
+ b0.id ? pmGet('/api/boards/items?ws=' + encodeURIComponent(b0.ws || WS || '') + '&board=' + encodeURIComponent(b0.id)) : null,
200
+ ]);
201
+ if (rows.length) D.trail = tr && tr.ok ? tr : null;
201
202
  D.items = items && items.ok ? items : null;
202
203
  D.others = D.others || [];
203
204
  S.ready = true;
@@ -469,7 +470,7 @@ function iniViewOf(id) {
469
470
  const need = H.needsOf(S.D).find((r) => r.ini === id);
470
471
  const p = programOf(S.D.programs || [], row.ws || (B.board || {}).ws || '', id);
471
472
  return iniView(rowFor({ ...row, trail: t || row.trail || null }), { steps: B.steps || STEPS, today: B.today, usual: WFM.usualOf(S.D.trail, row),
472
- ask: need ? { title: need.name, n: H.needsOf(S.D).filter((r) => r.ini === id).length } : null, program: p ? { id: p.id, title: p.title } : null,
473
+ ask: need ? { title: need.name, n: H.needsOf(S.D).filter((r) => r.ini === id).length } : null, program: p ? { id: p.id, title: p.title } : null, jiraReadAt: ((B.jira || {}).readAt) || '',
473
474
  // the card (batch 18 item 1): Claude's line while a session works on it, the stakeholders
474
475
  claude: (() => { const w = S.D.sessions.find((s) => H.iniOfSession(s) === id && s.shown === 'working'); return w ? 'I’m working on “' + H.nameOf(w) + '”. I’ll say here when it is ready.' : ''; })(),
475
476
  people: (((S.D.desk && S.D.desk.stakeholders) || {})[id] || []) });
@@ -1023,6 +1024,7 @@ async function goIni(id, o = {}) {
1023
1024
  openTarget(iniTarget(id));
1024
1025
  if (o.page !== false) { pushPage(); iniPage(); }
1025
1026
  syncUrl();
1027
+ if (window.czPanels) window.czPanels.scope(id); // the initiative reopens with its last panels and shares (batch 18 item 15)
1026
1028
  await loadIni();
1027
1029
  if (S.ini !== id) return;
1028
1030
  drawList(); openTarget(iniTarget(id));
@@ -1062,7 +1064,7 @@ function goProgram(id) {
1062
1064
  pushPage();
1063
1065
  programPanel().then(() => { if (S.head === 'g:' + id) document.dispatchEvent(new CustomEvent('bd:program', { detail: { id } })); }).catch(() => toast('The program could not open.'));
1064
1066
  }
1065
- function goHome() { S.ini = null; S.sel = null; S.IM = null; S.head = null; S.phoneChat = false; syncUrl(); drawList(); openTarget(homeTarget()); }
1067
+ function goHome() { S.ini = null; S.sel = null; S.IM = null; S.head = null; S.phoneChat = false; syncUrl(); drawList(); openTarget(homeTarget()); if (window.czPanels) window.czPanels.scope(null); }
1066
1068
  /* The browser's Back closes the page a name opened (HbC). The Viewer keeps the one trail and its history entries (batch 14 item 7): Back
1067
1069
  * at the trail's first item closes it, and Home is then as it was. Close (×, Escape) takes the entries off and keeps the initiative's chat. */
1068
1070
  let paged = false;
@@ -1754,7 +1756,9 @@ $('#hmList').onclick = (e) => { // delegated: every press on the list is a <bu
1754
1756
  if (d.hmGroup) { if (S.shut.has(d.hmGroup)) S.shut.delete(d.hmGroup); else S.shut.add(d.hmGroup); store.set('pmos.home.shut', JSON.stringify([...S.shut])); drawList(); return; }
1755
1757
  if ('hmAllneeds' in d) { S.allNeeds = !S.allNeeds; drawList(); return; }
1756
1758
  if ('hmNew' in d) { menu(b, newItems(), 'New'); return; }
1757
- if ('hmFold' in d) { S.folded = true; store.set('pmos.home.fold', '1'); drawList(); return; }
1759
+ // the list header's fold (batch 18 item 15): with a Viewer open the list folds to the rail and the Viewer takes the room; with none, the
1760
+ // list folds away and the button at the top left brings it back
1761
+ if ('hmFold' in d) { if (VW.isOpen()) { VW.wide(true); return; } S.folded = true; store.set('pmos.home.fold', '1'); drawList(); return; }
1758
1762
  if ('hmMeet' in d) { const m = H.meetLineOf(S.D.today); if (m) openMeeting(m.meeting); return; }
1759
1763
  if ('hmCal' in d) { openCalendar(); return; }
1760
1764
  if ('hmRec' in d) { MORE.openRecorder().then(() => drawList()); return; }
@@ -1873,14 +1877,21 @@ PO.mount({ programs: () => S.D.programs || [], stateOf: (p) => (((S.M && S.M.gro
1873
1877
  SO.mount({ redraw: () => { S.D.order = SO.layout(); drawList(); }, say: (m, undo) => (undo ? toastUndo(m, undo) : toast(m)) });
1874
1878
  mountNav('home', document, { here: () => { if (VW.isOpen()) VW.close(); goHome(); } });
1875
1879
  // the Live pill (batch 6 item 2): on Home a row opens in place, the session's chat (with its Viewer page) or the meeting; the open one is tinted
1876
- mountLivePill(document, {
1877
- open: () => (S.cur && S.cur.ses) || null,
1878
- go: (x) => {
1879
- if (x.kind === 'rec') { const id = /[?&]meeting=([^&]+)/.exec(x.href || ''); if (!id) return false; openMeeting({ note: decodeURIComponent(id[1]) }); return true; }
1880
- const s = x.sid && S.D.sessions.find((y) => y.id === x.sid); if (!s) return false;
1881
- if (VW.isOpen() && isPhone()) VW.close();
1882
- S.sel = 's:' + s.id; S.phoneChat = isPhone(); openTarget(sessionTarget(s)); followViewer(s); drawList(); syncUrl();
1883
- return true;
1880
+ const liveGo = (x) => {
1881
+ if (x.kind === 'rec') { const id = /[?&]meeting=([^&]+)/.exec(x.href || ''); if (!id) return false; openMeeting({ note: decodeURIComponent(id[1]) }); return true; }
1882
+ const s = x.sid && S.D.sessions.find((y) => y.id === x.sid); if (!s) return false;
1883
+ if (VW.isOpen() && isPhone()) VW.close();
1884
+ S.sel = 's:' + s.id; S.phoneChat = isPhone(); openTarget(sessionTarget(s)); followViewer(s); drawList(); syncUrl();
1885
+ return true;
1886
+ };
1887
+ mountLivePill(document, { open: () => (S.cur && S.cur.ses) || null, go: liveGo });
1888
+ /* The panels (batch 18 item 15, canvas TbT1Split…TbT9Divider): the chat and up to 3 Viewers side by side, the divider, open beside, ⧉, slide
1889
+ * over. A Live pill row opens in the chat (liveGo); a remembered Viewer of an initiative opens again here when Home has a view for it. */
1890
+ mountPanels({
1891
+ go: liveGo,
1892
+ reopen: (it) => {
1893
+ if (/^file:[\w./-]+\.\w+$/.test(it.id || '')) { openFile({ path: it.id.slice(5), name: it.title || '' }); return true; }
1894
+ return false;
1884
1895
  },
1885
1896
  });
1886
1897
  PHC = mountPhoneCard({ pmGet, pmPost, toast, ws: () => WS || null, openMeeting: (m) => openMeeting(m), skip: ['meeting'] }); drawList();
@@ -282,13 +282,19 @@ function wirePage(b, id) {
282
282
  addCancel: () => { ADDING = null; ADD_DATES = null; redrawView(); },
283
283
  // the stage card's ⏸ or calendar on a hold (batch 11 item 21): what the hold says, and its return date set or changed here
284
284
  hold: (i, btn) => holdPop(btn, id),
285
- addTask: async (title, inp) => {
285
+ // opt (batch 18 item 16): the + on a stage: the task goes under that stage, with the dates its field picked; the toast offers Undo
286
+ addTask: async (title, inp, opt) => {
286
287
  const M = curM(); if (!M) return;
287
288
  inp.disabled = true;
288
- const r = await C.pmPost('/api/boards/tasks/add', { ...bw(M), initiative: id, title, ...(ADD_DATES ? { start: ADD_DATES.start, due: ADD_DATES.due } : {}) });
289
+ const D = opt ? opt : ADD_DATES || {};
290
+ const r = await C.pmPost('/api/boards/tasks/add', { ...bw(M), initiative: id, title, ...(D.start ? { start: D.start } : {}), ...(D.due ? { due: D.due } : {}), ...(opt && opt.section != null ? { section: opt.section } : {}) });
289
291
  inp.disabled = false;
290
292
  if (!r || r.ok === false) { say((r && r.error) || 'The task was not added.'); return; }
291
- say('Task added.'); await C.load(); redrawView();
293
+ const uid = r.item && r.item.uid;
294
+ if (opt && uid) undoToast('Added to ' + (opt.name || 'the stage') + '.', async () => { const u = await C.pmPost('/api/boards/tasks/delete', { ...bw(M), task: uid, why: 'undo of add' }); if (!u || u.ok === false) C.toast((u && u.error) || 'The undo did not land.'); await C.load(); redrawView(); });
295
+ else say('Task added.');
296
+ await C.load(); redrawView();
297
+ if (opt) return;
292
298
  const n = BODY && BODY.querySelector('#ivAddTask'); if (n) { n.value = ''; n.focus(); }
293
299
  },
294
300
  next: (btn) => { const M = curM(); if (M) popNext(btn, id, M); },
@@ -28,7 +28,7 @@ export const P = {
28
28
  pause: 'M8 5v14M16 5v14', stop: 'M7 7h10v10H7z', list: 'M9 6h11M9 12h11M9 18h11', doc: 'M7 3h7l5 5v13H7zM14 3v5h5',
29
29
  gate: 'M12 3l7 3v6c0 4-3 7-7 9-4-2-7-5-7-9V6z', flag: 'M5 21V4h11l-2 4 2 4H5', cal: 'M4 6h16v14H4zM4 10h16', pin: 'M9 4h6l-1 6 3 3H7l3-3zM12 13v7',
30
30
  decide: 'M12 3v18M5 8l7-5 7 5', ret: 'M9 14L4 9l5-5M4 9h10a6 6 0 0 1 0 12h-3', back: 'M19 12H5M11 6l-6 6 6 6', warn: 'M12 4l9 16H3zM12 10v4M12 17v.5',
31
- chat: 'M4 5h16v11H9l-5 4z', prog: 'M4 5h7v5H4zM13 5h7v5h-7zM8.5 14h7v5h-7zM7.5 10v2h9v-2M12 12v2', dots: 'M5 12h.01M12 12h.01M19 12h.01', send: 'M5 12h14M13 6l6 6-6 6', ticket: 'M3 5h18v4H3zM3 11h18v4H3z',
31
+ chat: 'M4 5h16v11H9l-5 4z', fold: 'M5 4h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2zM9 4v16', prog: 'M4 5h7v5H4zM13 5h7v5h-7zM8.5 14h7v5h-7zM7.5 10v2h9v-2M12 12v2', dots: 'M5 12h.01M12 12h.01M19 12h.01', send: 'M5 12h14M13 6l6 6-6 6', ticket: 'M3 5h18v4H3zM3 11h18v4H3z',
32
32
  };
33
33
  export const svg = (d, w = 16, cls = '') => `<svg aria-hidden="true"${cls ? ` class="${cls}"` : ''} width="${w}" height="${w}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="${d}"/></svg>`;
34
34
  const ROW_ICON = { decision: P.decide, blocked: P.warn, waited: P.clock, src: P.doc, source: P.doc, ev: P.gate, run: P.ret, update: P.doc, meeting: P.cal };
@@ -320,7 +320,9 @@ export function listHtml(M, T, o) {
320
320
  + (o.pick ? chipHtml(o.pick, { id: 'hmPick', attrs: 'data-hm-pick', label: 'Products on Home', tones: o.tones }) : '')
321
321
  + (o.phone ? '' : `<button type="button" class="ut-ib hv-ib${flt ? ' on' : ''}" data-hm-flt aria-haspopup="menu" aria-label="Show: Today, Kept or Done${flt ? '. Now ' + esc(flt.label) : ''}" title="Show: Today, Kept or Done">${svg(P.filter, 18)}</button>`)
322
322
  + SO.btnHtml('ut-ib hv-ib' + (SO.layout().sort !== 'mine' ? ' on' : ''))
323
- + `<button type="button" class="ut-ib hv-ib" data-hm-new aria-haspopup="menu" aria-label="New" title="New">${svg(P.plus, 20)}</button></span></div>`
323
+ + `<button type="button" class="ut-ib hv-ib" data-hm-new aria-haspopup="menu" aria-label="New" title="New">${svg(P.plus, 20)}</button>`
324
+ // fold the list to the rail (batch 18 item 15, TbT1Split): the rail's list button brings it back; a phone has no rail
325
+ + (o.phone ? '' : `<button type="button" class="ut-ib hv-ib" data-hm-fold aria-label="Fold the list to the rail" title="Fold the list to the rail">${svg(P.fold, 18)}</button>`) + '</span></div>'
324
326
  + (M.yours ? `<p class="hv-sub">${M.yours} ${M.yours === 1 ? 'is' : 'are'} yours</p>` : '');
325
327
  // the Today card only while the day has a moment; the plain day (its meetings and load) is in Your day
326
328
  const card = MOMENT.has(T.mode) ? todayHtml(T, { greet: M.greet, sub: '', phone: o.phone }) : '';
@@ -0,0 +1,405 @@
1
+ /* pm/ini-edit.js — a task changed where it sits in the Tasks List (feedback batch 18 item 16, agreed A; main canvas In development, frames
2
+ * StA1Rows to StA10bDragPhone, stickies stRules and stWhy). pm/ini-view.js draws the List and calls this file for the parts below; the
3
+ * Board's panel and Home's initiative page draw the same List, so both get them.
4
+ *
5
+ * openOf(id) / addOf(id) the task whose row is open in place, and the stage whose + field is open (one each per initiative)
6
+ * stagesSet(id, v) the stages a task can move to (the workflow's, then Not in a stage), from the view by stage
7
+ * rowHtml(x, o) the open row (StA2Edit): the name field (a Jira row: its title and "<Status> in Jira · read N min ago"),
8
+ * then ONE quiet line: the status icon chip, the date chips (Start – Due; a milestone: one ◇ chip; none: a
9
+ * dashed Dates chip) and ⋯ right after the dates (StA8Desk)
10
+ * ticketHtml(k, o) an unlinked Jira ticket's open row: the same, with Open the ticket in place of ⋯ (its place is Jira's)
11
+ * plusHtml(sec, id, o) the + on an open stage's header: "New task in <stage>" (StA5Add)
12
+ * addHtml(sec, id) the field at the top of that stage's list, with an optional Dates chip
13
+ * press(b, d, root, H, e) a press this file owns → true: a title (opens the row), ⋯ and its menu, the +, the field's Dates chip
14
+ * wire(body) once per body: the name field (Enter or blur saves, Esc closes), the add field (Enter adds and stays open),
15
+ * a press outside the open row closes it, and the drag (StA10Drag): a grip on hover on a desktop, a long press
16
+ * on the title on a phone; the target stage lights up and a blue line shows where the task lands
17
+ * writes(h) the host's handlers with the writes this file needs, where the host has none: h.rename(uid, title),
18
+ * h.move(uid, { to, from, ids, name }) (a stage, and the order inside it), each with Undo in the toast,
19
+ * h.jiraMove({ key, to, from, fromRaw }) (a Jira ticket's status, moved in Jira: pm/jira-move.js)
20
+ *
21
+ * A move never changes a task's status or dates. Zero is silence: a row with no dates shows none. Icon-only presses carry their words in
22
+ * aria-label and title. */
23
+ import * as TV from './ini-tasks.js';
24
+ import { stateIcon, freshness } from './task-card.js';
25
+ import { pmPost } from './http.js';
26
+ import * as JM from './jira-move.js';
27
+
28
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
29
+ const SVG = (d, w = 16, sw = 1.8) => `<svg aria-hidden="true" width="${w}" height="${w}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${sw}" stroke-linecap="round" stroke-linejoin="round"><path d="${d}"/></svg>`;
30
+ const P = {
31
+ more: 'M5 12h.01M12 12h.01M19 12h.01', plus: 'M12 5v14M5 12h14', check: 'M5 12l5 5 9-10', down: 'M7 10l5 5 5-5', right: 'M10 7l5 5-5 5', left: 'M14 7l-5 5 5 5',
32
+ dia: 'M12 4l8 8-8 8-8-8z', cal: 'M4 5h16v15H4zM8 3v4M16 3v4M4 10h16', grip: 'M9 6h.01M15 6h.01M9 12h.01M15 12h.01M9 18h.01M15 18h.01',
33
+ open: 'M14 4h6v6M20 4l-9 9M18 14v6H4V6h6', bin: 'M5 7h14M10 7V4h4v3M7 7l1 13h8l1-13',
34
+ };
35
+
36
+ /* ── what is open, per initiative ── */
37
+ const OPEN = new Map(); // initiative id → the uid of the row open in place
38
+ const ADD = new Map(); // initiative id → the stage key whose + field is open
39
+ const ADD_D = new Map(); // initiative id → { start, due } the add field's Dates chip picked
40
+ const STAGES = new Map(); // initiative id → [{ key, name }] the stages a task can move to
41
+ const VIEW = new Map(); // initiative id → the view the List drew last (the drag reads its stages' tasks)
42
+ export const openOf = (id) => OPEN.get(id) || '';
43
+ export const addOf = (id) => (ADD.has(id) ? ADD.get(id) : null);
44
+ /** For the tests: close every open row and field. */
45
+ export const reset = () => { OPEN.clear(); ADD.clear(); ADD_D.clear(); STAGES.clear(); VIEW.clear(); };
46
+ /** The stages of the view by stage (v0), in workflow order, then Not in a stage. Folded lines (past, Later) hold their stages inside.
47
+ * v: the view as the List draws it (grouped as the PM picked). */
48
+ export function stagesSet(id, v0, v) {
49
+ VIEW.set(id, v || v0);
50
+ v = v0;
51
+ const out = [];
52
+ const walk = (s) => { if (s.stages) { s.stages.forEach(walk); return; } if (s.kind === 'stage') out.push({ key: s.key, name: s.name }); };
53
+ for (const s of (v.tasks && v.tasks.sections) || []) walk(s);
54
+ out.push({ key: '', name: 'Not in a stage' });
55
+ STAGES.set(id, out);
56
+ }
57
+ const stageName = (id, key) => { const s = (STAGES.get(id) || []).find((x) => x.key === key); return s ? s.name : key || 'Not in a stage'; };
58
+
59
+ /* ── the open row (StA2Edit, StA6Jira, StA8Desk) ── */
60
+ const chip = (cls, attrs, inner, label) => `<button type="button" class="iv-edc ${cls}" ${attrs} aria-label="${esc(label)}" title="${esc(label)}">${inner}</button>`;
61
+ /** The date chips: a milestone's one ◇ day; else Start – Due; with no dates one dashed Dates chip. The press opens the task card's picker. */
62
+ function datesHtml(x, uid) {
63
+ const base = `data-iv-date="${esc(uid)}" data-s="${esc(x.start)}" data-e="${esc(x.end)}" data-t="${esc(x.title)}"`;
64
+ if (x.ms && !x.jiraTk) {
65
+ return x.dueText ? chip('iv-edd ms', `${base} data-one="1"`, `${SVG(P.dia, 13, 2.2)}<b>${esc(x.dueText)}</b>`, 'Milestone date: ' + x.dueText + '. Change')
66
+ : chip('iv-edd ms dash', `${base} data-one="1"`, `${SVG(P.dia, 13, 2.2)}Date`, 'Set the milestone date');
67
+ }
68
+ if (!x.start && !x.end) return chip('iv-edd dash', `${base} data-f="start"`, `${SVG(P.cal, 14, 2)}Dates`, 'Add dates');
69
+ return chip('iv-edd', `${base} data-f="start"`, `<small>Start</small><b>${esc(x.startText || 'None')}</b>`, 'Start: ' + (x.startText || 'none') + '. Change')
70
+ + '<span class="iv-eds" aria-hidden="true">–</span>'
71
+ + chip('iv-edd', `${base} data-f="due"`, `<small>Due</small><b>${esc(x.dueText || 'None')}</b>`, 'Due: ' + (x.dueText || 'none') + '. Change');
72
+ }
73
+ /** "In Progress in Jira · read 4 min ago": a Jira row's status and title are Jira's (read-only here). */
74
+ const jiraLine = (st, at) => `<p class="iv-edj">${esc((st || 'To do') + ' in Jira')}${at ? `<span> · ${esc(freshness(at))}</span>` : ''}</p>`;
75
+ export function rowHtml(x, o, box, name) {
76
+ const jira = !!(x.jkey && !x.dr);
77
+ const field = jira ? `<b class="iv-tt">${name}</b>${jiraLine(x.jst || x.status, o.jiraRead)}`
78
+ : `<form class="iv-edf" data-iv-renf="${esc(x.uid)}"><input type="text" class="iv-edn" data-iv-ren="${esc(x.uid)}" value="${esc(x.title)}" maxlength="200" autocomplete="off" aria-label="Task name" data-was="${esc(x.title)}"></form>`;
79
+ const st = jira ? '' : chip('iv-edst', `data-iv-stat="${esc(x.uid)}" data-st="${esc(x.status)}" data-plain="1" aria-haspopup="dialog"`, `${stateIcon(x.status)}${SVG(P.down, 11, 2.4)}`, 'Status: ' + x.status + '. Change');
80
+ const more = `<button type="button" class="iv-ib iv-edm" data-iv-more="${esc(x.uid)}" aria-haspopup="menu" aria-expanded="false" aria-label="More for this task" title="More">${SVG(P.more, 18, 3)}</button>`;
81
+ return `<div class="iv-tr iv-ed${jira ? ' jr' : ''}" data-esc-layer data-iv-r="${esc(x.uid)}" data-iv-open="${esc(x.uid)}">${box}<span class="w">${field}<span class="iv-edl">${st}${datesHtml(x, x.uid)}${more}</span></span></div>`;
82
+ }
83
+ /** An unlinked Jira ticket's open row (StA6Jira): the start and due kept in PMOS change here; Open the ticket sits after them. */
84
+ export function ticketHtml(k, o) {
85
+ const r = TV.jiraRow(k), x = { ...r, jiraTk: true, startText: k.startText || '', dueText: k.dueText || '' };
86
+ const open = `<button type="button" class="iv-ib iv-edm" data-iv-ticket="${esc(k.key)}" aria-label="Open the ticket" title="Open the ticket">${SVG(P.open, 16, 2)}</button>`;
87
+ return `<div class="iv-tr iv-tkr iv-ed jr" data-esc-layer data-iv-open="${esc(k.key)}"><span class="iv-jq" aria-hidden="true"></span><span class="w"><b class="iv-tt"><em>${esc(k.key)}</em> ${esc(k.title)}</b>${jiraLine(k.status, o.jiraRead)}<span class="iv-edl">${datesHtml(x, k.key)}${open}</span></span></div>`;
88
+ }
89
+
90
+ /* ── + on a stage, and its field (StA5Add) ── */
91
+ export function plusHtml(sec, id, o) {
92
+ if (!o.addIn) return '';
93
+ const nm = sec.name || 'Not in a stage', on = addOf(id) === (sec.key || '');
94
+ return `<button type="button" class="iv-ib iv-plus${on ? ' on' : ''}" data-iv-plus="${esc(sec.key || '')}" data-nm="${esc(nm)}" aria-pressed="${on}" aria-label="${esc('New task in ' + nm)}" title="${esc('New task in ' + nm)}">${SVG(P.plus, 16, 2.2)}</button>`;
95
+ }
96
+ const mdIso = (iso) => { const n = TV.dn(iso); return n == null ? '' : TV.md(n); };
97
+ export function addHtml(sec, id) {
98
+ if (addOf(id) !== (sec.key || '')) return '';
99
+ const nm = sec.name || 'Not in a stage', D = ADD_D.get(id) || {};
100
+ const dt = D.start || D.due ? [mdIso(D.start), mdIso(D.due)].filter(Boolean).join(' – ') : '';
101
+ return `<form class="iv-addf iv-addin" data-esc-layer data-iv-addin="${esc(sec.key || '')}" data-nm="${esc(nm)}"><span class="iv-cb" aria-hidden="true"></span>`
102
+ + `<input type="text" data-iv-addinp maxlength="200" autocomplete="off" placeholder="${esc('New task in ' + nm)}" aria-label="${esc('New task in ' + nm)}">`
103
+ + `<button type="submit" class="iv-go" aria-label="Add the task" title="Add (Enter). Esc closes.">${SVG(P.check, 16, 2.2)}</button></form>`
104
+ + `<div class="iv-addd"><button type="button" class="iv-edc iv-edd${dt ? '' : ' dash'}" data-iv-adddt data-s="${esc(D.start || '')}" data-e="${esc(D.due || '')}" data-f="start" aria-label="${esc(dt ? 'Dates: ' + dt + '. Change' : 'Dates, optional')}" title="Dates, optional">${SVG(P.cal, 14, 2)}${esc(dt || 'Dates')}</button></div>`;
105
+ }
106
+
107
+ /* ── the writes (Undo in the host's toast) ── */
108
+ async function post(H, route, body) {
109
+ const at = H.where ? H.where() : {};
110
+ return pmPost('/api/boards/tasks/' + route, { ws: at.ws, board: at.board, ...body }).catch(() => null);
111
+ }
112
+ const say = (H, m, undo) => { if (H.toast) H.toast(m, undo); };
113
+ const failed = (H, res, m) => { say(H, (res && res.error) || m || 'Nothing was changed.'); return false; };
114
+ const after = async (H) => { if (H.reload) await H.reload(); else if (H.redraw) H.redraw(); };
115
+ /** Add the writes the host does not have. The draft's own writes wrap these (pm/ini-versions.js). */
116
+ export function writes(h) {
117
+ const W = { ...h };
118
+ // a Jira ticket's status (a Kanban drag, its status press): asked of Jira through the jira-move agent, with Undo (pm/jira-move.js)
119
+ if (!W.jiraMove) W.jiraMove = (m) => JM.move(W, m);
120
+ if (!W.rename) W.rename = async (uid, title) => {
121
+ const res = await post(W, 'rename', { task: uid, title });
122
+ if (!res || res.ok === false) return failed(W, res, 'The name was not changed.');
123
+ await after(W);
124
+ const was = res.from;
125
+ say(W, 'Renamed.', was ? async () => { const u = await post(W, 'rename', { task: uid, title: was }); if (!u || u.ok === false) failed(W, u, 'The undo did not land.'); await after(W); } : undefined);
126
+ return true;
127
+ };
128
+ if (!W.move) W.move = async (uid, m) => {
129
+ const id = W.__id ? W.__id() : '', moved = m.to !== m.from;
130
+ let sec = null, ord = null;
131
+ if (moved) { sec = await post(W, 'edit', { task: uid, section: m.to }); if (!sec || sec.ok === false) return failed(W, sec, 'The task was not moved.'); }
132
+ if (m.ids) { ord = await post(W, 'order', { initiative: id, section: m.to, tasks: m.ids }); if (!ord || ord.ok === false) { if (!moved) return failed(W, ord, 'The order was not saved.'); say(W, 'Moved, but not its place in the stage: ' + ((ord && ord.error) || 'the server did not say why') + '.'); ord = null; } }
133
+ await after(W);
134
+ say(W, moved ? 'Moved to ' + (m.name || stageName(id, m.to)) + '.' : 'Order saved.', async () => {
135
+ if (ord) { const u = await post(W, 'order', { initiative: id, section: m.to, tasks: ord.from || [] }); if (!u || u.ok === false) { failed(W, u, 'The undo did not land.'); await after(W); return; } }
136
+ if (moved) { const u = await post(W, 'edit', { task: uid, section: sec.from && typeof sec.from.section === 'string' ? sec.from.section : m.from }); if (!u || u.ok === false) failed(W, u, 'The undo did not land.'); }
137
+ await after(W);
138
+ });
139
+ return true;
140
+ };
141
+ return W;
142
+ }
143
+
144
+ /* ── the presses ── */
145
+ let SUPPRESS = 0; // a long press lifted the row: the click that follows is not a press on the title
146
+ let TOUCHED = 0; // this click opened or kept a row open: the document's own click does not close it
147
+ const rowOf = (v, uid) => {
148
+ for (const s of (v && v.tasks && v.tasks.sections) || []) for (const c of s.stages || [s]) {
149
+ for (const x of [...(c.top || []), ...(c.groups || []).flatMap((g) => g.rows), ...(c.done || []), ...(c.archived || [])]) if (x.uid === uid) return { x, sec: c };
150
+ }
151
+ return null;
152
+ };
153
+ /** The open (not closed) tasks of a stage, top to bottom, as the List draws them. */
154
+ const openIds = (v, key) => {
155
+ for (const s of (v && v.tasks && v.tasks.sections) || []) for (const c of s.stages || [s]) if (c.kind !== 'group' && (c.key || '') === key) return [...(c.top || []), ...(c.groups || []).flatMap((g) => g.rows)].filter((x) => !x.dr).map((x) => x.uid);
156
+ return [];
157
+ };
158
+ export function press(b, d, root, H, e) {
159
+ const id = root.dataset.iv, v = VIEW.get(id);
160
+ if (d.ivEdit) {
161
+ e.preventDefault(); TOUCHED = Date.now();
162
+ if (Date.now() - SUPPRESS < 350) return true;
163
+ OPEN.set(id, d.ivEdit); ADD.delete(id); if (H.redraw) H.redraw();
164
+ focusLater(root, `[data-iv-open="${cssq(d.ivEdit)}"] .iv-edn`, true);
165
+ return true;
166
+ }
167
+ if (d.ivPlus != null) {
168
+ e.preventDefault(); TOUCHED = Date.now();
169
+ if (addOf(id) === d.ivPlus) { ADD.delete(id); ADD_D.delete(id); } else { ADD.set(id, d.ivPlus); ADD_D.delete(id); OPEN.delete(id); }
170
+ if (H.redraw) H.redraw();
171
+ focusLater(root, '[data-iv-addinp]');
172
+ return true;
173
+ }
174
+ if ('ivAdddt' in d) {
175
+ e.preventDefault(); TOUCHED = Date.now();
176
+ TV.datePop(b, '', { dates: (u, p) => { ADD_D.set(id, { ...(ADD_D.get(id) || {}), ...p }); const f = b.closest('.iv-wl'); redrawAdd(f, id); } });
177
+ return true;
178
+ }
179
+ if (d.ivMore) { e.preventDefault(); TOUCHED = Date.now(); moreMenu(b, d.ivMore, id, v, H); return true; }
180
+ if (b.closest('.iv-ed')) TOUCHED = Date.now();
181
+ return false;
182
+ }
183
+ const cssq = (s) => String(s).replace(/["\\]/g, '\\$&');
184
+ function focusLater(root, sel, select) {
185
+ const body = root.parentElement;
186
+ // a host may draw after a read: try for a short while, until the field is there and holds the focus
187
+ let n = 0;
188
+ const go = () => {
189
+ const f = (body && body.isConnected ? body : document).querySelector(sel);
190
+ if (f && document.activeElement !== f) { f.focus({ preventScroll: true }); if (select && f.setSelectionRange) f.setSelectionRange(f.value.length, f.value.length); }
191
+ if ((!f || document.activeElement !== f) && ++n < 40) setTimeout(go, 50); // up to 2 s: a slow host draws late
192
+ };
193
+ if (typeof requestAnimationFrame === 'function') requestAnimationFrame(go); else go();
194
+ }
195
+ /** The add field's Dates chip again, after a pick, without a redraw (the typed words stay). */
196
+ function redrawAdd(list, id) {
197
+ const f = list && list.querySelector('.iv-addd'); if (!f) return;
198
+ const D = ADD_D.get(id) || {}, dt = [mdIso(D.start), mdIso(D.due)].filter(Boolean).join(' – '), c = f.querySelector('[data-iv-adddt]');
199
+ if (!c) return;
200
+ c.dataset.s = D.start || ''; c.dataset.e = D.due || ''; c.classList.toggle('dash', !dt);
201
+ c.setAttribute('aria-label', dt ? 'Dates: ' + dt + '. Change' : 'Dates, optional');
202
+ c.innerHTML = SVG(P.cal, 14, 2) + esc(dt || 'Dates');
203
+ }
204
+ /** ⋯ of the open row (StA2bMore): Milestone (or Make it a plain task), Move to a stage, Open the task card (Open the ticket on a Jira row),
205
+ * Delete (only where the task can be deleted; never a Jira row). Move to a stage turns the menu into the workflow's stages, ← goes back. */
206
+ function moreMenu(b, uid, id, v, H) {
207
+ const f = rowOf(v, uid); if (!f) return;
208
+ const x = f.x, jira = !!(x.jkey && !x.dr), cur = f.sec.kind === 'stage' || f.sec.kind === 'none' ? f.sec.key || '' : null;
209
+ const del = !jira && !!H.remove && TV.deletable(uid);
210
+ const item = (attr, ico, label, extra = '') => `<button type="button" role="menuitem" class="o" ${attr}><span class="ck" aria-hidden="true">${SVG(ico, 15, 2)}</span><span>${esc(label)}</span>${extra}</button>`;
211
+ const main = () => `<div class="tkc-pop ivq-m ive-m" role="menu" aria-label="More for this task">`
212
+ + item('data-ive-ms', P.dia, x.ms ? 'Make it a plain task' : 'Milestone')
213
+ + item('data-ive-mv aria-haspopup="menu"', P.grip, 'Move to a stage', `<span class="k" aria-hidden="true">${SVG(P.right, 14, 2)}</span>`)
214
+ + item('data-ive-card', P.open, jira ? 'Open the ticket' : 'Open the task card')
215
+ + (del ? '<hr>' + item('data-ive-del class="o dl"', P.bin, 'Delete task') : '') + '</div>';
216
+ const stages = () => `<div class="tkc-pop ivq-m ive-m" role="menu" aria-label="Move to a stage"><button type="button" class="o ive-bk" data-ive-bk><span class="ck" aria-hidden="true">${SVG(P.left, 15, 2)}</span><span>Move to a stage</span></button><hr>`
217
+ + (STAGES.get(id) || []).map((s) => `<button type="button" role="menuitemradio" class="o${s.key === cur ? ' hl' : ''}" aria-checked="${s.key === cur}" data-ive-to="${esc(s.key)}"><span class="ck" aria-hidden="true">${s.key === cur ? SVG(P.check, 14, 2.4) : ''}</span><span>${esc(s.name)}</span></button>`).join('') + '</div>';
218
+ const el = TV.openPop(b, main(), (o) => {
219
+ const d = o.dataset;
220
+ if ('iveMv' in d) { el.innerHTML = stages(); const c = el.querySelector('[aria-checked="true"], button'); if (c) c.focus({ preventScroll: true }); return; }
221
+ if ('iveBk' in d) { el.innerHTML = main(); return; }
222
+ TV.closePop();
223
+ if ('iveMs' in d) { milestone(H, x, !x.ms); return; }
224
+ if (d.iveTo != null) { if (d.iveTo !== cur && H.move) { OPEN.delete(id); H.move(uid, { to: d.iveTo, from: cur == null ? '' : cur, name: stageName(id, d.iveTo) }); } return; }
225
+ if ('iveCard' in d) { OPEN.delete(id); if (jira) { if (H.openTicket) H.openTicket(x.jkey, b); } else if (H.openTask) H.openTask(uid, b); return; }
226
+ if ('iveDel' in d && del) { OPEN.delete(id); H.remove(uid); }
227
+ }, { right: true });
228
+ }
229
+ /** A milestone has one date (StA4Milestone): turning ◇ on keeps the due day (or the start, when it has no due day) and clears the start; the
230
+ * host's Undo puts both back. */
231
+ function milestone(H, x, on) {
232
+ if (!H.dates) return;
233
+ const p = { milestone: on };
234
+ if (on && x.start) { p.start = ''; if (!x.end) p.due = x.start; }
235
+ H.dates(x.uid, p);
236
+ }
237
+
238
+ /* ── the fields, the outside press, the drag ── */
239
+ export function wire(body) {
240
+ if (!body || body.__iveWired) return;
241
+ body.__iveWired = true;
242
+ const H = () => body.__iv || {};
243
+ const idOf = () => { const n = body.querySelector('[data-iv]'); return n ? n.dataset.iv : ''; };
244
+ const close = (id) => { if (!id) return; const had = OPEN.has(id) || ADD.has(id); OPEN.delete(id); ADD.delete(id); ADD_D.delete(id); if (had && H().redraw) H().redraw(); };
245
+ // the name: Enter saves and closes the row; a blur saves (the row stays); Esc closes it as it was
246
+ const save = (inp) => {
247
+ const t = inp.value.trim(), was = inp.dataset.was || '';
248
+ if (!t || t === was) { inp.value = was; return false; }
249
+ inp.dataset.was = t;
250
+ if (H().rename) H().rename(inp.dataset.ivRen, t);
251
+ return true;
252
+ };
253
+ body.addEventListener('submit', (e) => {
254
+ const f = e.target.closest('[data-iv-renf], [data-iv-addin]'); if (!f) return;
255
+ e.preventDefault(); e.stopPropagation();
256
+ if (f.dataset.ivRenf != null) { const inp = f.querySelector('[data-iv-ren]'), id = idOf(); OPEN.delete(id); if (!save(inp) && H().redraw) H().redraw(); return; }
257
+ const inp = f.querySelector('[data-iv-addinp]'), t = inp ? inp.value.trim() : '', id = idOf();
258
+ if (!t || !H().addTask) return;
259
+ const D = ADD_D.get(id) || {};
260
+ inp.disabled = true;
261
+ Promise.resolve(H().addTask(t, inp, { section: f.dataset.ivAddin, name: f.dataset.nm, ...(D.start ? { start: D.start } : {}), ...(D.due ? { due: D.due } : {}) })).then(() => {
262
+ // Enter keeps the field open for the next one (StA5Add)
263
+ ADD_D.delete(id);
264
+ const n = body.querySelector('[data-iv-addinp]'); if (n) { if (n === inp) n.value = ''; n.disabled = false; n.focus({ preventScroll: true }); }
265
+ });
266
+ }, true);
267
+ body.addEventListener('focusout', (e) => { const inp = e.target.closest && e.target.closest('[data-iv-ren]'); if (inp && inp.isConnected) save(inp); });
268
+ body.addEventListener('keydown', (e) => {
269
+ if (e.key !== 'Escape') return;
270
+ const inp = e.target.closest && e.target.closest('[data-iv-ren], [data-iv-addinp]');
271
+ if (DRAG) { e.preventDefault(); e.stopPropagation(); dragStop(true); return; }
272
+ if (!inp && !(e.target.closest && e.target.closest('.iv-ed'))) return;
273
+ e.preventDefault(); e.stopPropagation();
274
+ if (inp && inp.dataset.was != null) inp.value = inp.dataset.was;
275
+ close(idOf());
276
+ });
277
+ // Esc with the focus outside the row (after a drill-in and Back, the row is drawn open again and the focus is on the page): the open row
278
+ // or + field is the top layer, so it closes here; the Viewer's own Esc steps aside while any layer is open (cozy-viewer.js)
279
+ window.addEventListener('keydown', (e) => {
280
+ if (e.key !== 'Escape' || e.defaultPrevented || !body.isConnected || DRAG) return;
281
+ const a = document.activeElement;
282
+ if (a && a !== document.body && a.closest && a.closest('[data-esc-layer]')) return; // a picker, a menu or the row itself has it
283
+ if ([...document.querySelectorAll('[data-esc-layer]')].some((l) => !body.contains(l))) return; // another layer is on top
284
+ if (!body.querySelector('.iv-ed, .iv-addin')) return;
285
+ e.preventDefault(); close(idOf());
286
+ });
287
+ // a press outside the open row (and outside its pickers) closes it
288
+ document.addEventListener('click', (e) => {
289
+ const id = idOf(); if (!id || !body.isConnected || (!OPEN.has(id) && !ADD.has(id)) || Date.now() - TOUCHED < 50) return;
290
+ const t = e.target; if (!t || !t.closest || t.closest('.iv-ed, .iv-addin, .iv-addd, .tkc.ivq, .vs-scrim, .cz-toast, [role="status"]')) return;
291
+ if (!t.isConnected) return;
292
+ close(id);
293
+ });
294
+ /* the drag (StA10Drag, StA10bDragPhone) */
295
+ body.addEventListener('pointerdown', (e) => {
296
+ const g = e.target.closest && e.target.closest('[data-iv-grip]');
297
+ if (g && e.button === 0) { e.preventDefault(); dragStart(body, g.closest('.iv-tr'), e); return; }
298
+ const t = e.target.closest && e.target.closest('[data-iv-edit][data-drag]');
299
+ if (t && (e.pointerType === 'touch' || coarse())) {
300
+ LP_off();
301
+ // a touch keeps sending its events to the element it began on: when a read draws the list again mid-press, that element leaves the
302
+ // page and its events no longer reach the document, so it hands them on itself while it is out of the page
303
+ const out = (fn) => (ev) => { if (!t.isConnected) fn(ev); };
304
+ const mv = out(docMove), up = out(docUp), cn = out(docCancel), tm = (ev) => { if (DRAG) ev.preventDefault(); }; // and the page does not scroll
305
+ const off = () => { t.removeEventListener('pointermove', mv); t.removeEventListener('pointerup', up); t.removeEventListener('pointercancel', cn); t.removeEventListener('touchmove', tm); };
306
+ t.addEventListener('pointermove', mv); t.addEventListener('touchmove', tm, { passive: false }); t.addEventListener('pointerup', (ev) => { up(ev); off(); }, { once: true }); t.addEventListener('pointercancel', (ev) => { cn(ev); off(); }, { once: true });
307
+ LP = { x: e.clientX, y: e.clientY, t: setTimeout(() => { LP = null; SUPPRESS = Date.now(); dragStart(body, t.closest('.iv-tr'), { clientX: LPX.x, clientY: LPX.y, pointerId: e.pointerId }); }, 450) };
308
+ LPX = { x: e.clientX, y: e.clientY };
309
+ }
310
+ });
311
+ body.addEventListener('contextmenu', (e) => { if (e.target.closest && e.target.closest('[data-iv-edit][data-drag]') && coarse()) e.preventDefault(); });
312
+ if (!wire.doc) {
313
+ wire.doc = true;
314
+ document.addEventListener('pointermove', docMove);
315
+ document.addEventListener('pointerup', docUp);
316
+ document.addEventListener('pointercancel', docCancel);
317
+ document.addEventListener('touchmove', (e) => { if (DRAG) e.preventDefault(); }, { passive: false });
318
+ }
319
+ }
320
+ function docMove(e) { if (LP) { LPX = { x: e.clientX, y: e.clientY }; if (Math.abs(e.clientX - LP.x) + Math.abs(e.clientY - LP.y) > 10) LP_off(); } if (DRAG) dragMove(e); }
321
+ function docUp() { LP_off(); if (DRAG) dragStop(false); }
322
+ function docCancel() { LP_off(); if (DRAG) dragStop(true); }
323
+ const coarse = () => typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches;
324
+ let LP = null, LPX = { x: 0, y: 0 };
325
+ const LP_off = () => { if (LP) { clearTimeout(LP.t); LP = null; } };
326
+
327
+ let DRAG = null;
328
+ function dragStart(body, row, e) {
329
+ if (!row || DRAG) return;
330
+ if (!row.isConnected) { const u = row.dataset.ivR; row = u ? body.querySelector(`.iv-tr[data-iv-r="${cssq(u)}"]`) : null; if (!row) return; }
331
+ const wbs = row.closest('.iv-wbs'), list = row.closest('.iv-wl[data-iv-sec]'); if (!wbs || !list) return;
332
+ const r = row.getBoundingClientRect();
333
+ const fly = row.cloneNode(true);
334
+ fly.classList.add('iv-fly'); fly.removeAttribute('data-iv-r'); fly.setAttribute('aria-hidden', 'true'); fly.setAttribute('data-esc-layer', '');
335
+ fly.querySelectorAll('[id]').forEach((n) => n.removeAttribute('id'));
336
+ fly.style.setProperty('--fly-w', r.width + 'px');
337
+ document.body.appendChild(fly);
338
+ const line = document.createElement('div'); line.className = 'iv-dl'; line.hidden = true; wbs.appendChild(line);
339
+ const tip = document.createElement('div'); tip.className = 'iv-dtip'; tip.hidden = true; document.body.appendChild(tip);
340
+ row.classList.add('iv-ghost');
341
+ document.body.classList.add('iv-dragging');
342
+ DRAG = { body, row, wbs, fly, line, tip, uid: row.dataset.ivR, from: list.dataset.ivSec, dx: e.clientX - r.left, dy: e.clientY - r.top, to: null, before: null };
343
+ dragMove(e);
344
+ }
345
+ // a read that lands mid-drag draws the list again: the ghost and the line follow the new rows
346
+ function live(g) {
347
+ if (!g.wbs.isConnected) { const w = g.body.querySelector('.iv-wbs'); if (w) { g.wbs = w; w.appendChild(g.line); } }
348
+ if (!g.row.isConnected) { const r = g.body.querySelector(`.iv-tr[data-iv-r="${cssq(g.uid)}"]`); if (r) { g.row = r; r.classList.add('iv-ghost'); } }
349
+ }
350
+ function dragMove(e) {
351
+ const g = DRAG; if (!g) return;
352
+ live(g);
353
+ g.fly.style.setProperty('--fly-x', (e.clientX - g.dx) + 'px'); g.fly.style.setProperty('--fly-y', (e.clientY - g.dy) + 'px');
354
+ const el = document.elementFromPoint(e.clientX, e.clientY);
355
+ g.wbs.querySelectorAll('.iv-tgt').forEach((n) => n.classList.remove('iv-tgt'));
356
+ g.to = null; g.before = null; g.line.hidden = true; g.tip.hidden = true;
357
+ if (!el || !g.wbs.contains(el)) return;
358
+ const head = el.closest('.iv-ws[data-iv-sec]');
359
+ const row = el.closest('.iv-tr[data-iv-r]');
360
+ const list = (row && row.closest('.iv-wl[data-iv-sec]')) || el.closest('.iv-wl[data-iv-sec]');
361
+ const W = g.wbs.getBoundingClientRect();
362
+ const at = (y, x0) => { g.line.hidden = false; g.line.style.setProperty('--dl-y', (y - W.top + g.wbs.scrollTop) + 'px'); g.line.style.setProperty('--dl-x', (x0 - W.left) + 'px'); };
363
+ if (head && !row) {
364
+ // a stage's header: the task lands last in that stage
365
+ g.to = head.dataset.ivSec; g.before = null;
366
+ head.classList.add('iv-tgt');
367
+ const L = g.wbs.querySelector(`.iv-wl[data-iv-sec="${cssq(g.to)}"]`), rows = L ? [...L.querySelectorAll(':scope > .iv-tr[data-iv-r]')].filter((n) => n !== g.row) : [];
368
+ const last = rows[rows.length - 1], hr = head.getBoundingClientRect();
369
+ at(last ? last.getBoundingClientRect().bottom : hr.bottom, (last || head).getBoundingClientRect().left);
370
+ } else if (list) {
371
+ g.to = list.dataset.ivSec;
372
+ const h = g.wbs.querySelector(`.iv-ws[data-iv-sec="${cssq(g.to)}"]`); if (h) h.classList.add('iv-tgt');
373
+ const rows = [...list.querySelectorAll(':scope > .iv-tr[data-iv-r]')];
374
+ let y = null, x0 = list.getBoundingClientRect().left;
375
+ for (const n of rows) { const b = n.getBoundingClientRect(); if (e.clientY < b.top + b.height / 2) { g.before = n.dataset.ivR; y = b.top; x0 = b.left; break; } }
376
+ if (y == null) { const n = rows[rows.length - 1]; y = n ? n.getBoundingClientRect().bottom : list.getBoundingClientRect().top; if (n) x0 = n.getBoundingClientRect().left; }
377
+ if (g.before === g.uid) g.before = (() => { const i = rows.findIndex((n) => n.dataset.ivR === g.uid); const nx = rows[i + 1]; return nx ? nx.dataset.ivR : null; })();
378
+ at(y, x0);
379
+ }
380
+ if (g.to != null) {
381
+ const id = g.body.querySelector('[data-iv]').dataset.iv;
382
+ const nm = stageName(id, g.to), where = g.before ? 'in ' + nm : 'last in ' + nm;
383
+ g.tip.textContent = 'Drop: ' + where + '. Its dates stay; Undo puts it back';
384
+ g.tip.style.setProperty('--fly-x', (e.clientX + 18) + 'px'); g.tip.style.setProperty('--fly-y', (e.clientY + 14) + 'px');
385
+ g.tip.hidden = false;
386
+ }
387
+ }
388
+ function dragStop(cancel) {
389
+ const g = DRAG; DRAG = null; if (!g) return;
390
+ live(g);
391
+ g.fly.remove(); g.line.remove(); g.tip.remove(); g.row.classList.remove('iv-ghost');
392
+ document.body.classList.remove('iv-dragging');
393
+ g.wbs.querySelectorAll('.iv-tgt').forEach((n) => n.classList.remove('iv-tgt'));
394
+ SUPPRESS = Date.now();
395
+ if (cancel || g.to == null) return;
396
+ const H = g.body.__iv || {}, id = g.body.querySelector('[data-iv]').dataset.iv, v = VIEW.get(id);
397
+ const f = rowOf(v, g.uid), dr = f && f.x.dr;
398
+ const ids = openIds(v, g.to).filter((u) => u !== g.uid);
399
+ const i = g.before ? ids.indexOf(g.before) : -1;
400
+ ids.splice(i < 0 ? ids.length : i, 0, g.uid);
401
+ const was = openIds(v, g.from);
402
+ if (g.to === g.from && was.join('\n') === ids.join('\n')) return;
403
+ OPEN.delete(id);
404
+ if (H.move) H.move(g.uid, { to: g.to, from: g.from, ids: dr ? null : ids, name: stageName(id, g.to) });
405
+ }