create-pmos 0.377.0 → 0.379.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.
- package/package.json +25 -25
- package/payload/KIT-VERSION +1 -1
- package/payload/planning/evals/eval-calibration.md +1 -1
- package/payload/planning/okrs/health-budgets.md +1 -1
- package/payload/state/discoveries.md +1 -1
- package/workspace/briefing-premium-test.js +1 -1
- package/workspace/changelog.json +24 -0
- package/workspace/guide/briefing-premium.md +14 -8
- package/workspace/lib/chat-files.js +50 -3
- package/workspace/lib/jira-status.js +20 -1
- package/workspace/lib/routes-briefing-premium.js +18 -0
- package/workspace/lib/transcript-read.js +2 -0
- package/workspace/package-lock.json +2 -2
- package/workspace/package.json +1 -1
- package/workspace/premium-chat-attach-test.js +2 -3
- package/workspace/premium-chat-context-test.js +121 -0
- package/workspace/premium-chat-notes-test.js +146 -0
- package/workspace/public/pm/chat-context.js +102 -0
- package/workspace/public/pm/premium-attach.js +17 -6
- package/workspace/public/pm/premium-notes.js +227 -0
- package/workspace/public/pm/premium-shell.js +43 -7
- package/workspace/public/pm/premium-vw-ctx.js +70 -0
- package/workspace/public/pm/premium-vw-notepad.css +41 -0
- package/workspace/public/pm/premium.css +16 -21
- package/workspace/server.js +5 -0
- package/workspace/test-lists/premium-chat-context.json +9 -0
- package/workspace/test-lists/premium-chat-notes.json +13 -0
- package/workspace/premium-pad-test.js +0 -125
- package/workspace/public/pm/premium-pad.js +0 -89
- package/workspace/test-lists/premium-pad.json +0 -13
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
/* premium-chat-notes-test.js — Notes for a premium chat conversation (initiative premium-chat-attach, N1-N7).
|
|
4
|
+
* Serves the real My work page from the real server with a fixture model; notes save through the real /api/chat-file/notes in a scratch state folder.
|
|
5
|
+
* N1 + › Notes opens the notepad in the viewer, the old Scratchpad text is the first note · N2 typed Markdown is saved as a .md file
|
|
6
|
+
* N3 a checkbox ticks · N4 New note and the list · N5 the buttons are icons with names · N6 Add selection · N7 Share with Claude puts the note on
|
|
7
|
+
* the message · N8 the bubble's note chip opens Notes · N9 Delete asks first · N10 phone, both themes */
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const { spawn } = require('child_process');
|
|
11
|
+
const { findBrowser } = require('./lib/find-browser');
|
|
12
|
+
const T = require('./test-run').configure({ name: 'premium-chat-notes' });
|
|
13
|
+
const WP = require('./lib/my-work-premium.js');
|
|
14
|
+
const F = require('./fixtures/my-work-premium-facts.js');
|
|
15
|
+
const lib = require('./lib/chat-files.js');
|
|
16
|
+
|
|
17
|
+
const BASE = T.BASE;
|
|
18
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
19
|
+
const until = async (fn, ms = 6000, step = 100) => { const t0 = Date.now(); for (;;) { const v = await fn(); if (v) return v; if (Date.now() - t0 > ms) return v; await sleep(step); } };
|
|
20
|
+
const results = [];
|
|
21
|
+
const ok = (name, cond, extra = '') => { results.push({ name, cond: !!cond }); console.log(`${cond ? '✓' : '✗'} ${name}${!cond && extra !== '' ? ' — ' + extra : ''}`); };
|
|
22
|
+
let srv = null; let browser = null;
|
|
23
|
+
const finish = async (code) => {
|
|
24
|
+
if (browser) await browser.close().catch(() => {});
|
|
25
|
+
if (srv) { try { srv.kill('SIGKILL'); } catch { /* gone */ } }
|
|
26
|
+
T.killTmux();
|
|
27
|
+
const bad = results.filter((x) => !x.cond).length;
|
|
28
|
+
console.log(`\n${results.length - bad}/${results.length} premium-chat-notes assertions passed`);
|
|
29
|
+
process.exit(code !== undefined ? code : (bad ? 1 : 0));
|
|
30
|
+
};
|
|
31
|
+
process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
|
|
32
|
+
const SHOTS = process.env.NOTES_SHOTS || ''; // a folder: the suite also saves screenshots there for review
|
|
33
|
+
const shot = async (page, n) => { if (SHOTS) await page.screenshot({ path: path.join(SHOTS, n + '.png') }); };
|
|
34
|
+
const KEY = 'work:notes-1';
|
|
35
|
+
const notes = (key = KEY) => lib.listNotes({ runtimeDir: T.STATE_DIR, key }).notes;
|
|
36
|
+
|
|
37
|
+
(async () => {
|
|
38
|
+
const exe = findBrowser();
|
|
39
|
+
if (!exe) { console.log('✗ no Chrome/Chromium on this machine — the suite cannot run'); return finish(1); }
|
|
40
|
+
let chromium;
|
|
41
|
+
try { ({ chromium } = require('playwright-core')); } catch { console.log('✗ playwright-core is not installed'); return finish(1); }
|
|
42
|
+
srv = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore', env: T.env({ PMOS_WS_PORT: String(T.PORT) }) });
|
|
43
|
+
await T.waitForServer(BASE);
|
|
44
|
+
browser = await chromium.launch({ executablePath: exe });
|
|
45
|
+
const model = WP.build({ v: F.view(), now: F.NOW });
|
|
46
|
+
|
|
47
|
+
const open = async ({ w = 1280, h = 900, scheme = 'light' } = {}) => {
|
|
48
|
+
const ctx = await browser.newContext({ viewport: { width: w, height: h }, colorScheme: scheme });
|
|
49
|
+
const page = await ctx.newPage();
|
|
50
|
+
const errors = [], asks = [];
|
|
51
|
+
page.on('pageerror', (e) => errors.push(String((e && e.message) || e)));
|
|
52
|
+
await page.route('**/api/my-work-premium', (r) => r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, state: 'ready', model, as_of: Date.now() }) }));
|
|
53
|
+
await page.route('**/api/briefing-premium/**', (r) => { const rq = r.request(); if (rq.method() !== 'GET') asks.push({ path: new URL(rq.url()).pathname, body: JSON.parse(rq.postData() || '{}') }); r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, turns: [], working: false }) }); });
|
|
54
|
+
await page.goto(BASE + '/premium-work.html', { waitUntil: 'domcontentloaded' });
|
|
55
|
+
await page.waitForFunction(() => document.querySelector('#dBody') !== null);
|
|
56
|
+
return { page, ctx, errors, asks };
|
|
57
|
+
};
|
|
58
|
+
const dlg = (page, key) => page.evaluate(async (key) => { const m = await import('/pm/premium-shell.js'); m.openDlg({ eye: 'Test', title: 'Notes test', say: 'Hello.', noteKey: key, html: '<p>detail</p>' }); m.setTab('chat'); }, key);
|
|
59
|
+
const close = (page) => page.evaluate(async () => { const m = await import('/pm/premium-shell.js'); m.closeDlg(); });
|
|
60
|
+
const openNotes = async (page) => { await page.click('#askPlus'); await page.click('[data-plus="pad"]'); return until(async () => page.isVisible('#ntEd')); };
|
|
61
|
+
const typeIn = async (page, s) => { await page.click('#ntEd'); await page.keyboard.type(s); };
|
|
62
|
+
|
|
63
|
+
// the old Scratchpad of this conversation, as the pad left it
|
|
64
|
+
await fetch(BASE + '/api/scratchpad', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: KEY, text: 'call Dana\nask about Q4' }) });
|
|
65
|
+
|
|
66
|
+
let { page, ctx, errors, asks } = await open();
|
|
67
|
+
await dlg(page, KEY);
|
|
68
|
+
/* N1 */
|
|
69
|
+
ok('N1 the + menu names Notes, not Scratchpad', /Notes/.test(await page.textContent('#plusM')) && !/Scratchpad/.test(await page.textContent('#plusM')));
|
|
70
|
+
ok('N1 the Scratchpad strip and its chip are gone', (await page.$('#sPad')) === null && (await page.$('#sPadT')) === null);
|
|
71
|
+
ok('N1 Notes opens in the viewer as a tab', !!(await openNotes(page)) && /Notes/.test(await page.textContent('#vTabs')));
|
|
72
|
+
ok('N1 the old Scratchpad text is the first note, line by line', !!(await until(async () => notes().length === 1)) && notes()[0].text === 'call Dana\n\nask about Q4' && /call Dana[\s\S]*ask about Q4/.test(await page.textContent('#ntEd')));
|
|
73
|
+
ok('N1 the pad is emptied once its text is a note', !!(await until(async () => { const r = await (await fetch(BASE + '/api/scratchpad?key=' + encodeURIComponent(KEY))).json(); return r.text === ''; })));
|
|
74
|
+
ok('N1 the note title shows in the head', (await page.textContent('#ntSw')).trim() === 'call Dana');
|
|
75
|
+
/* N2 */
|
|
76
|
+
await page.click('[data-nt="new"]');
|
|
77
|
+
ok('N2 New note shows an empty note with a hint', await page.evaluate(() => { const e = document.querySelector('#ntEd'); return !e.textContent.trim() && e.classList.contains('ph') && document.activeElement === e; }));
|
|
78
|
+
await page.keyboard.type('# Q4 review prep'); await page.keyboard.press('Enter');
|
|
79
|
+
await page.keyboard.type('Story for leadership'); await page.keyboard.press('Enter');
|
|
80
|
+
await page.keyboard.type('- Lead with the drop'); await page.keyboard.press('Enter'); await page.keyboard.press('Enter');
|
|
81
|
+
await page.keyboard.type('[] Pull Q3 numbers'); await page.keyboard.press('Enter'); await page.keyboard.type('Draft speaker notes');
|
|
82
|
+
const md = await until(async () => { const n = notes().find((x) => x.title === 'Q4 review prep'); return n && /Draft speaker notes/.test(n.text) ? n.text : null; });
|
|
83
|
+
ok('N2 typed Markdown starts are saved as Markdown', !!md && /^# Q4 review prep$/m.test(md) && /^Story for leadership$/m.test(md) && /^- Lead with the drop$/m.test(md) && /^- \[ \] Pull Q3 numbers$/m.test(md) && /^- \[ \] Draft speaker notes$/m.test(md), JSON.stringify(md));
|
|
84
|
+
ok('N2 the editor shows a heading, a bullet and two checkboxes', await page.evaluate(() => { const e = document.querySelector('#ntEd'); return !!e.querySelector('h1') && e.querySelectorAll('ul:not(.tasks) li').length === 1 && e.querySelectorAll('li.task input[type=checkbox]').length === 2; }));
|
|
85
|
+
ok('N2 the head says Saved', !!(await until(async () => (await page.textContent('#ntSt')) === 'Saved')));
|
|
86
|
+
/* N3 */
|
|
87
|
+
await page.click('#ntEd li.task input');
|
|
88
|
+
ok('N3 ticking a checkbox saves it as done', !!(await until(async () => /^- \[x\] Pull Q3 numbers$/m.test((notes().find((x) => x.title === 'Q4 review prep') || {}).text || ''))) && await page.evaluate(() => document.querySelector('#ntEd li.task').classList.contains('done')));
|
|
89
|
+
await shot(page, 'notes-1280-light');
|
|
90
|
+
/* N4 */
|
|
91
|
+
ok('N4 the head counts two notes', (await page.textContent('.ntn')).trim() === '2 notes');
|
|
92
|
+
await page.click('#ntSw');
|
|
93
|
+
ok('N4 the title opens the list, newest first, with Delete', await page.isVisible('#ntM') && (await page.$$eval('#ntM [data-ntgo]', (xs) => xs.map((x) => x.textContent))).join('|') === 'Q4 review prep|call Dana' && !!(await page.$('#ntM [data-ntdel]')));
|
|
94
|
+
await shot(page, 'list-1280-light');
|
|
95
|
+
await page.click('#ntM [data-ntgo]:nth-child(2)');
|
|
96
|
+
ok('N4 picking a note shows it', /call Dana/.test(await page.textContent('#ntEd')) && (await page.textContent('#ntSw')).trim() === 'call Dana');
|
|
97
|
+
/* N5 */
|
|
98
|
+
ok('N5 New note, Add selection and Share with Claude are icons with a name and a tooltip, no words', await page.evaluate(() => ['new', 'sel', 'share'].every((k) => { const b = document.querySelector(`[data-nt="${k}"]`); return b && !b.textContent.trim() && b.querySelector('svg') && b.getAttribute('aria-label') && b.title; })));
|
|
99
|
+
/* N6 */
|
|
100
|
+
await page.evaluate(() => { const p = [...document.querySelectorAll('#ntEd p')].find((x) => /ask about/.test(x.textContent)); const r = document.createRange(); r.selectNodeContents(p); getSelection().removeAllRanges(); getSelection().addRange(r); });
|
|
101
|
+
await page.click('[data-nt="sel"]');
|
|
102
|
+
ok('N6 Add selection puts only the selected words in the message box', (await page.inputValue('#askIn')) === 'ask about Q4', JSON.stringify(await page.inputValue('#askIn')));
|
|
103
|
+
ok('N6 nothing was sent', asks.length === 0);
|
|
104
|
+
/* N7 */
|
|
105
|
+
await page.fill('#askIn', 'Plan the deck from my note');
|
|
106
|
+
await page.click('#ntSw'); await page.click('#ntM [data-ntgo]:nth-child(1)');
|
|
107
|
+
await page.click('[data-nt="share"]');
|
|
108
|
+
ok('N7 Share with Claude puts the note on the message as a chip', !!(await until(async () => page.evaluate(() => { const c = document.querySelector('#attRow .atc'); return c && /Q4 review prep/.test(c.textContent) && /NOTE/.test(c.textContent); }))));
|
|
109
|
+
await shot(page, 'shared-1280-light');
|
|
110
|
+
await page.click('#askGo');
|
|
111
|
+
const ask = await until(async () => asks.find((a) => a.path.endsWith('/ask')));
|
|
112
|
+
const q4 = notes().find((x) => x.title === 'Q4 review prep');
|
|
113
|
+
ok('N7 send names the note as notes/<id>.md', !!ask && ask.body.text === 'Plan the deck from my note' && JSON.stringify(ask.body.files) === JSON.stringify(['notes/' + q4.id + '.md']), JSON.stringify(ask && ask.body));
|
|
114
|
+
const paths = lib.pathsOf({ runtimeDir: T.STATE_DIR, key: KEY, names: ask.body.files });
|
|
115
|
+
ok('N7 the name resolves to the note file Claude reads', paths.ok && paths.paths[0] === q4.path);
|
|
116
|
+
ok('N7 the note stays after the send', notes().length === 2);
|
|
117
|
+
/* N8 */
|
|
118
|
+
const line = lib.withFiles('Plan the deck from my note', paths.paths).replace(/\n/g, ' ');
|
|
119
|
+
await page.evaluate(async (text) => { const m = await import('/pm/premium-shell.js'); document.querySelector('#dBody .stream').innerHTML = m.sessionHtml({ state: 'conv', messages: [{ role: 'user', text }] }); }, line);
|
|
120
|
+
await page.click('#ntSw'); await page.click('#ntM [data-ntgo]:nth-child(2)');
|
|
121
|
+
await page.click('#dBody .turn.u .atc[data-att]');
|
|
122
|
+
ok('N8 the note chip in the PM\'s bubble opens that note', !!(await until(async () => (await page.textContent('#ntSw')).trim() === 'Q4 review prep')));
|
|
123
|
+
/* N9 */
|
|
124
|
+
await page.click('#ntSw'); await page.click('#ntM [data-ntdel]');
|
|
125
|
+
ok('N9 Delete asks first', await page.isVisible('.vcf'));
|
|
126
|
+
await page.click('.vcf button:has-text("Delete")');
|
|
127
|
+
ok('N9 Delete removes the note and shows the other', !!(await until(async () => notes().length === 1 && /call Dana/.test(await page.textContent('#ntEd')))));
|
|
128
|
+
await close(page);
|
|
129
|
+
ok('N1-N9 no page errors', errors.length === 0, errors.join(' | '));
|
|
130
|
+
await ctx.close();
|
|
131
|
+
|
|
132
|
+
/* N10 phone, both themes */
|
|
133
|
+
for (const scheme of ['light', 'dark']) {
|
|
134
|
+
({ page, ctx, errors } = await open({ w: 390, h: 844, scheme }));
|
|
135
|
+
await dlg(page, KEY);
|
|
136
|
+
ok(`N10 ${scheme}: Notes opens the viewer tab on a phone`, !!(await openNotes(page)));
|
|
137
|
+
await shot(page, 'notes-390-' + scheme);
|
|
138
|
+
ok(`N10 ${scheme}: the notepad fits the width`, await page.evaluate(() => { const w = innerWidth; return ['#ntEd', '.ntf', '.nth'].every((s) => { const r = document.querySelector(s).getBoundingClientRect(); return r.width > 0 && r.left >= 0 && r.right <= w + 1; }); }));
|
|
139
|
+
ok(`N10 ${scheme}: the icon buttons are 44px targets`, await page.evaluate(() => [...document.querySelectorAll('.ntic')].every((b) => b.getBoundingClientRect().height >= 44)));
|
|
140
|
+
await page.click('[data-nt="share"]');
|
|
141
|
+
ok(`N10 ${scheme}: Share with Claude goes back to the conversation with the chip`, !!(await until(async () => page.isVisible('#attRow .atc'))));
|
|
142
|
+
ok(`N10 ${scheme}: no page errors`, errors.length === 0, errors.join(' | '));
|
|
143
|
+
await ctx.close();
|
|
144
|
+
}
|
|
145
|
+
finish();
|
|
146
|
+
})();
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/* chat-context — what one of Claude's answers worked with (initiative premium-chat-viewer, slice 2). Pure: no DOM, so Node tests it.
|
|
2
|
+
* A turn is the PM's message and everything after it up to the next: Claude's words and the tool calls between them (lib/transcript-read.js
|
|
3
|
+
* gives each call its tool name and a short target: the file, the address, the Jira key, the Slack channel). contextOf() turns a turn into a
|
|
4
|
+
* short list of things the viewer can open, the main one first:
|
|
5
|
+
* 1. a file Claude wrote or changed, 2. a thing named in its words (a file path, a Jira key, a link), 3. a thing it only read.
|
|
6
|
+
* Kinds: 'file' (any file, opened read-only), 'jira' (a ticket key), 'slack' (a channel or a message link), 'web' (a Claude artifact, a Google
|
|
7
|
+
* Doc or a Confluence page, see chat-md.js webKind). Nothing here reads a file or calls a route; the viewer does that when a chip is pressed. */
|
|
8
|
+
import { looksFile, webKind, toolName } from './chat-md.js';
|
|
9
|
+
|
|
10
|
+
const MAX = 6;
|
|
11
|
+
const WRITE = /^(write|edit|multiedit|notebookedit|str_replace_based_edit_tool|create_file)$/i;
|
|
12
|
+
const READ = /^(read|notebookread|view)$/i;
|
|
13
|
+
const JIRA_KEY = /\b([A-Z][A-Z0-9]{1,9})-(\d{1,6})\b/g;
|
|
14
|
+
const NOT_JIRA = new Set(['UTF', 'ISO', 'SHA', 'RFC', 'CVE', 'MD', 'HTTP', 'TLS', 'SSL', 'IPV', 'COVID', 'GPT', 'Q1', 'Q2', 'Q3', 'Q4', 'H1', 'H2', 'FY', 'P0', 'P1', 'P2', 'P3', 'P4', 'L2', 'L3', 'L4', 'KR', 'D']);
|
|
15
|
+
const SLACK_LINK = /https:\/\/[\w-]+\.slack\.com\/archives\/[A-Z0-9]+(\/p\d+)?[^\s)\]>"']*/g;
|
|
16
|
+
const URL_RE = /https?:\/\/[^\s)\]>"'`]+/g;
|
|
17
|
+
const PATH_RE = /`([^`\n]+)`|\[[^\]\n]*\]\(([^)\s]+)\)|(?:^|[\s(])((?:~\/|\.{1,2}\/|\/)?[\w.@+-]+(?:\/[\w.@+-]+)+\.[A-Za-z0-9]{1,10})(?=[\s).,;:!?]|$)/gm;
|
|
18
|
+
|
|
19
|
+
const base = (p) => String(p).split('/').filter(Boolean).pop() || String(p);
|
|
20
|
+
const clip = (s, n) => (s.length > n ? s.slice(0, n - 1) + '…' : s);
|
|
21
|
+
const keyOf = (it) => it.kind + ':' + (it.kind === 'file' ? it.path : it.kind === 'jira' ? it.key : it.url || it.channel);
|
|
22
|
+
|
|
23
|
+
/** A Jira key in a tool call's target or input words, or null. */
|
|
24
|
+
export function jiraKeyIn(s) {
|
|
25
|
+
const m = String(s || '').match(/\b[A-Z][A-Z0-9]{1,9}-\d{1,6}\b/);
|
|
26
|
+
return m && !NOT_JIRA.has(m[0].split('-')[0]) ? m[0] : null;
|
|
27
|
+
}
|
|
28
|
+
/** A Slack place from a tool call: { channel, ts } from the target lib/transcript-read.js wrote ("C0123 1700000000.000100" or a link). */
|
|
29
|
+
export function slackOf(target) {
|
|
30
|
+
const t = String(target || '');
|
|
31
|
+
const link = t.match(/https:\/\/[\w-]+\.slack\.com\/archives\/[A-Z0-9]+[^\s]*/); if (link) return { url: link[0] };
|
|
32
|
+
const m = t.match(/\b([CDG][A-Z0-9]{6,})\b(?:\s+(\d{9,}\.\d+))?/);
|
|
33
|
+
return m ? { channel: m[1], ts: m[2] || null } : null;
|
|
34
|
+
}
|
|
35
|
+
/** The address that opens a Slack channel or message: its own link, or the Slack app's address for a channel (the page names no web origin of its own). */
|
|
36
|
+
export const slackUrl = (it) => it.url || ('slack://channel?id=' + encodeURIComponent(it.channel));
|
|
37
|
+
|
|
38
|
+
/** One item for a tool call, or null. */
|
|
39
|
+
function fromCall(c) {
|
|
40
|
+
const n = toolName(c && c.tool), t = String((c && c.target) || '').trim();
|
|
41
|
+
if (!t) return null;
|
|
42
|
+
if (WRITE.test(n) && looksFile(t)) return { kind: 'file', path: t, how: 'wrote' };
|
|
43
|
+
if (READ.test(n) && looksFile(t)) return { kind: 'file', path: t, how: 'read' };
|
|
44
|
+
if (/jira/i.test(n)) { const k = jiraKeyIn(t); if (k) return { kind: 'jira', key: k, how: /edit|create|transition|comment|add/i.test(n) ? 'wrote' : 'read' }; }
|
|
45
|
+
if (/slack/i.test(n)) { const s = slackOf(t); if (s) return { kind: 'slack', ...s, how: /send|post|schedule|update/i.test(n) ? 'wrote' : 'read' }; }
|
|
46
|
+
if (/^https?:\/\//.test(t)) { const w = webKind(t); if (w) return { kind: 'web', url: t, web: w, how: 'read' }; }
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
/** The items Claude's words name: file paths, Jira keys it also touched or whose project it touched, Slack links and web links. */
|
|
50
|
+
function fromText(text, projects) {
|
|
51
|
+
const s = String(text || ''), out = [];
|
|
52
|
+
for (const m of s.matchAll(PATH_RE)) { const p = (m[1] || m[2] || m[3] || '').replace(/:\d+(:\d+)?$/, ''); if (looksFile(p)) out.push({ kind: 'file', path: p, how: 'named' }); }
|
|
53
|
+
for (const m of s.matchAll(SLACK_LINK)) out.push({ kind: 'slack', url: m[0], how: 'named' });
|
|
54
|
+
for (const m of s.matchAll(URL_RE)) { const w = webKind(m[0]); if (w) out.push({ kind: 'web', url: m[0], web: w, how: 'named' }); }
|
|
55
|
+
for (const m of s.matchAll(JIRA_KEY)) if (projects.has(m[1]) && !NOT_JIRA.has(m[1])) out.push({ kind: 'jira', key: m[0], how: 'named' });
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
const RANK = { wrote: 0, named: 1, read: 2 };
|
|
59
|
+
/** The title and the small line a chip shows. */
|
|
60
|
+
export function labelOf(it) {
|
|
61
|
+
if (it.kind === 'file') return { title: clip(base(it.path), 48), sub: it.how === 'wrote' ? 'Claude wrote this' : it.how === 'named' ? 'File' : 'Claude read this' };
|
|
62
|
+
if (it.kind === 'jira') return { title: it.key, sub: 'Jira ticket' };
|
|
63
|
+
if (it.kind === 'slack') return { title: it.channel ? 'Slack channel' : 'Slack message', sub: it.how === 'wrote' ? 'Claude posted here' : 'Slack' };
|
|
64
|
+
return { title: it.web === 'artifact' ? 'Claude artifact' : it.web === 'google' ? 'Google file' : 'Confluence page', sub: it.how === 'named' ? 'Link' : 'Claude read this' };
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* What one turn worked with, the main item first. calls: [{ tool, target }] in order; text: Claude's words in the turn; projects: Jira project
|
|
68
|
+
* prefixes seen anywhere in the conversation's tool calls (a key in the words counts only for a project Claude touched, so "UTF-8" is not a ticket).
|
|
69
|
+
* Returns at most MAX items, each { kind, id, title, sub, how, ... }.
|
|
70
|
+
*/
|
|
71
|
+
export function contextOf(calls, text, projects = new Set()) {
|
|
72
|
+
const seen = new Map();
|
|
73
|
+
const add = (it, order) => { if (!it) return; const k = keyOf(it), was = seen.get(k); if (!was) seen.set(k, { ...it, id: k, order }); else if (RANK[it.how] < RANK[was.how]) seen.set(k, { ...was, how: it.how }); };
|
|
74
|
+
(calls || []).forEach((c, i) => add(fromCall(c), i));
|
|
75
|
+
fromText(text, projects).forEach((it, i) => add(it, 1000 + i));
|
|
76
|
+
// files Claude only searched through (Grep/Glob results) never reach here: only Read, Write and Edit name one file
|
|
77
|
+
return [...seen.values()].sort((a, b) => RANK[a.how] - RANK[b.how] || (a.how === 'wrote' ? b.order - a.order : a.order - b.order)).slice(0, MAX).map((it) => ({ ...it, ...labelOf(it) }));
|
|
78
|
+
}
|
|
79
|
+
/** The Jira project prefixes in a conversation's tool calls. */
|
|
80
|
+
export function jiraProjects(messages) {
|
|
81
|
+
const out = new Set();
|
|
82
|
+
for (const m of messages || []) for (const c of (m && m.calls) || []) { if (!/jira/i.test(toolName(c.tool))) continue; const k = jiraKeyIn(c.target); if (k) out.add(k.split('-')[0]); }
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* The conversation split into turns, each with its context: [{ at, id, done, items }]. at: the index of the assistant message that ends the turn;
|
|
87
|
+
* id: that message's time (stable when older messages scroll out of the read); done: the PM wrote after it, or Claude is waiting (waiting=true)
|
|
88
|
+
* and it is the last turn. A turn with no words from Claude has none. messages: the session conversation (lib/transcript-read.js).
|
|
89
|
+
*/
|
|
90
|
+
export function turnsOf(messages, waiting = false) {
|
|
91
|
+
const ms = messages || [], projects = jiraProjects(ms), out = [];
|
|
92
|
+
let calls = [], words = [], last = -1;
|
|
93
|
+
const close = (done) => { if (last >= 0) out.push({ at: last, id: (ms[last] && ms[last].at) || 'i' + last, done, items: contextOf(calls, words.join('\n'), projects) }); calls = []; words = []; last = -1; };
|
|
94
|
+
ms.forEach((m, i) => {
|
|
95
|
+
if (!m) return;
|
|
96
|
+
if (m.role === 'user') { close(true); return; }
|
|
97
|
+
if (m.role === 'tool') { calls.push(...(m.calls || [])); return; }
|
|
98
|
+
if (m.role === 'assistant') { words.push(m.text || ''); last = i; }
|
|
99
|
+
});
|
|
100
|
+
close(!!waiting);
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/* pm/premium-attach.js — files and photos on a premium chat message (initiative premium-chat-attach; PM, 2026-10-21: "Where is Add photos or file on PMOS?").
|
|
2
|
-
* A + at the left of the message box opens a small menu: Add files or photos, Slash commands,
|
|
2
|
+
* A + at the left of the message box opens a small menu: Add files or photos, Slash commands, Notes. A file can also be dropped on the chat or pasted
|
|
3
3
|
* into the box. Each file is saved at once through POST /api/chat-file (in the workspace state folder, never a repository) and shows as a chip above
|
|
4
4
|
* the text with ×. On send the ask route names each file's path for Claude in one closing line; the PM's bubble shows that line as chips, and a chip
|
|
5
5
|
* opens the file in the viewer: a photo as the picture, a PDF as the document, anything else as a download.
|
|
6
6
|
* attachMarkup() · attachRowMarkup() · mountAttach({ getKey, input, note, onSlash, onPad }) · attachNames() · clearAttach()
|
|
7
|
-
* splitFiles(text) · filesHtml(paths) · openAttachment(path) */
|
|
7
|
+
* splitFiles(text) · filesHtml(paths) · openAttachment(path) · attachSaved(f) (a note that Share with Claude puts on the message) */
|
|
8
8
|
import { pressFetch, pmPost } from './http.js';
|
|
9
9
|
import { vwOpen, vwStyle } from './premium-viewer.js';
|
|
10
10
|
|
|
@@ -25,7 +25,9 @@ export function splitFiles(text) {
|
|
|
25
25
|
return { text: t.slice(0, i).trim(), files: t.slice(i + LEAD.length).replace(/\]\s*$/, '').split(' | ').map((s) => s.trim()).filter(Boolean) };
|
|
26
26
|
}
|
|
27
27
|
/** The name a saved file had when the PM picked it: the folder and the time prefix go. Pure. */
|
|
28
|
-
export const shownName = (p) => String(p || '').split('/').pop().replace(/^\d{8}T\d{6}-/, '');
|
|
28
|
+
export const shownName = (p) => (isNote(p) ? 'Note' : String(p || '').split('/').pop().replace(/^\d{8}T\d{6}-/, ''));
|
|
29
|
+
/** A note shared from Notes (premium-notes.js): <conversation folder>/notes/<id>.md. Pure. */
|
|
30
|
+
export const isNote = (p) => /\/notes\/n[0-9a-z]{6,16}\.md$/.test(String(p || ''));
|
|
29
31
|
/** "214 KB", "1.8 MB". Pure. */
|
|
30
32
|
export const sizeText = (n) => (n >= 1048576 ? (n / 1048576).toFixed(1) + ' MB' : Math.max(1, Math.round(n / 1024)) + ' KB');
|
|
31
33
|
const extOf = (n) => ((/\.([A-Za-z0-9]{1,5})$/.exec(n || '') || [])[1] || 'file').toUpperCase();
|
|
@@ -34,7 +36,7 @@ export const fileUrl = (p) => '/api/chat-file?path=' + encodeURIComponent(p);
|
|
|
34
36
|
/** One chip as HTML. f: { name, path?, size?, state: 'saving'|'saved'|'sent', url? }. Pure. */
|
|
35
37
|
export function chipHtml(f, i) {
|
|
36
38
|
const img = IMG.test(f.name || '') && (f.url || f.path);
|
|
37
|
-
const th = img ? `<img class="ath" alt="" src="${esc(f.url || fileUrl(f.path))}">` : `<span class="ath atx">${esc(extOf(f.name))}</span>`;
|
|
39
|
+
const th = img ? `<img class="ath" alt="" src="${esc(f.url || fileUrl(f.path))}">` : `<span class="ath atx">${esc(f.note || isNote(f.path) ? 'NOTE' : extOf(f.name))}</span>`;
|
|
38
40
|
const meta = f.state === 'saving' ? 'Saving' : f.size ? sizeText(f.size) : '';
|
|
39
41
|
const body = `${th}<span class="atn"><b>${esc(f.name)}</b>${meta ? `<em>${esc(meta)}</em>` : ''}</span>`;
|
|
40
42
|
if (f.state === 'sent') return `<button type="button" class="atc" data-att="${esc(f.path)}" title="Open ${esc(f.name)} beside the conversation">${body}</button>`;
|
|
@@ -45,7 +47,7 @@ export const filesHtml = (paths) => (paths && paths.length ? `<div class="atrow
|
|
|
45
47
|
|
|
46
48
|
export const attachMarkup = () => `<button type="button" class="askplus" id="askPlus" aria-label="Add files, photos or commands" title="Add files, photos or commands" aria-haspopup="menu" aria-expanded="false" aria-controls="plusM" hidden>${PLUS}</button>`
|
|
47
49
|
+ `<div class="plusm" id="plusM" role="menu" aria-label="Add" hidden><button type="button" role="menuitem" data-plus="file">${CLIP}<span>Add files or photos</span><em>or drop, or paste</em></button>`
|
|
48
|
-
+ `<button type="button" role="menuitem" data-plus="slash">${SLASH}<span>Slash commands</span><em>/</em></button><button type="button" role="menuitem" data-plus="pad">${PEN}<span>
|
|
50
|
+
+ `<button type="button" role="menuitem" data-plus="slash">${SLASH}<span>Slash commands</span><em>/</em></button><button type="button" role="menuitem" data-plus="pad">${PEN}<span>Notes</span></button></div>`
|
|
49
51
|
+ `<input type="file" id="askFile" multiple hidden tabindex="-1" aria-hidden="true">`;
|
|
50
52
|
export const attachRowMarkup = () => '<div class="atrow" id="attRow" hidden></div>';
|
|
51
53
|
|
|
@@ -64,6 +66,7 @@ export function mountAttach({ getKey, input, note, onSlash, onPad }) {
|
|
|
64
66
|
if (!plus || !menu || !pick || !row) return;
|
|
65
67
|
const me = { files: [], key: getKey() };
|
|
66
68
|
const say = (t) => { if (note) note.textContent = t; };
|
|
69
|
+
me.say = say;
|
|
67
70
|
me.draw = () => { row.hidden = !me.files.length; row.innerHTML = me.files.map(chipHtml).join(''); };
|
|
68
71
|
A = me;
|
|
69
72
|
const sync = () => {
|
|
@@ -94,7 +97,7 @@ export function mountAttach({ getKey, input, note, onSlash, onPad }) {
|
|
|
94
97
|
const f = me.files[Number(b.dataset.attRm)]; if (!f) return;
|
|
95
98
|
me.files = me.files.filter((x) => x !== f); me.draw();
|
|
96
99
|
if (f.url) URL.revokeObjectURL(f.url);
|
|
97
|
-
if (f.saved) pmPost('/api/chat-file/remove', { key: me.key, name: f.saved }).catch(() => { /* left in the folder; nothing names it */ });
|
|
100
|
+
if (f.saved && !f.note) pmPost('/api/chat-file/remove', { key: me.key, name: f.saved }).catch(() => { /* left in the folder; nothing names it */ });
|
|
98
101
|
if (input) input.focus();
|
|
99
102
|
};
|
|
100
103
|
if (input) input.addEventListener('paste', (e) => {
|
|
@@ -125,6 +128,13 @@ export function mountAttach({ getKey, input, note, onSlash, onPad }) {
|
|
|
125
128
|
}
|
|
126
129
|
me.add = add;
|
|
127
130
|
}
|
|
131
|
+
/** A note already saved (Share with Claude): a chip like a saved file; × takes it off the message and keeps the note. */
|
|
132
|
+
export function attachSaved(f) {
|
|
133
|
+
if (!A || !f || !f.saved) return;
|
|
134
|
+
if (A.files.some((x) => x.saved === f.saved)) return;
|
|
135
|
+
if (A.files.length >= MAX_FILES) { if (A.say) A.say('A message takes ' + MAX_FILES + ' files at most.'); return; }
|
|
136
|
+
A.files.push({ name: f.name, size: f.size, state: 'saved', saved: f.saved, path: f.path, note: !!f.note }); A.draw();
|
|
137
|
+
}
|
|
128
138
|
/** A file dropped anywhere on the chat side. Call from the dialog's drop handler. */
|
|
129
139
|
export function dropFiles(list) { if (A && A.add) A.add([...list]); }
|
|
130
140
|
/** Re-read the key (the session list switched the conversation without redrawing the box). */
|
|
@@ -132,6 +142,7 @@ export function syncAttach() { if (A && A.sync) A.sync(); }
|
|
|
132
142
|
|
|
133
143
|
/** An attachment as a viewer tab: a photo as the picture, a PDF as the document, anything else by name with Download. */
|
|
134
144
|
export function openAttachment(p) {
|
|
145
|
+
if (isNote(p)) return import('./premium-notes.js').then((m) => m.openNotes(p.split('/').pop().replace(/\.md$/, '')));
|
|
135
146
|
vwStyle('doc');
|
|
136
147
|
const name = shownName(p), url = fileUrl(p);
|
|
137
148
|
const view = IMG.test(name) ? `<img class="atview" alt="${esc(name)}" src="${esc(url)}">`
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
/* pm/premium-notes.js — Notes for a premium chat conversation (initiative premium-chat-attach, N1-N7; PM, 2026-10-21: "scratch pad can be converted
|
|
2
|
+
* into a proper notepad"). The Scratchpad strip above the message box is gone; Notes opens in the viewer (on a phone, the viewer tab).
|
|
3
|
+
* · several notes for each conversation, each a Markdown file in the conversation's folder (lib/chat-files.js, under notes/), saved as you type
|
|
4
|
+
* · light formatting typed as Markdown: "# " a heading, "- " a bullet, "1. " a numbered list, "[] " a checkbox; Ctrl+B bold, Ctrl+I italic
|
|
5
|
+
* · the head: the note's title with the list of notes (and Delete), how many, Saved, and New note
|
|
6
|
+
* · the foot: Add selection (the selected words, or the whole note, go into the message box; nothing is sent) and Share with Claude (the note
|
|
7
|
+
* goes on the message as a file, as an attachment does, and Claude reads it when the PM sends)
|
|
8
|
+
* The buttons carry no words, only an icon with a tooltip and a name (PM, 2026-10-21). The old Scratchpad text becomes the first note.
|
|
9
|
+
* mountNotes({ getKey, ws, input, note, show, toChat }) · openNotes(id?) · flushNotes()
|
|
10
|
+
* addToMessage(cur, add) · padToMd(text) · mdShortcut(line) · notesCount(n) pure */
|
|
11
|
+
import { pmGet, pmPost } from './http.js';
|
|
12
|
+
import { vwOpen, vwStyle, vwConfirm, vwClose } from './premium-viewer.js';
|
|
13
|
+
import { parseMd, toMd, toDom, fromDom } from './c3-md.js';
|
|
14
|
+
import { attachSaved } from './premium-attach.js';
|
|
15
|
+
|
|
16
|
+
const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
17
|
+
const ic = (d) => `<svg class="i" viewBox="0 0 24 24"><path d="${d}"/></svg>`;
|
|
18
|
+
const I_NEW = ic('M12 5v14M5 12h14'), I_ADD = ic('M4 6h16M4 11h9M20 11v4a3 3 0 0 1-3 3H8M11 15l-3 3 3 3'), I_SHARE = ic('M12 15V3M7 8l5-5 5 5M5 13v7h14v-7');
|
|
19
|
+
const I_DOWN = ic('M6 9l6 6 6-6'), I_DEL = ic('M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3');
|
|
20
|
+
|
|
21
|
+
/** The message box after Add selection: the added text goes after what is already typed, on a new line. Pure. */
|
|
22
|
+
export function addToMessage(cur, add) {
|
|
23
|
+
const a = String(add || '').replace(/^\n+|\s+$/g, ''); if (!a) return String(cur || '');
|
|
24
|
+
const c = String(cur || '').replace(/\s+$/, '');
|
|
25
|
+
return c ? c + '\n' + a : a;
|
|
26
|
+
}
|
|
27
|
+
const LIST = /^\s*([-*+]|\d+[.)])\s/;
|
|
28
|
+
/** Old Scratchpad text as Markdown: each line stays a line (a blank line between two that are not list items), so nothing joins up. Pure. */
|
|
29
|
+
export function padToMd(text) {
|
|
30
|
+
const ls = String(text || '').replace(/\r/g, '').replace(/^\s*\n|\s+$/g, '').split('\n');
|
|
31
|
+
let out = '';
|
|
32
|
+
ls.forEach((l, i) => { if (i) out += LIST.test(l) && LIST.test(ls[i - 1]) ? '\n' : l.trim() && ls[i - 1].trim() ? '\n\n' : '\n'; out += l; });
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
/** What a line typed so far turns into when it is a Markdown start and a space was just typed. Pure. */
|
|
36
|
+
export function mdShortcut(line) {
|
|
37
|
+
const t = String(line || '').replace(/ /g, ' ');
|
|
38
|
+
const h = /^(#{1,3}) $/.exec(t); if (h) return { kind: 'h' + h[1].length };
|
|
39
|
+
if (/^[-*] $/.test(t)) return { kind: 'ul' };
|
|
40
|
+
if (/^1[.)] $/.test(t)) return { kind: 'ol' };
|
|
41
|
+
if (/^\[ ?\] $/.test(t)) return { kind: 'task' };
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
export const notesCount = (n) => (n > 1 ? n + ' notes' : '');
|
|
45
|
+
|
|
46
|
+
let C = null; // what the shell gave: { getKey, ws, input, note, show, toChat }
|
|
47
|
+
const N = { key: null, notes: [], cur: null, ed: null, el: null, timer: null, dirty: false, chain: Promise.resolve(), state: '' };
|
|
48
|
+
|
|
49
|
+
export function mountNotes(ctx) { flushNotes(); C = ctx; N.key = null; N.notes = []; N.cur = null; N.ed = null; N.el = null; }
|
|
50
|
+
|
|
51
|
+
const noteOf = (id) => N.notes.find((n) => n.id === id) || null;
|
|
52
|
+
const textOf = () => (N.ed ? toMd(fromDom(N.ed)) : '');
|
|
53
|
+
function setState(s) { N.state = s; const e = N.el && N.el.querySelector('#ntSt'); if (e) e.textContent = s; }
|
|
54
|
+
/** Save the open note now (a switch, a share, the dialog closing). Resolves when the server has it. */
|
|
55
|
+
export function flushNotes() {
|
|
56
|
+
if (N.timer) { clearTimeout(N.timer); N.timer = null; }
|
|
57
|
+
if (!N.dirty || !N.key) return N.chain;
|
|
58
|
+
N.dirty = false;
|
|
59
|
+
const key = N.key, text = textOf(), id0 = N.cur;
|
|
60
|
+
N.chain = N.chain.then(async () => {
|
|
61
|
+
const id = id0 || N.cur || null; // a new note's first save, still on its way when this one was asked for, has named it by now
|
|
62
|
+
const r = await pmPost('/api/chat-file/notes', { key, id: id || undefined, text }).catch(() => null);
|
|
63
|
+
if (N.key !== key) return;
|
|
64
|
+
if (!r || !r.ok) { setState('Not saved'); N.dirty = true; return; }
|
|
65
|
+
let n = noteOf(r.id); if (!n) { n = { id: r.id }; N.notes.push(n); if (!N.cur) N.cur = r.id; }
|
|
66
|
+
Object.assign(n, { title: r.title, text, path: r.path, name: r.name });
|
|
67
|
+
if (!N.dirty) setState('Saved');
|
|
68
|
+
head();
|
|
69
|
+
});
|
|
70
|
+
return N.chain;
|
|
71
|
+
}
|
|
72
|
+
function later() { N.dirty = true; setState('Saving…'); if (N.timer) clearTimeout(N.timer); N.timer = setTimeout(flushNotes, 500); }
|
|
73
|
+
|
|
74
|
+
/** Open Notes in the viewer, on the note `id` when given, else the newest. */
|
|
75
|
+
export async function openNotes(id) {
|
|
76
|
+
const key = C && C.getKey(); if (!key) return;
|
|
77
|
+
await flushNotes();
|
|
78
|
+
if (N.key !== key) {
|
|
79
|
+
const r = await pmGet('/api/chat-file/notes?key=' + encodeURIComponent(key)).catch(() => null);
|
|
80
|
+
N.key = key; N.notes = r && r.ok ? r.notes : []; N.cur = null;
|
|
81
|
+
if (!N.notes.length) await claimPad(key);
|
|
82
|
+
}
|
|
83
|
+
N.cur = id && noteOf(id) ? id : N.cur && noteOf(N.cur) ? N.cur : (N.notes[N.notes.length - 1] || {}).id || null;
|
|
84
|
+
vwStyle('doc'); vwStyle('notepad');
|
|
85
|
+
vwOpen({ id: 'notes', title: 'Notes', icon: 'notes', render: draw });
|
|
86
|
+
if (C.show) C.show();
|
|
87
|
+
}
|
|
88
|
+
/* The old Scratchpad of this conversation becomes its first note, once: the pad is emptied after the note is saved. */
|
|
89
|
+
async function claimPad(key) {
|
|
90
|
+
const q = 'key=' + encodeURIComponent(key) + (C.ws ? '&ws=' + encodeURIComponent(C.ws) : '');
|
|
91
|
+
const p = await pmGet('/api/scratchpad?' + q).catch(() => null);
|
|
92
|
+
const text = p && p.ok && typeof p.text === 'string' ? p.text : '';
|
|
93
|
+
if (!text.trim()) return;
|
|
94
|
+
const md = padToMd(text);
|
|
95
|
+
const r = await pmPost('/api/chat-file/notes', { key, text: md }).catch(() => null);
|
|
96
|
+
if (!r || !r.ok) return;
|
|
97
|
+
N.notes.push({ id: r.id, title: r.title, text: md, path: r.path, name: r.name });
|
|
98
|
+
pmPost('/api/scratchpad', { key, ws: C.ws || undefined, text: '' }).catch(() => { /* the pad keeps a copy */ });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function headHtml() {
|
|
102
|
+
const n = noteOf(N.cur);
|
|
103
|
+
return `<div class="nth"><button type="button" class="ntsw" id="ntSw" aria-haspopup="menu" aria-expanded="false" title="Your notes in this conversation"><b>${esc(n ? n.title : 'New note')}</b>${I_DOWN}</button>`
|
|
104
|
+
+ `<span class="ntn">${esc(notesCount(N.notes.length))}</span><span class="gap"></span><span class="ntst" id="ntSt" role="status">${esc(N.state)}</span>`
|
|
105
|
+
+ `<button type="button" class="ntic" data-nt="new" aria-label="New note" title="New note">${I_NEW}</button></div>`;
|
|
106
|
+
}
|
|
107
|
+
function head() { const h = N.el && N.el.querySelector('.nth'); if (h) h.outerHTML = headHtml(); }
|
|
108
|
+
function draw(el) {
|
|
109
|
+
N.el = el; N.state = N.state === 'Saving…' ? N.state : '';
|
|
110
|
+
const n = noteOf(N.cur);
|
|
111
|
+
el.innerHTML = `<div class="ntpad">${headHtml()}<div class="ntmenu" id="ntM" role="menu" hidden></div>`
|
|
112
|
+
+ `<div class="ntd" id="ntEd" contenteditable="true" role="textbox" aria-multiline="true" aria-label="Note" spellcheck="true" data-ph="Write a note. Type # for a heading, - for a bullet, [] for a checkbox."></div>`
|
|
113
|
+
+ `<div class="ntf"><span class="ntw">This conversation · saved on this machine</span>`
|
|
114
|
+
+ `<button type="button" class="ntic" data-nt="sel" aria-label="Add selection to message" title="Add selection to message. Nothing is sent.">${I_ADD}</button>`
|
|
115
|
+
+ `<button type="button" class="ntic pri" data-nt="share" aria-label="Share with Claude" title="Share with Claude: the note goes on your message as a file">${I_SHARE}</button></div></div>`;
|
|
116
|
+
const ed = el.querySelector('#ntEd'); N.ed = ed;
|
|
117
|
+
ed.append(...toDom(parseMd(n ? n.text || '' : ''), document, { editable: true }));
|
|
118
|
+
empty();
|
|
119
|
+
el.onclick = onClick;
|
|
120
|
+
el.onmousedown = (e) => { if (e.target.closest('[data-nt="sel"]')) e.preventDefault(); }; // the selection stays while the button is pressed
|
|
121
|
+
ed.onfocus = () => { try { document.execCommand('defaultParagraphSeparator', false, 'p'); } catch { /* the browser's own */ } };
|
|
122
|
+
ed.oninput = (e) => { if (e.inputType === 'insertText' && e.data === ' ') shortcut(); empty(); later(); };
|
|
123
|
+
ed.onkeydown = onKey;
|
|
124
|
+
ed.onchange = (e) => { const b = e.target; if (b && b.type === 'checkbox') { b.toggleAttribute('checked', b.checked); const li = b.closest('li'); if (li) li.classList.toggle('done', b.checked); later(); } };
|
|
125
|
+
}
|
|
126
|
+
const empty = () => { if (N.ed) N.ed.classList.toggle('ph', !N.ed.textContent.trim() && !N.ed.querySelector('input,hr')); };
|
|
127
|
+
|
|
128
|
+
/* the block the caret is in: a direct child of the editor, or a list item */
|
|
129
|
+
function blockAt() {
|
|
130
|
+
const s = getSelection(); if (!s.rangeCount || !N.ed.contains(s.anchorNode)) return null;
|
|
131
|
+
let n = s.anchorNode;
|
|
132
|
+
while (n && n.parentNode !== N.ed && !(n.nodeType === 1 && n.tagName === 'LI')) n = n.parentNode;
|
|
133
|
+
return n && n !== N.ed ? n : null;
|
|
134
|
+
}
|
|
135
|
+
const caretIn = (node) => { const r = document.createRange(); r.selectNodeContents(node); r.collapse(true); const s = getSelection(); s.removeAllRanges(); s.addRange(r); };
|
|
136
|
+
function shortcut() {
|
|
137
|
+
const b = blockAt(); if (!b || b.tagName === 'LI' || /^H\d$/.test(b.tagName || '')) return;
|
|
138
|
+
const s = getSelection(), r = document.createRange(); r.setStart(b, 0); r.setEnd(s.anchorNode, s.anchorOffset);
|
|
139
|
+
if (r.toString() !== b.textContent) return; // only a start typed at the head of a line that holds nothing else
|
|
140
|
+
const m = mdShortcut(b.textContent); if (!m) return;
|
|
141
|
+
let x, at;
|
|
142
|
+
if (m.kind[0] === 'h') { x = document.createElement(m.kind); x.append(document.createElement('br')); at = x; }
|
|
143
|
+
else {
|
|
144
|
+
x = document.createElement(m.kind === 'ol' ? 'ol' : 'ul'); const li = document.createElement('li'); x.append(li); at = li;
|
|
145
|
+
if (m.kind === 'task') { x.className = 'tasks'; li.className = 'task'; li.append(box(), at = document.createElement('span')); }
|
|
146
|
+
at.append(document.createElement('br'));
|
|
147
|
+
}
|
|
148
|
+
b.replaceWith(x); caretIn(at);
|
|
149
|
+
}
|
|
150
|
+
function box() { const c = document.createElement('input'); c.type = 'checkbox'; c.setAttribute('aria-label', 'Done'); c.setAttribute('contenteditable', 'false'); return c; }
|
|
151
|
+
function onKey(e) {
|
|
152
|
+
if (e.key === 'Enter') { e.stopPropagation(); if (!e.shiftKey && taskEnter()) { e.preventDefault(); later(); } }
|
|
153
|
+
}
|
|
154
|
+
/* Enter in a checkbox item: a new checkbox item below, or, on an empty one, the list ends and a line starts */
|
|
155
|
+
function taskEnter() {
|
|
156
|
+
const li = blockAt(); if (!li || li.tagName !== 'LI' || !li.classList.contains('task')) return false;
|
|
157
|
+
const sp = li.querySelector(':scope > span') || li;
|
|
158
|
+
if (!sp.textContent.trim()) {
|
|
159
|
+
const ul = li.parentNode, p = document.createElement('p'); p.append(document.createElement('br'));
|
|
160
|
+
const rest = [...ul.children].slice([...ul.children].indexOf(li) + 1);
|
|
161
|
+
li.remove(); ul.after(p);
|
|
162
|
+
if (rest.length) { const u2 = ul.cloneNode(false); u2.append(...rest); p.after(u2); }
|
|
163
|
+
if (!ul.children.length) ul.remove();
|
|
164
|
+
caretIn(p); return true;
|
|
165
|
+
}
|
|
166
|
+
const s = getSelection(), r = document.createRange(); r.setStart(s.anchorNode, s.anchorOffset); r.setEnd(sp, sp.childNodes.length);
|
|
167
|
+
const tail = r.extractContents();
|
|
168
|
+
const n = document.createElement('li'); n.className = 'task'; const ns = document.createElement('span');
|
|
169
|
+
if (tail.textContent) ns.append(tail); else ns.append(document.createElement('br'));
|
|
170
|
+
n.append(box(), ns); li.after(n); caretIn(ns);
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function onClick(e) {
|
|
175
|
+
const sw = e.target.closest('#ntSw'); if (sw) { menu(); return; }
|
|
176
|
+
const m = e.target.closest('[data-ntgo]'); if (m) { closeMenu(); await flushNotes(); N.cur = m.dataset.ntgo; draw(N.el); return; }
|
|
177
|
+
if (e.target.closest('[data-ntdel]')) { closeMenu(); del(); return; }
|
|
178
|
+
const b = e.target.closest('[data-nt]'); if (!b) return;
|
|
179
|
+
if (b.dataset.nt === 'new') { await flushNotes(); N.cur = null; N.state = ''; draw(N.el); N.ed.focus(); return; }
|
|
180
|
+
if (b.dataset.nt === 'sel') addSel();
|
|
181
|
+
if (b.dataset.nt === 'share') share();
|
|
182
|
+
}
|
|
183
|
+
function menu() {
|
|
184
|
+
const m = N.el.querySelector('#ntM'), sw = N.el.querySelector('#ntSw');
|
|
185
|
+
if (!m.hidden) { closeMenu(); return; }
|
|
186
|
+
m.innerHTML = N.notes.slice().reverse().map((n) => `<button type="button" role="menuitem" data-ntgo="${esc(n.id)}"${n.id === N.cur ? ' aria-current="true"' : ''}>${esc(n.title)}</button>`).join('')
|
|
187
|
+
+ (noteOf(N.cur) ? `<button type="button" role="menuitem" class="ntdel" data-ntdel="1">${I_DEL}<span>Delete this note</span></button>` : '');
|
|
188
|
+
if (!m.innerHTML) m.innerHTML = '<p class="vwmut">No notes yet.</p>';
|
|
189
|
+
m.hidden = false; m.dataset.escLayer = '1'; sw.setAttribute('aria-expanded', 'true');
|
|
190
|
+
m.onkeydown = (e) => { if (e.key === 'Escape') { e.stopPropagation(); closeMenu(); sw.focus(); } };
|
|
191
|
+
const f = m.querySelector('button'); if (f) f.focus();
|
|
192
|
+
}
|
|
193
|
+
function closeMenu() { const m = N.el && N.el.querySelector('#ntM'); if (!m || m.hidden) return; m.hidden = true; delete m.dataset.escLayer; const sw = N.el.querySelector('#ntSw'); if (sw) sw.setAttribute('aria-expanded', 'false'); }
|
|
194
|
+
if (typeof document !== 'undefined') document.addEventListener('pointerdown', (e) => { if (N.el && !e.target.closest('#ntM,#ntSw')) closeMenu(); }, { capture: true });
|
|
195
|
+
async function del() {
|
|
196
|
+
const n = noteOf(N.cur); if (!n) return;
|
|
197
|
+
if (!(await vwConfirm(N.el, { text: `Delete "${n.title}"? It cannot be brought back.`, yes: 'Delete', no: 'Keep' }))) return;
|
|
198
|
+
if (N.timer) { clearTimeout(N.timer); N.timer = null; } N.dirty = false;
|
|
199
|
+
await N.chain;
|
|
200
|
+
const r = await pmPost('/api/chat-file/notes/remove', { key: N.key, id: n.id }).catch(() => null);
|
|
201
|
+
if (!r || !r.ok) { setState('Not deleted'); return; }
|
|
202
|
+
N.notes = N.notes.filter((x) => x !== n); N.cur = (N.notes[N.notes.length - 1] || {}).id || null; N.state = '';
|
|
203
|
+
draw(N.el);
|
|
204
|
+
}
|
|
205
|
+
function say(t) { if (C && C.note) C.note.textContent = t; }
|
|
206
|
+
function addSel() {
|
|
207
|
+
const input = C && C.input; if (!input || !N.ed) return;
|
|
208
|
+
const s = getSelection(), inEd = s.rangeCount && !s.isCollapsed && N.ed.contains(s.anchorNode);
|
|
209
|
+
const text = inEd ? s.toString() : textOf(); if (!text.trim()) { setState('Nothing to add'); return; }
|
|
210
|
+
input.value = addToMessage(input.value, text);
|
|
211
|
+
input.dispatchEvent(new Event('input', { bubbles: true }));
|
|
212
|
+
if (C.toChat) C.toChat();
|
|
213
|
+
input.focus(); try { input.setSelectionRange(input.value.length, input.value.length); } catch { /* none */ }
|
|
214
|
+
say(inEd ? 'The selection is in your message. Press send when it reads right.' : 'The note is in your message. Press send when it reads right.');
|
|
215
|
+
}
|
|
216
|
+
async function share() {
|
|
217
|
+
if (!N.ed || !textOf().trim()) { setState('Write something first'); return; }
|
|
218
|
+
N.dirty = true; await flushNotes();
|
|
219
|
+
const n = noteOf(N.cur); if (!n || !n.name) { setState('Not saved'); return; }
|
|
220
|
+
attachSaved({ name: n.title, saved: n.name, path: n.path, size: new Blob([n.text || '']).size, note: true });
|
|
221
|
+
if (C.toChat) C.toChat();
|
|
222
|
+
if (C.input) C.input.focus();
|
|
223
|
+
say('The note is on your message. Claude reads it when you send.');
|
|
224
|
+
}
|
|
225
|
+
/** The dialog switched conversation: the open Notes tab belonged to the old one. */
|
|
226
|
+
export function syncNotes() { const k = C && C.getKey(); if (N.key && k !== N.key) { flushNotes(); N.key = null; vwClose('notes'); } }
|
|
227
|
+
if (typeof addEventListener === 'function') addEventListener('pagehide', () => { flushNotes(); });
|