tickets
All repositories: gitoria
8.1 KB
// tests/md-paste-files.mjs — tickets#49: a REAL Ctrl+V of a clipboard that holds text AND a picture (a spreadsheet, an office app) pastes the// text, in every editor, files "on" or "off"; a picture alone still goes to the files where files are "on". A real headless Chrome, a real click// into the visual editor, the clipboard filled through the browser's Clipboard API, then a real Ctrl+V key (rawKeyDown with the paste command).// node tests/md-paste-files.mjs <base-url> <path> <editor-article-selector> <value-field-selector> [pre-click-selector] [sid-cookie] [images: on|off]// exit 0 = all passed, 1 = a check failed. Chrome debug port: PASTE_CHROME_PORT (default 8745).import { spawn } from 'node:child_process';import { rmSync, mkdtempSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';const [BASE, PATH, SEL, VAL, PRE = '', SID = '', FILES = 'off'] = process.argv.slice(2);const DP = Number(process.env.PASTE_CHROME_PORT || 8745), J = JSON.stringify, sleep = ms => new Promise(r => setTimeout(r, ms));const prof = mkdtempSync(join(process.env.PASTE_PROFILE_DIR || tmpdir(), 'pf-'));const ch = spawn('/opt/google/chrome/chrome', ['--headless=new', '--no-sandbox', '--remote-debugging-port=' + DP, '--user-data-dir=' + prof, 'about:blank'], { stdio: 'ignore' });let failed = 0; const check = (n, ok, d) => { console.log((ok ? 'ok ' : 'FAIL ') + n + (ok ? '' : ' ' + d)); if (!ok) failed++; };try {let v; for (let i = 0; i < 60; i++) { try { v = await (await fetch(`http://127.0.0.1:${DP}/json/version`)).json(); break; } catch { await sleep(200); } }const bws = new WebSocket(v.webSocketDebuggerUrl); await new Promise(r => bws.onopen = r);let bid = 0; const bp = new Map(); bws.onmessage = m => { const d = JSON.parse(m.data); if (d.id && bp.has(d.id)) { bp.get(d.id)(d); bp.delete(d.id); } };const bsend = (method, params = {}) => new Promise((res, rej) => { const i = ++bid; bp.set(i, d => d.error ? rej(new Error(J(d.error))) : res(d.result)); bws.send(J({ id: i, method, params })); });await bsend('Browser.grantPermissions', { permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'], origin: BASE });for (const W of [1280, 390]) {const { targetId } = await bsend('Target.createTarget', { url: 'about:blank' });const ws = new WebSocket(`ws://127.0.0.1:${DP}/devtools/page/${targetId}`); await new Promise(r => ws.onopen = r);let id = 0; const pend = new Map();ws.onmessage = m => { const d = JSON.parse(m.data); if (d.id && pend.has(d.id)) { pend.get(d.id)(d); pend.delete(d.id); } };const send = (method, params = {}) => new Promise((res, rej) => { const i = ++id; pend.set(i, d => d.error ? rej(new Error(method + J(d.error))) : res(d.result)); ws.send(J({ id: i, method, params })); });const ev = async e => { const r = await send('Runtime.evaluate', { expression: e, returnByValue: true, awaitPromise: true, userGesture: true }); if (r.exceptionDetails) throw new Error(J(r.exceptionDetails).slice(0, 300)); return r.result.value; };const press = async (key, code, vk, mod, commands) => { await send('Input.dispatchKeyEvent', { type: 'rawKeyDown', modifiers: mod, key, code, windowsVirtualKeyCode: vk, commands }); await send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: mod, key, code, windowsVirtualKeyCode: vk }); };const click = async sel => { const r = await ev(`(()=>{const e=document.querySelector(${J(sel)}); e.scrollIntoView({block:'center'}); const r=e.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+Math.min(r.height/2,20)}})()`); await sleep(250); for (const [type, x] of [['mouseMoved', {}], ['mousePressed', { button: 'left', clickCount: 1 }], ['mouseReleased', { button: 'left', clickCount: 1 }]]) await send('Input.dispatchMouseEvent', { type, x: r.x, y: r.y, ...x }); await sleep(600); };try {await send('Page.enable'); await send('Runtime.enable'); await send('Network.enable');await send('Emulation.setDeviceMetricsOverride', { width: W, height: W < 600 ? 844 : 900, deviceScaleFactor: 1, mobile: W < 600 });if (SID) await send('Network.setCookie', { name: 'hlsid', value: SID, url: BASE, httpOnly: true });await send('Page.bringToFront'); await send('Page.navigate', { url: BASE + PATH });for (let i = 0; i < 120; i++) { try { if (await ev(`document.readyState==='complete' && !!document.querySelector(${J(SEL.split('|')[0])})`)) break; } catch {} await sleep(300); }await sleep(1500);for (const p of PRE ? PRE.split('|') : []) await click(p);await click(SEL);const clip = async (o) => ev(`(async()=>{ const items={}; const o=${J(o)}; if (o.p!==undefined) items['text/plain']=new Blob([o.p],{type:'text/plain'}); if (o.h!==undefined) items['text/html']=new Blob([o.h],{type:'text/html'}); if (o.img) { const cv=document.createElement('canvas'); cv.width=cv.height=8; cv.getContext('2d').fillRect(0,0,8,8); items['image/png']=await new Promise(r=>cv.toBlob(r)); } await navigator.clipboard.write([new ClipboardItem(items)]); return 1; })()`);const value = () => ev(`document.querySelector(${J(VAL)}).value`);const empty = async () => { await click(SEL); await press('a', 'KeyA', 65, 2, ['selectAll']); await press('Delete', 'Delete', 46, 0, ['deleteBackward']); await sleep(300); };const L = `[${W}] `;await empty();await clip({ p: 'PASTE SPREADSHEET TEXT', img: 1 }); await press('v', 'KeyV', 86, 2, ['paste']); await sleep(1200);let val = await value();check(L + 'text + picture on the clipboard: a real Ctrl+V pastes the text and the field has it', val.includes('PASTE SPREADSHEET TEXT'), J(val));check(L + 'text + picture: the text is in the visible editor', (await ev(`document.querySelector(${J(SEL)}).innerText`)).includes('PASTE SPREADSHEET TEXT'), '');check(L + 'text + picture: no picture was taken as a file', !val.includes('!['), J(val));await empty();await clip({ p: 'plain only', h: '<p>plain only</p>' }); await press('v', 'KeyV', 86, 2, ['paste']); await sleep(900);check(L + 'text + html still pastes', (await value()).includes('plain only'), J(await value()));// a file manager copy: text that is only the names / file:// paths of the files, plus the files: the files are about (as before)for (const nm of ['image.png', 'file:///home/someone/Pictures/image.png\n']) {await empty();await clip({ p: nm, img: 1 }); await press('v', 'KeyV', 86, 2, ['paste']);if (FILES === 'on') {let got = false; for (let i = 0; i < 40 && !got; i++) { await sleep(300); got = (await value()).includes('![') || (await ev(`document.querySelectorAll('li.picked, ul.files li').length`)) > 0; }check(L + 'file manager copy (text = ' + J(nm) + ' + the file): the file is attached', got, J(await value()));} else { await sleep(1200); check(L + 'file manager copy, files "off": no name text is inserted', (await value()) === '', J(await value())); }}await empty();await clip({ p: 'image.png and more words', img: 1 }); await press('v', 'KeyV', 86, 2, ['paste']); await sleep(1200);check(L + 'text that is more than the file names + a picture: the text is pasted', (await value()).includes('and more words'), J(await value()));if (FILES === 'on') {await empty();await clip({ img: 1 }); await press('v', 'KeyV', 86, 2, ['paste']);let got = false; for (let i = 0; i < 40 && !got; i++) { await sleep(300); got = (await value()).includes('![') || (await ev(`document.querySelectorAll('li.picked, ul.files li').length`)) > 0; }check(L + 'a picture alone still goes to the files (files "on")', got, J(await value()));} else {await empty();await clip({ img: 1 }); await press('v', 'KeyV', 86, 2, ['paste']); await sleep(1200);check(L + 'a picture alone, files "off": nothing is inserted', (await value()) === '', J(await value()));}} finally { await bsend('Target.closeTarget', { targetId }).catch(() => {}); }}} catch (e) { console.log('FAIL error ' + e.message); failed++; }finally { try { process.kill(ch.pid); } catch {} await sleep(500); rmSync(prof, { recursive: true, force: true }); }console.log(failed ? `${failed} failed` : '0 failed'); process.exit(failed ? 1 : 0);
Branches
Latest commits
- 5d144817Merge branch 'records-t40' into mainTickets
- 44ee6f06|||PR records: #43 #45 livemre
- b8fdeee9Merge branch 'p39-routes' into mainTickets
- a0187a0a|||PR Remove redundant route-order loopmre
- 369e4b9cMerge branch 'k40-lists' into mainTickets
- 9af8e780|||PR Use keyed list mutations for live ticket updatesmre
- 610d8e8aMerge branch 'records-t39' into mainTickets
- 32bcdf24|||PR records: GO P39 K40mre
- 4123c6d1Merge branch 'records-t38' into mainTickets
- cd3641a1|||PR records: day72 deploy live, tickets closedmre
- 7d44d852Merge branch 'records-t37' into mainTickets
- 926f7061|||PR records: merges, D36 deploymre
- bf58534eMerge branch 'l33-final' into mainTickets
- 759a9ac3|||PR thin login (tickets#46, #45): merge main, route entry cleanupmre
- 239436d8Merge remote-tracking branch 'origin/main' into l33-finalmre
- 5822cb3aMerge branch 'o34-clean' into mainTickets
- 0870653c|||PR offline note from __hlOnline, no polling (tickets#41)mre
- 14cf96b4Merge branch 'records-t36' into mainTickets
- 07749fa1|||PR records: day72 + #40 mergedmre
- ecd7e226|||PR Consolidate login and move handler logic into topic libraries (partial)mre