Files
dbx-main/tests/js/board_drive.browser.test.js
T
king f904d5935c feat(프로젝트): 설명란 하이퍼링크 글자 크기·굵기 변경
- 링크는 한 글자처럼 잠겨(contenteditable=false) execCommand 서식이 안 들어갔다
- 고른 범위의 링크는 링크 안쪽 span style 로 크기(글자 크기 도구)·굵기(굵게 버튼·Ctrl+B)
- 링크 기본이 굵게라 보통 = font-weight: 400, 서버 desc_inline_style 이 400 만 허용
- 글자와 같이 고르면 글자에 적용된 굵기를 따름
- project.js 캐시 버전 20261030b, 브라우저·sanitize 테스트 추가

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:41:47 +09:00

230 lines
16 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 실제 브라우저 — 보드 카드 끌기(필터를 켠 브라우저에서도 섹션 안 순서 변경, 숨은 업무는 제자리)와
// 파일 → 구글 드라이브(설명란 = 놓은 자리에 링크, 보드 카드 = 서버가 설명 끝에 링크 append) (2026-10-19).
// 서버는 가짜(이 파일의 http 서버), 화면은 실제 템플릿 렌더 결과.
// python tests/js/render_project.py
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/board_drive.browser.test.js
const fs = require("node:fs"), path = require("node:path"), http = require("node:http");
const { chromium } = require("playwright");
const ROOT = path.resolve(__dirname, "../.."), OUT = path.join(__dirname, ".out"), STATIC = path.join(ROOT, "app/static");
const fails = [];
function check(name, cond, extra) {
if (cond) console.log("PASS " + name);
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
}
// 렌더된 보드(할 일 섹션 = 작업 A·B) 에 완료된 C(필터 "미완료"로 숨김)와 D 를 더한다
function boardHtml() {
let html = fs.readFileSync(path.join(OUT, "project_render.html"), "utf8");
return html.replace(/(<script id="pj-data" type="application\/json">)([\s\S]*?)(<\/script>)/, function (_, a, json, c) {
const data = JSON.parse(json);
const base = data.tasks.find(function (t) { return t.id === 101; });
base.description = "<p>앞 글</p>";
const b = data.tasks.find(function (t) { return t.id === 102; });
b.description = '<p>앞 <a href="https://example.com/x">링크 글자</a> 뒤</p><p>끝 링크 <a href="https://example.com/y">마지막</a></p>';
data.tasks.push(Object.assign({}, base, { description: "", id: 104, title: "작업 C(완료)", completed_at: "2026-10-01T00:00:00+09:00", sort_order: 104 }));
data.tasks.push(Object.assign({}, base, { description: "", id: 105, title: "작업 D", sort_order: 105 }));
return a + JSON.stringify(data) + c;
});
}
const orders = [], drives = [], puts = [];
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, "http://localhost");
const json = (code, body) => { res.statusCode = code; res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify(body)); };
if (url.pathname === "/project/p/1") { res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(boardHtml()); return; }
if (url.pathname.startsWith("/project/api/")) {
const chunks = []; for await (const c of req) chunks.push(c);
const raw = Buffer.concat(chunks).toString("utf8");
const order = /^\/project\/api\/projects\/1\/stages\/(\d+)\/tasks\/order$/.exec(url.pathname);
if (order) { orders.push({ stage: +order[1], ids: JSON.parse(raw).ordered_ids }); return json(200, { ok: true }); }
const drive = /^\/project\/api\/tasks\/(\d+)\/drive-files$/.exec(url.pathname);
if (drive && req.method === "POST") {
const name = (/filename="([^"]+)"/.exec(raw) || [])[1] || "file";
const append = /name="append"\r\n\r\ntrue/.test(raw);
drives.push({ id: +drive[1], name: name, append: append });
const f = { id: "FILE" + drives.length + "abcdefgh", name: name, url: "https://drive.google.com/file/d/FILE" + drives.length + "abcdefgh/view" };
const out = { file: f, link_html: "" };
if (append) out.task = { id: +drive[1], project_id: 1, context_project_id: 1, stage_id: 11, title: "작업", description: '<p><a href="' + f.url + '">' + name + "</a></p>" };
return json(201, out);
}
const task = /^\/project\/api\/tasks\/(\d+)$/.exec(url.pathname);
if (task && req.method === "GET") return json(200, { task: { id: +task[1], title: "작업 " + task[1], project_id: 1, context_project_id: 1, stage_id: 11,
description: "<p>앞 글</p>", priority: "normal", assignee_email: "", subtasks: [], links: [], followers: [], access: "full", completed_at: null } });
if (task && req.method === "PUT") {
const body = JSON.parse(raw); puts.push({ id: +task[1], body: body });
return json(200, { task: Object.assign({ id: +task[1], title: "작업", project_id: 1, context_project_id: 1, stage_id: 11 }, body) });
}
if (url.pathname.endsWith("/comments")) return json(200, { comments: [], events: [], features: {} });
if (url.pathname.endsWith("/attachments")) return json(200, { attachments: [] });
if (url.pathname.endsWith("/members")) return json(200, { members: [{ user_email: "me@test.local" }] });
if (url.pathname.endsWith("/live-version")) return json(200, { ts: "v1" });
if (url.pathname.endsWith("/alerts")) return json(200, { me: "me@test.local", latest_id: 0, alerts: [] });
return json(200, {});
}
if (url.pathname.startsWith("/static/")) {
const file = path.join(STATIC, decodeURIComponent(url.pathname.slice("/static/".length)));
if (file.startsWith(STATIC) && fs.existsSync(file)) {
res.setHeader("Content-Type", file.endsWith(".js") ? "text/javascript" : file.endsWith(".css") ? "text/css" : "application/octet-stream");
res.end(fs.readFileSync(file)); return;
}
}
res.statusCode = 404; res.end("");
});
// 파일 끌어 놓기 흉내 — 진짜 File 을 담은 DataTransfer 로 dragenter·dragover·drop
async function dropFile(page, selector, name) {
await page.evaluate(function (a) {
const target = document.querySelector(a.sel);
const r = target.getBoundingClientRect();
const dt = new DataTransfer();
dt.items.add(new File(["hello"], a.name, { type: "text/plain" }));
const opts = { bubbles: true, cancelable: true, dataTransfer: dt, clientX: r.left + 10, clientY: r.top + Math.min(10, r.height / 2) };
["dragenter", "dragover", "drop"].forEach(function (k) { target.dispatchEvent(new DragEvent(k, opts)); });
}, { sel: selector, name: name });
}
(async function () {
await new Promise(r => server.listen(0, "127.0.0.1", r));
const base = "http://127.0.0.1:" + server.address().port;
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
try {
const page = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
page.on("pageerror", e => console.log("PAGEERR", e.message));
// 이 브라우저에는 "미완료만" 필터가 저장돼 있다(다른 컴퓨터는 없음) — 예전엔 이 상태에서 섹션 안 이동이 늘 제자리로
await page.addInitScript(() => {
localStorage.setItem("pj_filter_1", JSON.stringify({ status: "open" }));
localStorage.setItem("pj_view", "board");
});
await page.goto(base + "/project/p/1");
await page.waitForSelector('.pj-card[data-task-id="105"]');
check("필터(미완료) — 완료된 C 는 보드에 안 보임", !(await page.$('.pj-card[data-task-id="104"]')));
// ── 1) 섹션 안 카드 끌기: D 를 A 위로
const a = await page.locator('.pj-card[data-task-id="101"]').boundingBox();
const d = await page.locator('.pj-card[data-task-id="105"]').boundingBox();
await page.mouse.move(d.x + d.width / 2, d.y + d.height / 2);
await page.mouse.down();
await page.mouse.move(d.x + d.width / 2, d.y + d.height / 2 - 8, { steps: 3 });
for (let i = 1; i <= 12; i++) await page.mouse.move(a.x + a.width / 2, d.y + (a.y + 4 - d.y) * i / 12, { steps: 2 });
await page.waitForTimeout(150);
await page.mouse.up();
await page.waitForTimeout(400);
check("필터를 켠 채 섹션 안 이동 — 순서 저장 요청", orders.length === 1, orders);
check("숨은 C 는 제자리, D 는 A 앞", orders[0] && JSON.stringify(orders[0].ids) === JSON.stringify([105, 101, 102, 104]), orders[0]);
const ids = await page.$$eval('.pj-col-body .pj-card[data-task-id]', els => els.map(e => +e.dataset.taskId));
check("보드도 D·A·B 순서로 다시 그림", JSON.stringify(ids.slice(0, 3)) === JSON.stringify([105, 101, 102]), ids);
// ── 2) 보드 카드에 파일 놓기 → 서버가 설명 끝에 링크(append)
await dropFile(page, '.pj-card[data-task-id="102"] .pj-card-title', "견적서.pdf");
await page.waitForTimeout(400);
check("보드 카드 파일 → drive-files(append) 한 번", drives.length === 1 && drives[0].id === 102 && drives[0].append && drives[0].name === "견적서.pdf", drives);
// ── 3) 업무 창 설명란에 파일 놓기 → 놓은 자리에 "파일 이름.확장자" 링크 + 설명 저장
await page.click('.pj-card[data-task-id="101"] .pj-card-title');
await page.waitForSelector("#pj-t-desc", { state: "visible" });
await page.waitForFunction(() => document.getElementById("pj-t-desc").textContent.includes("앞 글"));
await dropFile(page, "#pj-t-desc", "도면 v2.dwg");
await page.waitForFunction(() => !!document.querySelector('#pj-t-desc a[href*="drive.google.com"]'), null, { timeout: 5000 }).catch(() => {});
const link = await page.evaluate(() => {
const x = document.querySelector('#pj-t-desc a[href*="drive.google.com"]');
return x ? { text: x.textContent, href: x.getAttribute("href"), target: x.getAttribute("target"),
busy: !!document.querySelector("#pj-t-desc .pj-drive-uploading") } : null;
});
check("설명란 파일 → drive-files(append 아님)", drives.length === 2 && drives[1].id === 101 && !drives[1].append, drives);
check("설명란에 '파일 이름.확장자' 링크(새 탭)", link && link.text === "도면 v2.dwg" && /\/file\/d\/FILE2abcdefgh\/view$/.test(link.href) && link.target === "_blank" && !link.busy, link);
await page.waitForTimeout(1600); // 설명 자동 저장(1.2초)
const descPut = puts.filter(p => p.id === 101 && p.body.description != null).pop();
check("링크가 들어간 설명 저장", !!descPut && descPut.body.description.includes("FILE2abcdefgh") &&
/앞.*도면 v2\.dwg<\/a>.*글/.test(descPut.body.description), descPut); // 놓은 자리(앞|글 사이)에 링크
// ── 4) 업무 창이 열린 업무의 카드에 놓으면 서버 append 대신 편집기 끝에(옛 설명 저장이 링크를 지우지 않게)
await dropFile(page, '.pj-card[data-task-id="101"] .pj-card-title', "사진.jpg");
await page.waitForTimeout(500);
const n = await page.$$eval('#pj-t-desc a[href*="drive.google.com"]', els => els.map(e => e.textContent));
check("열린 업무 카드 → 편집기에 링크(append 아님)", drives.length === 3 && !drives[2].append && n.indexOf("사진.jpg") >= 0, { drives: drives, n: n });
// ── 5) 설명란 링크 = 굵게·기울임·밑줄, 한 글자처럼(Backspace·Delete 한 번에 통째로, Ctrl+Z 로 되살림)
await page.keyboard.press("Escape");
await page.waitForTimeout(300);
await page.evaluate(() => { const c = document.querySelector('.pj-card[data-task-id="102"] .pj-card-title'); c.click(); });
await page.waitForFunction(() => document.getElementById("pj-t-desc").textContent.includes("링크 글자"));
const st = await page.evaluate(() => {
const a = document.querySelector("#pj-t-desc a"), cs = getComputedStyle(a);
return { ce: a.getAttribute("contenteditable"), w: cs.fontWeight, i: cs.fontStyle, u: cs.textDecorationLine };
});
check("링크 서식 굵게·기울임·밑줄 + 잠금", st.ce === "false" && +st.w >= 700 && st.i === "italic" && st.u.includes("underline"), st);
function caret(where) { // where: "after1" = 첫 링크 바로 뒤, "before2" = 둘째 링크 바로 앞
return page.evaluate((w) => {
const box = document.getElementById("pj-t-desc"); box.focus();
const as = box.querySelectorAll("a"), r = document.createRange();
if (w === "after1") r.setStart(as[0].nextSibling, 0);
else { const t = as[as.length - 1].previousSibling; r.setStart(t, t.nodeValue.length); }
r.collapse(true); const s = getSelection(); s.removeAllRanges(); s.addRange(r);
}, where);
}
await caret("after1");
await page.keyboard.press("Backspace");
let txt = await page.evaluate(() => ({ t: document.getElementById("pj-t-desc").textContent, n: document.querySelectorAll("#pj-t-desc a").length }));
check("링크 바로 뒤 Backspace 한 번 → 링크 통째로 지움", txt.n === 1 && !txt.t.includes("링크 글자") && txt.t.replace(/ /g, " ").includes("앞 뒤"), txt);
await page.keyboard.press("Control+z");
txt = await page.evaluate(() => document.querySelectorAll("#pj-t-desc a").length);
check("Ctrl+Z 로 링크 되살림", txt === 2, txt);
await caret("before2");
await page.keyboard.press("Delete");
txt = await page.evaluate(() => ({ t: document.getElementById("pj-t-desc").textContent, n: document.querySelectorAll("#pj-t-desc a").length }));
check("링크 바로 앞 Delete 한 번 → 링크 통째로 지움", !txt.t.includes("마지막") && txt.t.includes("끝 링크"), txt);
await page.keyboard.press("Control+z");
// 줄 끝 링크 오른쪽을 눌러 이어 쓰면 링크 밖에 써진다
const last = await page.locator("#pj-t-desc a").last().boundingBox();
await page.mouse.click(last.x + last.width + 40, last.y + last.height / 2);
await page.keyboard.type("추가");
txt = await page.evaluate(() => { const a = [...document.querySelectorAll("#pj-t-desc a")].pop(); return { a: a.textContent, p: a.parentElement.textContent }; });
check("줄 끝 링크 뒤에 이어 쓰기(링크 밖)", txt.a === "마지막" && /마지막추가$/.test(txt.p), txt);
await page.waitForTimeout(1600);
const saved = puts.filter(p => p.id === 102 && p.body.description != null).pop();
check("저장 HTML 에 잠금 표시(contenteditable) 없음", !!saved && !saved.body.description.includes("contenteditable"), saved);
// ── 6) 링크 서식(2026-10-30) — 링크만 고르고 크기·굵기 바꾸기(잠긴 링크라 예전엔 안 바뀌었다), 글자와 같이 고르면 같은 굵기
function selectLink(i, withBefore) {
return page.evaluate((a) => {
const box = document.getElementById("pj-t-desc"); box.focus();
const link = box.querySelectorAll("a")[a.i], r = document.createRange();
if (a.withBefore) r.setStart(link.previousSibling, 0); else r.setStartBefore(link);
r.setEndAfter(link);
const s = getSelection(); s.removeAllRanges(); s.addRange(r);
}, { i: i, withBefore: withBefore });
}
const linkSt = (i) => page.evaluate((n) => {
const a = document.querySelectorAll("#pj-t-desc a")[n], t = a.querySelector("span[style]") || a, cs = getComputedStyle(t);
return { size: cs.fontSize, w: +cs.fontWeight, ce: a.getAttribute("contenteditable"), html: a.innerHTML };
}, i);
await selectLink(0, false);
await page.click('.pj-desc-fmtbtn[data-cmd="textSize"]');
await page.click('.pj-desc-stylepop button[data-v="18px"]');
let ls = await linkSt(0);
check("링크만 골라 크기 크게(18px), 링크는 그대로 잠김", ls.size === "18px" && ls.ce === "false" && ls.html.includes("링크 글자"), ls);
await selectLink(0, false);
await page.click('.pj-desc-fmtbtn[data-cmd="bold"]');
ls = await linkSt(0);
check("링크 굵게 버튼 → 보통(기본이 굵게라 끔), 크기는 그대로", ls.w === 400 && ls.size === "18px", ls);
await selectLink(0, false);
await page.keyboard.press("Control+b");
ls = await linkSt(0);
check("Ctrl+B → 다시 굵게", ls.w >= 700 && ls.size === "18px", ls);
await selectLink(0, true); // "앞 " 글자 + 링크 — 글자가 굵게 되면 링크도 굵게(그대로)
await page.click('.pj-desc-fmtbtn[data-cmd="bold"]');
const mix = await page.evaluate(() => {
const a = document.querySelector("#pj-t-desc a"), t = a.querySelector("span[style]") || a;
// 글자 굵기는 실제 계산값으로(잠긴 링크가 낀 선택에선 queryCommandState 가 틀린다)
const head = a.previousSibling && a.previousSibling.nodeType === 3 ? a.parentElement : a.previousElementSibling;
return { link: +getComputedStyle(t).fontWeight, text: +getComputedStyle(head).fontWeight >= 700 };
});
check("글자와 같이 고르면 링크도 글자와 같은 굵기", (mix.link >= 700) === mix.text, mix);
await page.waitForTimeout(1600);
const saved2 = puts.filter(p => p.id === 102 && p.body.description != null).pop();
check("링크 서식 저장 — 링크 안쪽 span 의 font-size", !!saved2 && /<a [^>]*><span style="font-size: 18px;?">링크 글자<\/span><\/a>/.test(saved2.body.description), saved2 && saved2.body.description);
} finally { await browser.close(); server.close(); }
console.log(fails.length ? "\n" + fails.length + " FAILED" : "\nALL PASS");
process.exit(fails.length ? 1 : 0);
})();