first commit

This commit is contained in:
paige 2026-10-26 13:23:13 -06:00
commit 3c23084c8f
1865 changed files with 415595 additions and 0 deletions

598
BA-Daily-Checklist.html Normal file
View File

@ -0,0 +1,598 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BA Daily Checklist</title>
<style>
:root {
--bg: #f6f7fb;
--card: #ffffff;
--accent: #4a6cf7;
--accent-soft: #e8edff;
--text: #1f2430;
--muted: #7a8195;
--done: #2ecc71;
--border: #e3e6ef;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
background: var(--bg);
color: var(--text);
display: flex;
justify-content: center;
padding: 40px 16px;
}
.container { width: 100%; max-width: 680px; }
header {
display: flex;
align-items: flex-end;
justify-content: space-between;
margin-bottom: 8px;
}
h1 { font-size: 24px; font-weight: 700; }
.date { color: var(--muted); font-size: 14px; margin-top: 4px; }
.progress-wrap {
height: 8px;
background: var(--border);
border-radius: 999px;
overflow: hidden;
margin: 16px 0 8px;
}
.progress-bar {
height: 100%;
width: 0%;
background: linear-gradient(90deg, var(--accent), #7c9bff);
border-radius: 999px;
transition: width .3s ease;
}
.progress-label { font-size: 13px; color: var(--muted); margin-bottom: 20px; }
.section {
background: var(--card);
border: 1px solid var(--border);
border-radius: 14px;
padding: 18px 20px;
margin-bottom: 16px;
box-shadow: 0 1px 3px rgba(20, 30, 60, .05);
}
.section h2 {
font-size: 13px;
text-transform: uppercase;
letter-spacing: .08em;
color: var(--accent);
margin-bottom: 4px;
}
.section .hint {
font-size: 12.5px;
color: var(--muted);
margin-bottom: 10px;
}
label.item {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 9px 6px;
border-radius: 8px;
cursor: pointer;
font-size: 15px;
line-height: 1.4;
transition: background .15s;
}
label.item:hover { background: var(--accent-soft); }
label.item input {
appearance: none;
width: 20px; height: 20px;
min-width: 20px;
border: 2px solid #c4c9d9;
border-radius: 6px;
margin-top: 1px;
cursor: pointer;
display: grid;
place-content: center;
transition: all .15s;
}
label.item input:checked {
background: var(--done);
border-color: var(--done);
}
label.item input:checked::after {
content: "✓";
color: #fff;
font-size: 13px;
font-weight: 700;
}
label.item.checked span {
text-decoration: line-through;
color: var(--muted);
}
.free-item {
display: flex;
gap: 8px;
margin-top: 4px;
}
.free-item input {
flex: 1;
padding: 10px 12px;
border: 1px dashed #c4c9d9;
border-radius: 8px;
font-size: 14px;
font-family: inherit;
}
.free-item button {
padding: 10px 16px;
background: var(--accent);
color: #fff;
border: none;
border-radius: 8px;
font-size: 14px;
cursor: pointer;
}
.free-item button:hover { background: #3a5be0; }
.free-list { margin-top: 10px; }
.free-item-row {
display: flex;
align-items: center;
gap: 8px;
}
.free-item-row .del {
background: none;
border: none;
color: #c4c9d9;
cursor: pointer;
font-size: 16px;
padding: 4px;
}
.free-item-row .del:hover { color: #e74c3c; }
footer {
text-align: center;
color: var(--muted);
font-size: 12px;
margin-top: 24px;
}
.reset-all {
background: none;
border: 1px solid var(--border);
color: var(--muted);
padding: 6px 14px;
border-radius: 8px;
font-size: 13px;
cursor: pointer;
}
.reset-all:hover { border-color: #e74c3c; color: #e74c3c; }
.celebrate {
text-align: center;
padding: 14px;
font-size: 15px;
color: var(--done);
font-weight: 600;
display: none;
}
.celebrate.show { display: block; }
.monday-badge {
display: inline-block;
background: #fff4e5;
color: #b0721f;
border: 1px solid #f0dcb8;
font-size: 11px;
font-weight: 600;
padding: 1px 8px;
border-radius: 999px;
margin-left: 6px;
vertical-align: 2px;
text-transform: none;
letter-spacing: 0;
}
.gantt-tools { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 12px; }
.gantt-tools button {
padding: 7px 14px;
background: var(--accent);
color: #fff;
border: none;
border-radius: 8px;
font-size: 13px;
cursor: pointer;
}
.gantt-tools button:hover { background: #3a5be0; }
.gantt-tools button.secondary { background: none; color: var(--muted); border: 1px solid var(--border); }
.gantt-tools button.secondary:hover { color: #e74c3c; border-color: #e74c3c; background: none; }
.gantt-wrap { overflow-x: auto; }
table.gantt { border-collapse: collapse; width: 100%; table-layout: fixed; font-size: 12px; }
table.gantt th, table.gantt td { border: 1px solid var(--border); padding: 0; height: 30px; }
table.gantt th.day { font-weight: 500; color: var(--muted); font-size: 11px; text-align: center; }
table.gantt th.weekend { background: #fafbff; }
table.gantt th.weekend-today { background: #ffe9a8; }
table.gantt td.task-name {
padding: 6px 10px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-size: 13px;
}
table.gantt td.cell { position: relative; background: #fff; }
table.gantt td.cell.weekend { background: #fafbff; }
.bar {
position: absolute;
top: 7px; bottom: 7px;
border-radius: 5px;
min-width: 4px;
}
.bar.planned { background: #4a6cf7; }
.bar.inprogress, .bar.in_progress, .bar.active, .bar.wip { background: #f5a623; }
.bar.done, .bar.completed, .bar.complete, .bar.closed { background: #2ecc71; }
.bar.blocked, .bar.at_risk, .bar.at-risk { background: #e74c3c; }
.bar.other { background: #9aa3c7; }
.today-col { box-shadow: inset 0 0 0 2px #f5a623 !important; }
.legend { display: flex; gap: 14px; margin-top: 10px; font-size: 12px; color: var(--muted); flex-wrap: wrap; }
.legend span { display: inline-flex; align-items: center; gap: 5px; }
.legend i { width: 12px; height: 12px; border-radius: 3px; display: inline-block; }
.gantt-empty { color: var(--muted); font-size: 13.5px; padding: 14px 6px; line-height: 1.6; }
</style>
</head>
<body>
<div class="container">
<header>
<div>
<h1>📋 BA Daily Checklist</h1>
<div class="date" id="today"></div>
</div>
<button class="reset-all" onclick="resetDay()">Reset today</button>
</header>
<div class="progress-wrap"><div class="progress-bar" id="bar"></div></div>
<div class="progress-label" id="label">0 of 0 done</div>
<div class="celebrate" id="celebrate">🎉 All done — great work today!</div>
<div class="section">
<h2>☀️ Morning</h2>
<div class="hint">Start-of-day check. Monday tasks appear automatically.</div>
<div id="morning"></div>
</div>
<div class="section">
<h2>🌤️ Midday check</h2>
<div class="hint">Re-run the same checks. Already done in the morning and nothing new? Just check it off to skip.</div>
<div id="midday"></div>
</div>
<div class="section">
<h2>🌇 Afternoon check</h2>
<div class="hint">Final pass before end of day. Anything not needed today — check it off.</div>
<div id="afternoon"></div>
</div>
<div class="section">
<h2>🗺️ Roadmap / Gantt</h2>
<div class="gantt-tools">
<button onclick="document.getElementById('csvFile').click()">📁 Load / replace CSV</button>
<button class="secondary" onclick="clearRoadmap()">Remove roadmap</button>
<span id="ganttSource" style="font-size:12px;color:var(--muted)"></span>
<input type="file" id="csvFile" accept=".csv,.txt" style="display:none" onchange="loadCsvFile(this)">
</div>
<div id="ganttBody" class="gantt-empty">
No roadmap loaded yet.<br>
Click <b>📁 Load / replace CSV</b> and pick a CSV file. Expected columns (in this order, or with headers):
<b>task, start, end</b> and optionally <b>status</b> (planned / in progress / done / blocked) and <b>notes</b>.
Dates can be like <b>2025-03-10</b>, <b>3/10/2025</b>, or <b>Mar 10, 2025</b>.
</div>
<div class="legend" id="ganttLegend" style="display:none">
<span><i style="background:#4a6cf7"></i>Planned</span>
<span><i style="background:#f5a623"></i>In progress</span>
<span><i style="background:#2ecc71"></i>Done</span>
<span><i style="background:#e74c3c"></i>Blocked / at risk</span>
<span><i style="background:#9aa3c7"></i>Other</span>
<span style="margin-left:auto">▌ amber outline = today</span>
</div>
</div>
<div class="section">
<h2>Additional items</h2>
<div class="free-item">
<input type="text" id="freeInput" placeholder="Add your own item for today…"
onkeydown="if(event.key==='Enter') addFree()">
<button onclick="addFree()">Add</button>
</div>
<div class="free-list" id="freeList"></div>
</div>
<footer>Progress is saved locally in your browser and resets automatically each day.</footer>
</div>
<script>
const isMonday = new Date().getDay() === 1;
// Same core checks repeated each period. Each is its own checkbox,
// so you can tick "already done / not needed" at any later point.
const CORE = [
"Check approvals",
"Check defects",
"Check emails",
"Check what tickets I could prep for UAT"
];
const MORNING_EXTRA = [
"Add release notes export to SharePoint (Mon)",
"Update / submit the change request form (Mon)",
"Prep the change request for approval (Mon)"
];
const SECTIONS = {
morning: isMonday ? CORE.concat(MORNING_EXTRA) : CORE.slice(),
midday: CORE.slice(),
afternoon: CORE.slice()
};
const SECTIONS_IN_ORDER = ["morning", "midday", "afternoon"];
const todayKey = new Date().toISOString().slice(0, 10);
const storeKey = "ba-checklist-v3-" + todayKey;
const freeKey = "ba-free-v3-" + todayKey;
let state = JSON.parse(localStorage.getItem(storeKey) || "{}");
let free = JSON.parse(localStorage.getItem(freeKey) || "[]");
// ensure all items exist (supports new items added later)
for (const s of SECTIONS_IN_ORDER) {
state[s] = state[s] || [];
for (const item of SECTIONS[s]) {
if (!state[s].includes(item)) state[s].push(item);
}
// drop items that are no longer on the checklist (e.g. moved to Monday-only)
state[s] = state[s].filter(item => SECTIONS[s].includes(item));
if (state[s + "Done"]) {
state[s + "Done"] = Object.fromEntries(
Object.entries(state[s + "Done"]).filter(([k]) => SECTIONS[s].includes(k)));
}
}
function save() {
localStorage.setItem(storeKey, JSON.stringify(state));
localStorage.setItem(freeKey, JSON.stringify(free));
}
function render() {
for (const s of SECTIONS_IN_ORDER) {
const el = document.getElementById(s);
el.innerHTML = "";
for (const item of state[s]) {
const checked = !!(state[s + "Done"] && state[s + "Done"][item]);
const label = document.createElement("label");
label.className = "item" + (checked ? " checked" : "");
const cb = document.createElement("input");
cb.type = "checkbox";
cb.checked = checked;
cb.onchange = () => {
state[s + "Done"] = state[s + "Done"] || {};
state[s + "Done"][item] = cb.checked;
save(); render();
};
const span = document.createElement("span");
span.textContent = item;
if (isMonday && item.includes("(Mon)")) {
const b = document.createElement("span");
b.className = "monday-badge";
b.textContent = "Monday";
span.append(" ", b);
}
label.append(cb, span);
el.appendChild(label);
}
}
const fl = document.getElementById("freeList");
fl.innerHTML = "";
free.forEach((f, i) => {
const row = document.createElement("label");
row.className = "free-item-row item" + (f.done ? " checked" : "");
const cb = document.createElement("input");
cb.type = "checkbox";
cb.checked = f.done;
cb.onchange = () => { f.done = cb.checked; save(); render(); };
const span = document.createElement("span");
span.textContent = f.text;
const del = document.createElement("button");
del.className = "del";
del.textContent = "✕";
del.onclick = (e) => { e.preventDefault(); free.splice(i, 1); save(); render(); };
row.append(cb, span, del);
fl.appendChild(row);
});
const items = SECTIONS_IN_ORDER.flatMap(s => state[s])
.concat(free.map(f => f.text));
const total = items.length;
const done = SECTIONS_IN_ORDER.reduce(
(n, s) => n + state[s].filter(i => state[s+"Done"] && state[s+"Done"][i]).length, 0)
+ free.filter(f => f.done).length;
document.getElementById("bar").style.width = total ? (done/total*100) + "%" : "0%";
document.getElementById("label").textContent = done + " of " + total + " done";
document.getElementById("celebrate").classList.toggle("show", total > 0 && done === total);
}
const ROAD_KEY = "ba-roadmap";
let roadmap = JSON.parse(localStorage.getItem(ROAD_KEY) || "null");
function parseDate(s) {
s = String(s).trim();
if (!s) return null;
let m = s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})/);
if (m) return new Date(+m[1], +m[2]-1, +m[3]);
m = s.match(/^(\d{1,2})[\/\-.](\d{1,2})[\/\-.](\d{2,4})/);
if (m) {
let y = +m[3]; if (y < 100) y += 2000;
return new Date(y, +m[1]-1, +m[2]);
}
const d = new Date(s);
return isNaN(d) ? null : d;
}
function parseCsv(text) {
const lines = text.split(/\r?\n/).filter(l => l.trim());
if (!lines.length) return null;
function splitLine(line) {
const out = []; let cur = ""; let q = false;
for (let i = 0; i < line.length; i++) {
const c = line[i];
if (q) {
if (c === '"' && line[i+1] === '"') { cur += '"'; i++; }
else if (c === '"') q = false;
else cur += c;
} else if (c === '"') q = true;
else if (c === ',') { out.push(cur.trim()); cur = ""; }
else cur += c;
}
out.push(cur.trim());
return out;
}
let rows = lines.map(splitLine);
let header = rows[0].map(h => h.toLowerCase());
const hasHeader = header.some(h => /task|name|project|start|end|status/i.test(h));
let cols = { task: 0, start: 1, end: 2, status: 3, notes: 4 };
if (hasHeader) {
cols.task = header.findIndex(h => /task|name|project|item|feature/.test(h));
cols.start = header.findIndex(h => /start|begin|from/.test(h));
cols.end = header.findIndex(h => /end|finish|due|target/.test(h));
cols.status = header.findIndex(h => /status|state|phase/.test(h));
cols.notes = header.findIndex(h => /note|comment|desc|owner/.test(h));
rows = rows.slice(1);
}
const items = [];
for (const r of rows) {
const name = r[cols.task]; if (!name) continue;
const start = parseDate(r[cols.start] || r[1]);
const end = parseDate(r[cols.end] || r[2]);
if (!start) continue;
items.push({
name,
start,
end: end || start,
status: cols.status >= 0 && r[cols.status] ? r[cols.status].toLowerCase() : "planned",
notes: cols.notes >= 0 && r[cols.notes] ? r[cols.notes] : ""
});
}
return items.length ? items : null;
}
function statusClass(s) {
if (/done|complet|closed|shipped|live/.test(s)) return "done";
if (/in.?progress|active|wip|started/.test(s)) return "inprogress";
if (/block|at.?risk|delay|paused/.test(s)) return "blocked";
if (/plan|scheduled|upcoming|new|backlog/.test(s)) return "planned";
return "other";
}
function renderGantt() {
const body = document.getElementById("ganttBody");
const legend = document.getElementById("ganttLegend");
const src = document.getElementById("ganttSource");
if (!roadmap) {
body.classList.add("gantt-empty");
body.innerHTML = "No roadmap loaded yet.<br>Click <b>📁 Load / replace CSV</b> and pick a CSV file.";
legend.style.display = "none";
src.textContent = "";
return;
}
body.classList.remove("gantt-empty");
legend.style.display = "flex";
src.textContent = roadmap.source || "";
const today = new Date(); today.setHours(0,0,0,0);
let min = roadmap.items.reduce((m, i) => i.start < m ? i.start : m, roadmap.items[0].start);
let max = roadmap.items.reduce((m, i) => i.end > m ? i.end : m, roadmap.items[0].end);
const start = new Date(min); start.setDate(start.getDate() - ((start.getDay()+6)%7));
const end = new Date(max); end.setDate(end.getDate() + 7);
const days = [];
for (let d = new Date(start); d <= end; d.setDate(d.getDate()+1)) days.push(new Date(d));
const fmt = d => d.toLocaleDateString(undefined, { month: "short", day: "numeric" });
let html = "<table class='gantt'><colgroup><col style='width:220px'>" +
days.map(() => "<col>").join("") + "</colgroup><tr><th></th>";
for (const d of days) {
const wk = d.getDay() === 0 || d.getDay() === 6;
const isToday = d.getTime() === today.getTime();
html += "<th class='day" + (wk ? " weekend" : "") + (isToday ? " weekend-today" : "") + "'>" +
(d.getDate() % 7 === 1 || isToday ? d.getDate() : "") + "</th>";
}
html += "</tr>";
for (const item of roadmap.items) {
const a = Math.max(0, Math.min(days.length-1, Math.round((item.start - start)/86400000)));
const b = Math.max(0, Math.min(days.length-1, Math.round((item.end - start)/86400000)));
html += "<tr><td class='task-name' title='" + item.name + (item.notes ? " — " + item.notes : "") + "'>" +
item.name + "</td>";
for (let i = 0; i < days.length; i++) {
const wk = days[i].getDay() === 0 || days[i].getDay() === 6;
const isToday = days[i].getTime() === today.getTime();
if (i >= a && i <= b) {
html += "<td class='cell" + (isToday ? " today-col" : "") + "'><div class='bar " + statusClass(item.status) + "' title='" +
item.name + " — " + item.status + " (" + fmt(item.start) + " → " + fmt(item.end) + "')"></div></td>";
} else {
html += "<td class='cell" + (wk ? " weekend" : "") + (isToday ? " today-col" : "") + "'></td>";
}
}
html += "</tr>";
}
html += "</table>";
body.innerHTML = "<div class='gantt-wrap'>" + html + "</div>";
}
function loadCsvFile(input) {
const file = input.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = () => {
const items = parseCsv(reader.result);
if (!items) { alert("Couldn't parse that CSV. Expected columns: task, start, end (and optionally status, notes)."); return; }
roadmap = { items, source: file.name };
localStorage.setItem(ROAD_KEY, JSON.stringify(roadmap));
renderGantt();
};
reader.readAsText(file);
input.value = "";
}
function clearRoadmap() {
if (!confirm("Remove the roadmap from the checklist?")) return;
roadmap = null;
localStorage.removeItem(ROAD_KEY);
renderGantt();
}
if (roadmap) {
for (const i of roadmap.items) {
i.start = new Date(i.start); i.end = new Date(i.end);
}
}
renderGantt();
function addFree() {
const input = document.getElementById("freeInput");
const text = input.value.trim();
if (!text) return;
free.push({ text, done: false });
input.value = "";
save(); render();
input.focus();
}
function resetDay() {
if (!confirm("Uncheck all items for today?")) return;
for (const s of SECTIONS_IN_ORDER) state[s + "Done"] = {};
free.forEach(f => f.done = false);
save(); render();
}
document.getElementById("today").textContent =
new Date().toLocaleDateString(undefined, { weekday: "long", year: "numeric", month: "long", day: "numeric" });
// cleanup old days
for (const k of Object.keys(localStorage)) {
if (/^ba-(checklist|free)-v\d+-\d{4}-\d{2}-\d{2}$/.test(k) && !k.endsWith(todayKey)) {
localStorage.removeItem(k);
}
}
render();
</script>
</body>
</html>

2601
ServiceMeow-HQ.html Normal file

File diff suppressed because it is too large Load Diff

735
UAT-Outreach-Tracker.html Normal file
View File

@ -0,0 +1,735 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UAT Outreach Tracker</title>
<style>
:root {
--bg: #f6f7fb;
--card: #ffffff;
--accent: #4a6cf7;
--accent-soft: #e8edff;
--text: #1f2430;
--muted: #7a8195;
--border: #e3e6ef;
--st0: #9aa1b5; /* not reached out */
--st0bg: #eef0f6;
--st1: #4a6cf7; /* reached out */
--st1bg: #e8edff;
--st2: #d98b0b; /* waiting */
--st2bg: #fdf3df;
--st3: #22a45d; /* approved */
--st3bg: #e4f6ec;
--st4: #8a5cd6; /* on hold */
--st4bg: #f1eafc;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
background: var(--bg);
color: var(--text);
padding: 32px 16px 64px;
}
.container { max-width: 1120px; margin: 0 auto; }
header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; flex-wrap: wrap; }
h1 { font-size: 24px; font-weight: 700; }
.sub { color: var(--muted); font-size: 14px; margin-top: 4px; }
.toolbar { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
button, select, label.filebtn {
font: inherit; font-size: 13.5px;
border: 1px solid var(--border);
background: var(--card);
color: var(--text);
border-radius: 9px;
padding: 8px 12px;
cursor: pointer;
transition: background .15s, border-color .15s;
}
button:hover, select:hover { background: #f2f4fa; }
label.filebtn { display: inline-flex; align-items: center; }
label.filebtn input { display: none; }
.summary {
background: var(--card);
border: 1px solid var(--border);
border-radius: 14px;
padding: 16px 20px;
margin: 18px 0 20px;
box-shadow: 0 1px 3px rgba(20,30,60,.05);
}
.summary-grid { display: flex; gap: 10px; flex-wrap: wrap; }
.chip {
display: flex; flex-direction: column; gap: 2px;
border-radius: 10px; padding: 8px 14px; min-width: 118px;
}
.chip .n { font-size: 20px; font-weight: 700; }
.chip .l { font-size: 12px; }
.chip.s0 { background: var(--st0bg); } .chip.s0 .l { color: var(--st0); }
.chip.s1 { background: var(--st1bg); } .chip.s1 .l { color: var(--st1); }
.chip.s2 { background: var(--st2bg); } .chip.s2 .l { color: var(--st2); }
.chip.s3 { background: var(--st3bg); } .chip.s3 .l { color: var(--st3); }
.chip.s4 { background: var(--st4bg); } .chip.s4 .l { color: var(--st4); }
.progress-wrap { height: 8px; background: var(--border); border-radius: 999px; overflow: hidden; margin-top: 14px; }
.progress-bar { height: 100%; width: 0%; background: linear-gradient(90deg, var(--accent), #7c9bff); border-radius: 999px; transition: width .3s ease; }
.progress-label { font-size: 12.5px; color: var(--muted); margin-top: 6px; }
.filters { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-bottom: 14px; }
.filters .search { flex: 1; min-width: 200px; }
.filters input {
width: 100%; font: inherit; font-size: 13.5px;
border: 1px solid var(--border); border-radius: 9px;
padding: 8px 12px; background: var(--card);
}
.filters input:focus, select:focus { outline: 2px solid var(--accent-soft); border-color: var(--accent); }
.section {
background: var(--card);
border: 1px solid var(--border);
border-radius: 14px;
padding: 6px 10px;
margin-bottom: 16px;
box-shadow: 0 1px 3px rgba(20,30,60,.05);
}
.section h2 {
font-size: 12.5px; text-transform: uppercase; letter-spacing: .08em;
color: var(--muted); padding: 12px 10px 4px;
display: flex; justify-content: space-between; align-items: baseline;
}
.state-label {
font-size: 11.5px; font-weight: 700; text-transform: uppercase; letter-spacing: .06em;
color: var(--accent); padding: 10px 10px 2px;
}
.colhead {
display: grid;
grid-template-columns: 104px minmax(0,1fr) 150px 196px 136px 246px;
gap: 10px; align-items: center;
padding: 4px 10px 6px;
font-size: 10.5px; text-transform: uppercase; letter-spacing: .06em;
color: var(--muted);
border-bottom: 1px solid #eceef5;
}
.rowwrap { border-bottom: 1px solid #f0f2f8; display: grid; grid-template-columns: 30px 1fr; gap: 2px 6px; align-items: center; }
.rowwrap:last-child { border-bottom: none; }
.rowwrap .uat-line { grid-column: 2; }
.holdbtn {
width: 26px; height: 26px; border-radius: 50%; padding: 0;
border: 1.5px solid var(--border); background: #fff; color: var(--muted);
font-size: 11.5px; line-height: 1; cursor: pointer;
display: flex; align-items: center; justify-content: center;
transition: all .12s;
}
.holdbtn:hover { border-color: var(--st4); color: var(--st4); background: var(--st4bg); }
.holdbtn.on { background: var(--st4); border-color: var(--st4); color: #fff; box-shadow: 0 1px 4px rgba(138,92,214,.35); }
.row {
display: grid;
grid-template-columns: 104px minmax(0,1fr) 150px 196px 136px 246px;
gap: 10px; align-items: center;
padding: 8px 10px; border-radius: 9px;
border-left: 3px solid transparent;
}
.row.st-1 { border-left-color: var(--st1); background: linear-gradient(90deg, var(--st1bg), transparent 45%); }
.row.st-2 { border-left-color: var(--st2); background: linear-gradient(90deg, var(--st2bg), transparent 45%); }
.row.st-3 { border-left-color: var(--st3); background: linear-gradient(90deg, var(--st3bg), transparent 45%); }
.row.st-4 { border-left-color: var(--st4); background: linear-gradient(90deg, var(--st4bg), transparent 45%); }
.row:last-child { border-bottom: none; }
.row:hover { background: #f8f9fd; }
.row .ticket { font-weight: 600; font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--accent); }
.row .desc { font-size: 13.5px; line-height: 1.35; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.row .cell { font-size: 12.5px; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.row .cell.tester { white-space: normal; overflow: visible; }
.row .cell.tester .tag.tester { display: block; white-space: normal; line-height: 1.5; }
.tag {
font-size: 11.5px; padding: 3px 9px; border-radius: 999px;
background: var(--st0bg); color: var(--muted); white-space: nowrap;
}
.tag.epic { background: #f0f2f8; color: var(--muted); }
.tag.tester { background: var(--accent-soft); color: var(--accent); font-weight: 600; }
.status-btns { display: flex; gap: 3px; justify-content: flex-end; }
.sbtn {
font-size: 11.5px; font-weight: 600;
border: 1.5px solid transparent; border-radius: 8px;
padding: 5px 8px; cursor: pointer; white-space: nowrap;
background: transparent; color: var(--muted);
transition: all .12s;
}
.sbtn:hover { background: #eef0f6; }
.sbtn[data-s="0"].on { background: var(--st0bg); border-color: var(--st0); color: var(--st0); }
.sbtn[data-s="1"].on { background: var(--st1); border-color: var(--st1); color: #fff; }
.sbtn[data-s="2"].on { background: var(--st2); border-color: var(--st2); color: #fff; }
.sbtn[data-s="3"].on { background: var(--st3); border-color: var(--st3); color: #fff; }
.sbtn[data-s="4"].on { background: var(--st4); border-color: var(--st4); color: #fff; }
.clearbtn {
font-size: 12px; line-height: 1;
border: none; border-radius: 8px;
padding: 5px 7px; cursor: pointer;
background: transparent; color: #b6bccd;
transition: all .12s;
}
.clearbtn:hover { background: #fdecec; color: #d64545; }
.empty { text-align: center; color: var(--muted); padding: 40px 0; font-size: 14.5px; }
@media (max-width: 960px) {
.colhead { display: none; }
.row { grid-template-columns: 96px minmax(0,1fr) auto; }
.row .cell { display: none; }
}
.drop-hint {
border: 2px dashed var(--border); border-radius: 14px;
padding: 28px; text-align: center; color: var(--muted); font-size: 14px; margin-bottom: 16px;
}
.drop-hint.active { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); }
footer { margin-top: 28px; font-size: 12px; color: var(--muted); text-align: center; }
.editable { cursor: text; border-radius: 6px; transition: background .12s, outline-color .12s; outline: 1px dashed transparent; outline-offset: -1px; }
.editable:hover { background: #eef1fb; outline-color: #b9c4e8; }
.inline-edit { width: 100%; font: inherit; font-size: 12.5px; border: 1.5px solid var(--accent); border-radius: 6px; padding: 4px 6px; background: #fff; color: var(--text); }
.inline-edit:focus { outline: none; }
.uat-line { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; padding: 2px 10px 9px; }
.mini { font-size: 12px; font-weight: 600; padding: 4px 10px; border: 1px solid var(--border); border-radius: 8px; background: #fff; color: var(--text); cursor: pointer; transition: all .12s; }
.mini:hover { background: #f2f4fa; }
.mini.wip:hover { background: var(--st2bg); border-color: var(--st2); color: var(--st2); }
.notetext { font-size: 12.5px; color: var(--muted); font-style: italic; flex: 1 1 220px; min-width: 200px; line-height: 1.4; }
.note-edit { flex: 1 1 240px; min-width: 220px; font: inherit; font-size: 12.5px; border: 1.5px solid var(--accent); border-radius: 8px; padding: 6px 8px; background: #fff; color: var(--text); }
</style>
</head>
<body>
<div class="container">
<header>
<div>
<h1>UAT Outreach Tracker</h1>
<div class="sub" id="loadLabel">Stories to reach out about for UAT testing</div>
</div>
<div class="toolbar">
<select id="statusFilter">
<option value="">All statuses</option>
<option value="0">☐ Not reached out</option>
<option value="1">📤 Reached out</option>
<option value="2">⏳ Waiting on response</option>
<option value="3">✅ Approved</option>
<option value="4">⏸ On hold</option>
</select>
<select id="stateFilter">
<option value="">All ticket states</option>
</select>
<button id="showDoneToggle" title="Show or hide approved tickets">Hide approved</button>
<button id="hiddenToggle" title="Show tickets hidden because they're Approved / Awaiting Deployment / Complete / Cancelled">Show hidden</button>
<button id="resetAll" title="Clear every outreach status">Reset all</button>
<button id="backup" title="Download your statuses as a JSON file">Backup</button>
<label class="filebtn" title="Restore statuses from a backup JSON">Restore
<input type="file" id="restoreInput" accept=".json,application/json">
</label>
<label class="filebtn">📂 Load weekly CSV
<input type="file" id="csvInput" accept=".csv,text/csv">
</label>
</div>
</header>
<div id="dropHint" class="drop-hint active">📂 Drag &amp; drop your weekly export CSV here, or use the <b>"📂 Load weekly CSV"</b> button above.</div>
<div class="summary">
<div class="summary-grid">
<div class="chip s0"><span class="n" id="cnt0">0</span><span class="l">Not reached out</span></div>
<div class="chip s1"><span class="n" id="cnt1">0</span><span class="l">Reached out</span></div>
<div class="chip s2"><span class="n" id="cnt2">0</span><span class="l">Waiting on response</span></div>
<div class="chip s3"><span class="n" id="cnt3">0</span><span class="l">Approved</span></div>
<div class="chip s4"><span class="n" id="cnt4">0</span><span class="l">On hold</span></div>
</div>
<div class="progress-wrap"><div class="progress-bar" id="prog"></div></div>
<div class="progress-label" id="progLabel"></div>
</div>
<div class="filters">
<div class="search"><input type="text" id="search" placeholder="Search ticket #, description, person…"></div>
<select id="epicFilter">
<option value="">All epics</option>
</select>
</div>
<div id="list"></div>
<footer>Statuses and field edits are saved in this browser per ticket ID — they carry over when you load next week's export. Click a State / Tester / Dev field to edit it in place (Enter saves, Esc cancels). Use Backup/Restore to move or safeguard your data.</footer>
</div>
<script>
const STATUS_LABELS = ["Not reached out", "Reached out", "Waiting on response", "Approved", "On hold"];
const IGNORED_STATES = new Set(["Approved", "Awaiting Deployment", "Complete", "Cancelled"]);
// these are removed entirely — not even shown via "Show hidden"
const HARD_EXCLUDED = new Set(["Complete", "Cancelled"]);
const STORAGE_KEY = "uat-outreach-statuses-v1";
const OVERRIDE_KEY = "uat-outreach-overrides-v1";
// No data is built in — load the weekly ServiceNow export CSV to populate the tracker.
const INITIAL_TICKETS = [];
let INITIAL_SOURCE = "No CSV loaded yet — upload the weekly export";
let tickets = [];
function loadStatuses() {
try { return JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}"); }
catch { return {}; }
}
let statuses = loadStatuses();
function loadOverrides() {
try { return JSON.parse(localStorage.getItem(OVERRIDE_KEY) || "{}"); }
catch { return {}; }
}
let overrides = loadOverrides();
function saveOverrides() {
localStorage.setItem(OVERRIDE_KEY, JSON.stringify(overrides));
}
function saveStatuses() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(statuses));
}
function statusOf(t) {
const id = typeof t === "string" ? t : t.ticket;
return statuses[id] ? statuses[id].status : 0;
}
function setStatus(ticketId, s) {
statuses[ticketId] = { status: s, updatedAt: new Date().toISOString() };
saveStatuses();
render();
}
// ---------- CSV parsing ----------
function parseCSV(s) {
const rows = []; let row = [], cur = "", inQ = false;
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (inQ) {
if (c === '"') { if (s[i+1] === '"') { cur += '"'; i++; } else inQ = false; }
else cur += c;
} else {
if (c === '"') inQ = true;
else if (c === ",") { row.push(cur); cur = ""; }
else if (c === "\n") { row.push(cur); rows.push(row); row = []; cur = ""; }
else if (c === "\r") {}
else cur += c;
}
}
if (cur.length || row.length) { row.push(cur); rows.push(row); }
return rows;
}
function csvToTickets(text) {
const rows = parseCSV(text);
if (rows.length < 2) throw new Error("CSV appears to be empty");
const hdr = rows[0];
const idx = name => hdr.indexOf(name);
const iT = idx("original_task"), iD = idx("original_task.short_description"),
iS = idx("state"), iE = idx("epic"), iA = idx("assigned_to"),
iO = idx("opened_by");
if (iT === -1) throw new Error("Couldn't find the 'original_task' column — is this a ServiceNow story export?");
const out = [];
for (const r of rows.slice(1)) {
const ticket = (r[iT] || "").trim();
if (!ticket) continue;
out.push({
ticket,
desc: iD !== -1 ? (r[iD] || "").replace(/\s+/g, " ").trim() : "",
state: iS !== -1 ? (r[iS] || "").trim() : "",
epic: iE !== -1 ? (r[iE] || "").trim() : "",
assigned_to: iA !== -1 ? (r[iA] || "").trim() : "",
opened_by: iO !== -1 ? (r[iO] || "").trim() : ""
});
}
return out;
}
// ---------- Grouping ----------
// group by site (first token of the description)
function siteOf(t) {
const first = ((t.desc || "").split("|")[0] || "").trim().toLowerCase();
if (/^rnd|^r&d/.test(first)) return "RNDSystems";
if (/^bt\b|^bio/.test(first)) return "BT";
if (/^wms/.test(first)) return "WMS";
if (/^sbd|^spd|^spatial/.test(first)) return "SBD";
return "Other";
}
const SITE_ORDER = { "RNDSystems": 10, "BT": 11, "WMS": 12, "SBD": 13 };
const STATE_OPTIONS = ["Draft", "Ready", "Work in Progress", "Peer Review", "QA Testing", "UAT Testing", "Approved", "Awaiting Deployment", "Complete", "Cancelled"];
// sort order within each section: UAT first (most urgent to have contacted testers),
// then the states about to move into UAT, then Draft/Ready, everything else last
const STATE_ORDER = { "UAT Testing": 0, "Work in Progress": 1, "Peer Review": 2, "QA Testing": 3, "Draft": 4, "Ready": 5 };
// ---------- Filters ----------
const els = {
statusFilter: document.getElementById("statusFilter"),
stateFilter: document.getElementById("stateFilter"),
epicFilter: document.getElementById("epicFilter"),
search: document.getElementById("search"),
showDone: document.getElementById("showDoneToggle"),
list: document.getElementById("list"),
};
let hideApproved = false;
let showHidden = false;
const isVisibleState = t => !HARD_EXCLUDED.has(t.state) && (showHidden || !IGNORED_STATES.has(t.state));
function populateFilters() {
const states = [...new Set(tickets.map(t => t.state).filter(s => s && !HARD_EXCLUDED.has(s) && (showHidden || !IGNORED_STATES.has(s))))].sort();
const epics = [...new Set(tickets.map(t => t.epic).filter(Boolean))].sort();
// preserve the current selections when rebuilding the option lists
const prevState = els.stateFilter.value;
const prevEpic = els.epicFilter.value;
els.stateFilter.innerHTML = '<option value="">All ticket states</option>' +
states.map(s => `<option>${s}</option>`).join("");
els.epicFilter.innerHTML = '<option value="">All epics</option>' +
epics.map(s => `<option>${s}</option>`).join("");
if (states.includes(prevState)) els.stateFilter.value = prevState;
if (epics.includes(prevEpic)) els.epicFilter.value = prevEpic;
}
function visibleTickets() {
const sf = els.statusFilter.value;
const ts = els.stateFilter.value;
const ep = els.epicFilter.value;
const q = els.search.value.trim().toLowerCase();
return tickets.filter(t => {
if (!isVisibleState(t)) return false;
if (hideApproved && statusOf(t) === 3 && sf === "") return false;
if (sf !== "" && statusOf(t) !== Number(sf)) return false;
if (ts && t.state !== ts) return false;
if (ep && t.epic !== ep) return false;
if (q && !(t.ticket + " " + t.desc + " " + t.assigned_to + " " + t.opened_by + " " + t.epic + " " + (t.watch_list || "")).toLowerCase().includes(q)) return false;
return true;
});
}
// ---------- Render ----------
function esc(s) {
return (s || "").replace(/[&<>"']/g, c =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
}
function render() {
// summary (counts over all tickets)
const counts = [0, 0, 0, 0, 0];
const active = tickets.filter(t => isVisibleState(t));
active.forEach(t => counts[statusOf(t)]++);
for (let i = 0; i < 5; i++) document.getElementById("cnt" + i).textContent = counts[i];
const done = counts[3], total = active.length;
const pct = total ? Math.round((done / total) * 100) : 0;
document.getElementById("prog").style.width = pct + "%";
document.getElementById("progLabel").textContent =
total ? `${done} of ${total} approved (${pct}%) · ${counts[2]} waiting on a response` : "";
// group by site; within each site, sub-group by state (priority order)
const vis = visibleTickets();
if (!vis.length) {
if (!tickets.length) {
els.list.innerHTML = '<div class="empty">📂 No data loaded yet.<br>Click <b>"📂 Load weekly CSV"</b> in the toolbar (or drag &amp; drop your weekly ServiceNow export anywhere on this page) to get started.</div>';
} else {
els.list.innerHTML = '<div class="empty">No tickets match the current filters.</div>';
}
return;
}
const groups = new Map();
vis.forEach(t => {
const key = siteOf(t);
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(t);
});
// keep a stable order (ticket #) so items don't jump when you change a status
for (const arr of groups.values()) {
arr.sort((a, b) => a.ticket.localeCompare(b.ticket));
}
const keys = [...groups.keys()].sort((a, b) => (SITE_ORDER[a] ?? 98) - (SITE_ORDER[b] ?? 98) || a.localeCompare(b));
const colhead = `<div class="colhead"><span>Ticket</span><span>Description</span><span>State</span><span>Tester (watch list)</span><span>Dev</span><span style="text-align:right">Outreach status</span></div>`;
const row = t => {
const s = statusOf(t);
const btnLabels = ["Reached out", "Waiting", "Approved"];
const isUAT = /^UAT/i.test(t.state || "");
return `<div class="rowwrap">
<button class="holdbtn${s === 4 ? " on" : ""}" data-hold="${esc(t.ticket)}" title="On hold — not ready for UAT yet (waiting on something). Click again to clear.">⏸</button>
<div class="row st-${s}" data-ticket="${esc(t.ticket)}">
<span class="ticket" title="${esc(t.ticket)}">${esc(t.ticket)}</span>
<span class="desc" title="${esc(t.desc)}">${esc(t.desc) || "—"}</span>
<span class="cell editable" data-field="state" title="Click to edit"><span class="tag">${esc(t.state) || "—"}</span></span>
<span class="cell tester editable" data-field="watch_list" title="${esc(t.watch_list)} — click to edit">${t.watch_list ? `<span class="tag tester">${esc(t.watch_list)}</span>` : "—"}</span>
<span class="cell editable" data-field="assigned_to" title="${esc(t.assigned_to)} — click to edit">${t.assigned_to ? `→ ${esc(t.assigned_to)}` : "—"}</span>
<span class="status-btns">
${[1, 2, 3].map(i =>
`<button class="sbtn${i === s ? " on" : ""}" data-s="${i}" data-ticket="${esc(t.ticket)}">${btnLabels[i - 1]}</button>`
).join("")}
</span>
</div>
${(isUAT || t.note) ? `
<div class="uat-line">
<button class="mini" data-note="${esc(t.ticket)}">📝 ${t.note ? "Edit feedback note" : "Add feedback note"}</button>
${isUAT ? `<button class="mini wip" data-wip="${esc(t.ticket)}" title="Sets the state to Work in Progress">↩ Send back to Work in Progress</button>` : ""}
${t.note ? `<span class="notetext" title="${esc(t.note)}">“${esc(t.note)}”</span>` : ""}
</div>` : ""}
</div>`;
};
els.list.innerHTML = keys.map(site => {
const list = groups.get(site);
const byState = new Map();
list.forEach(t => {
const sk = t.state || "No state";
if (!byState.has(sk)) byState.set(sk, []);
byState.get(sk).push(t);
});
const skeys = [...byState.keys()].sort((a, b) => (STATE_ORDER[a] ?? 99) - (STATE_ORDER[b] ?? 99) || a.localeCompare(b));
const body = skeys.map(sk => `
<div class="state-label">${esc(sk)} · ${byState.get(sk).length}</div>
${colhead}
${byState.get(sk).map(row).join("")}
`).join("");
return `<div class="section">
<h2><span>${esc(site)}</span><span>${list.length} tickets</span></h2>
${body}
</div>`;
}).join("");
}
// ---------- Events ----------
els.list.addEventListener("click", e => {
if (e.target.closest(".inline-edit") || e.target.closest(".note-edit")) return;
const editable = e.target.closest(".editable");
if (editable) { startEdit(editable); return; }
const noteBtn = e.target.closest("[data-note]");
if (noteBtn) { startNoteEdit(noteBtn); return; }
const holdBtn = e.target.closest("[data-hold]");
if (holdBtn) {
const id = holdBtn.dataset.hold;
setStatus(id, statusOf(id) === 4 ? 0 : 4);
return;
}
const wipBtn = e.target.closest("[data-wip]");
if (wipBtn) {
const id = wipBtn.dataset.wip;
if (confirm(`Move ${id} back to "Work in Progress"?`)) setField(id, "state", "Work in Progress");
return;
}
const btn = e.target.closest(".sbtn");
if (!btn) return;
const s = Number(btn.dataset.s);
// clicking the already-selected button unchecks it
setStatus(btn.dataset.ticket, s === statusOf(btn.dataset.ticket) ? 0 : s);
});
// ---------- Inline field editing ----------
function setField(id, field, value) {
const base = rawByTicket[id] || {};
let diff = { ...(overrides[id] || {}) };
if (value === (base[field] ?? "")) delete diff[field];
else diff[field] = value;
if (Object.keys(diff).length) overrides[id] = diff;
else delete overrides[id];
saveOverrides();
const idx = tickets.findIndex(x => x.ticket === id);
if (idx !== -1) tickets[idx] = { ...base, ...(overrides[id] || {}) };
populateFilters();
render();
}
function startEdit(cell) {
if (cell.querySelector("input, select")) return;
const row = cell.closest(".row");
const id = row.dataset.ticket;
const field = cell.dataset.field;
const t = tickets.find(x => x.ticket === id);
if (!t) return;
const finishWith = (get) => {
let done = false;
const finish = save => {
if (done) return;
done = true;
if (save) setField(id, field, get());
else render();
};
return finish;
};
if (field === "state") {
const sel = document.createElement("select");
sel.className = "inline-edit";
STATE_OPTIONS.forEach(v => {
const o = document.createElement("option");
o.value = v;
o.textContent = v;
sel.appendChild(o);
});
if (STATE_OPTIONS.includes(t.state)) sel.value = t.state;
cell.textContent = "";
cell.appendChild(sel);
sel.focus();
const finish = finishWith(() => sel.value);
sel.addEventListener("change", () => finish(true));
sel.addEventListener("blur", () => finish(true));
return;
}
const input = document.createElement("input");
input.className = "inline-edit";
input.value = t[field] || "";
cell.textContent = "";
cell.appendChild(input);
input.focus();
input.select();
let done = false;
const finish = save => {
if (done) return;
done = true;
if (save) setField(id, field, input.value.trim());
else render();
};
input.addEventListener("keydown", e => {
if (e.key === "Enter") finish(true);
else if (e.key === "Escape") finish(false);
});
input.addEventListener("blur", () => finish(true));
}
function startNoteEdit(btn) {
const line = btn.closest(".uat-line");
if (line.querySelector("textarea")) return;
const id = btn.dataset.note;
const t = tickets.find(x => x.ticket === id);
if (!t) return;
line.innerHTML = "";
const ta = document.createElement("textarea");
ta.className = "note-edit";
ta.rows = 2;
ta.placeholder = "Feedback to work back into the ticket…";
ta.value = t.note || "";
const save = document.createElement("button");
save.className = "mini";
save.textContent = "Save note";
const cancel = document.createElement("button");
cancel.className = "mini";
cancel.textContent = "Cancel";
line.append(ta, save, cancel);
ta.focus();
let done = false;
const finish = saveIt => {
if (done) return;
done = true;
if (saveIt) setField(id, "note", ta.value.trim());
else render();
};
save.addEventListener("click", () => finish(true));
cancel.addEventListener("click", () => finish(false));
ta.addEventListener("keydown", e => {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); finish(true); }
else if (e.key === "Escape") finish(false);
});
}
["statusFilter", "stateFilter", "epicFilter"].forEach(id =>
els[id === "statusFilter" ? "statusFilter" : id].addEventListener("change", render));
els.search.addEventListener("input", render);
els.showDone.addEventListener("click", () => {
hideApproved = !hideApproved;
els.showDone.textContent = hideApproved ? "Hide approved" : "Show approved";
render();
});
document.getElementById("hiddenToggle").addEventListener("click", e => {
showHidden = !showHidden;
const n = tickets.filter(t => !HARD_EXCLUDED.has(t.state) && IGNORED_STATES.has(t.state)).length;
e.target.textContent = showHidden ? `Hiding ${n} approved/awaiting` : `Show ${n} hidden`;
populateFilters();
render();
});
document.getElementById("resetAll").addEventListener("click", () => {
if (!confirm("Clear the outreach status on ALL tickets? This can't be undone.")) return;
statuses = {};
saveStatuses();
render();
});
// ---------- Backup / restore ----------
document.getElementById("backup").addEventListener("click", () => {
const blob = new Blob([JSON.stringify({ exported: new Date().toISOString(), statuses, overrides }, null, 2)], { type: "application/json" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = "uat-outreach-statuses-" + new Date().toISOString().slice(0, 10) + ".json";
a.click();
URL.revokeObjectURL(a.href);
});
document.getElementById("restoreInput").addEventListener("change", e => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = () => {
try {
const obj = JSON.parse(reader.result);
if (typeof obj !== "object" || obj === null) throw new Error("unrecognized format");
const st = obj.statuses ? obj.statuses : {};
const ov = obj.overrides ? obj.overrides : {};
const n = Object.keys(st).length;
if (!confirm(`Restore ${n} saved statuses (${Object.keys(ov).length} card edits)? This replaces your current selections.`)) return;
statuses = st;
overrides = ov;
saveStatuses();
saveOverrides();
// re-apply card edits to the current list
tickets.forEach((t, i) => { const raw = rawByTicket[t.ticket]; if (raw) tickets[i] = { ...raw, ...(overrides[t.ticket] || {}) }; });
render();
} catch (err) {
alert("Could not restore: " + err.message);
}
};
reader.readAsText(file);
e.target.value = "";
});
function loadTickets(list, sourceLabel) {
// apply any local edits (tester/desc/state/dev changes) on top of the CSV data
rawByTicket = {};
tickets = list.map(t => {
// trim stray whitespace (e.g. "Quoting ") so filters and matching work
const clean = { ...t };
for (const k in clean) if (typeof clean[k] === "string") clean[k] = clean[k].trim();
rawByTicket[clean.ticket] = clean;
return { ...clean, ...(overrides[clean.ticket] || {}) };
});
const active = tickets.filter(t => isVisibleState(t)).length;
document.getElementById("loadLabel").textContent =
`${active} tickets to track (${list.length - active} not shown) · ${sourceLabel}`;
const dh = document.getElementById("dropHint");
if (dh) { dh.style.display = "none"; dh.classList.remove("active"); }
populateFilters();
render();
}
let rawByTicket = {};
document.getElementById("csvInput").addEventListener("change", e => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = () => {
try {
loadTickets(csvToTickets(reader.result), file.name);
} catch (err) {
alert("Could not load that CSV: " + err.message);
}
};
reader.readAsText(file);
e.target.value = "";
});
// drag & drop
const dropHint = document.getElementById("dropHint");
["dragenter", "dragover"].forEach(ev => document.addEventListener(ev, e => {
e.preventDefault(); dropHint.classList.add("active"); dropHint.style.display="block";
}));
["dragleave", "drop"].forEach(ev => document.addEventListener(ev, e => {
e.preventDefault(); dropHint.classList.remove("active"); dropHint.style.display="none";
}));
document.addEventListener("drop", e => {
const file = e.dataTransfer.files && e.dataTransfer.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = () => {
try { loadTickets(csvToTickets(reader.result), file.name); }
catch (err) { alert("Could not load that CSV: " + err.message); }
};
reader.readAsText(file);
});
// init
loadTickets(INITIAL_TICKETS, INITIAL_SOURCE);
</script>
</body>
</html>

File diff suppressed because it is too large Load Diff

225
build_hub.mjs Normal file
View File

@ -0,0 +1,225 @@
import fs from "fs";
const BASE = "/Users/paige.petrone/messingaround";
const rm = fs.readFileSync(`${BASE}/Web Team ServiceMeow - Roadmap.html`, "utf8");
const ut = fs.readFileSync(`${BASE}/UAT-Outreach-Tracker.html`, "utf8");
const newMid = fs.readFileSync(`${BASE}/uat_new_section.js`, "utf8");
const extract = html => {
const style = html.match(/<style>([\s\S]*?)<\/style>/)[1];
const body = html.match(/<body>([\s\S]*?)<script>/)[1];
const script = html.match(/<script>([\s\S]*?)<\/script>/g).pop().replace(/<\/?script>/g, "");
return { style, body, script };
};
const R = extract(rm), U = extract(ut);
// ---- UAT CSS tweaks ----
let cs = U.style
.replace(" padding: 32px 16px 64px;\n", "")
.replace("h1 { font-size: 24px; font-weight: 700; }", "#tab-uat h1 { font-size: 22px; font-weight: 700; }")
.replace("header { display: flex;", "#tab-uat header { display: flex;")
.replace("button, select, label.filebtn {", "#tab-uat button, #tab-uat select, #tab-uat label.filebtn {")
.replace("button:hover, select:hover {", "#tab-uat button:hover, #tab-uat select:hover {")
.replace(".chip {", ".uchip {").replace(".chip .n", ".uchip .n").replace(".chip .l", ".uchip .l");
for (let i = 0; i < 5; i++) cs = cs.split(`.chip.s${i}`).join(`.uchip.s${i}`);
cs = cs.replace(".empty { text-align: center;", ".uempty { text-align: center;");
cs = cs.replace(
".rowwrap { border-bottom: 1px solid #f0f2f8; display: grid; grid-template-columns: 30px 1fr; gap: 2px 6px; align-items: center; }",
".rowwrap { border-bottom: 1px solid #f0f2f8; display: grid; grid-template-columns: 30px 30px 1fr; gap: 2px 6px; align-items: center; }");
cs = cs.replace(".rowwrap .uat-line { grid-column: 2; }", ".rowwrap .uat-line { grid-column: 3; }");
cs += `
/* launch-aware additions */
.uat-banner { display:flex; align-items:center; gap:10px; flex-wrap:wrap; background:#fff8ef; border:1px solid #f3c18f; color:#7a4d12; border-radius:12px; padding:12px 16px; margin:14px 0; font-size:14px; font-weight:600; }
.uat-banner .b-sub { font-weight:400; font-size:12.5px; color:#a06a20; }
.launch-cards { display:flex; gap:12px; flex-wrap:wrap; margin-bottom:16px; }
.lcard { background:var(--card); border:1px solid var(--border); border-radius:14px; padding:12px 16px; min-width:230px; flex:1; box-shadow:0 1px 3px rgba(20,30,60,.05); }
.lcard h3 { font-size:13.5px; margin-bottom:2px; }
.lcard .rule { font-size:11.5px; color:var(--muted); margin-bottom:8px; }
.lcard .lnext { font-size:14.5px; font-weight:700; }
.lcard .lnext .fz { color:#b0721f; }
.lcard .lcount { margin-top:6px; font-size:12px; color:var(--muted); }
.lcard .lcount b { color:var(--text); }
.lcard .lmore { margin-top:4px; font-size:11.5px; color:var(--muted); }
.lcard.hot { border-color:#f3c18f; background:linear-gradient(180deg,#fffaf2,#fff); }
.bottombtn { width:26px; height:26px; border-radius:50%; padding:0; border:1.5px solid var(--border); background:#fff; color:var(--muted); font-size:11px; line-height:1; cursor:pointer; display:flex; align-items:center; justify-content:center; transition:all .12s; }
.bottombtn:hover { border-color:var(--accent); color:var(--accent); background:var(--accent-soft); }
.bottombtn.on { background:#4a5266; border-color:#4a5266; color:#fff; }
.bsec { display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
.bsec .blaunch { font-size:13.5px; font-weight:700; color:var(--text); }
.bsec .bfreeze { font-size:12.5px; font-weight:600; color:#b0721f; background:#fff3e0; border-radius:999px; padding:3px 10px; }
.bsec .bdays { font-size:11.5px; font-weight:700; border-radius:999px; padding:3px 10px; }
.bdays.urgent { background:#fdecea; color:#c0392b; }
.bdays.soon { background:#fff3e0; color:#b0721f; }
.bdays.later { background:#eef1f8; color:#5a6478; }
.bsec .bsub { font-size:11.5px; color:var(--muted); }
.bsec .count { margin-left:auto; font-weight:500; color:var(--muted); font-size:11px; }
.bottom-zone { margin-top:8px; border-top:1.5px dashed #e3e6ef; padding-top:2px; }
.bottom-zone .bz-label { font-size:10.5px; text-transform:uppercase; letter-spacing:.07em; color:var(--muted); padding:8px 10px 0; }
.secbody .row.dimmed { opacity:.82; }
/* nearest-launch section = most prominent */
.section.next { border:1.5px solid #f3c18f; background:linear-gradient(180deg,#fffaf2 0%,#fff 55%); box-shadow:0 2px 12px rgba(180,110,20,.14); }
.bnext { font-size:10.5px; font-weight:800; letter-spacing:.06em; color:#b0721f; background:#fff3e0; border:1px solid #f3c18f; border-radius:999px; padding:3px 10px; }
`;
// ---- UAT HTML tweaks ----
let ub = U.body
.replace(/class="chip s(\d)"/g, 'class="uchip s$1"')
.replace(/class="empty"/g, 'class="uempty"')
.replace(
"Statuses and field edits are saved in this browser per ticket ID",
"Use ⬇ to send a story to the bottom of its launch section (⬆ brings it back). Statuses and field edits are saved in this browser per ticket ID");
ub = ub.replace('<div class="summary">',
'<div class="uat-banner" id="uatBanner" style="display:none"></div>\n <div class="launch-cards" id="launchCards"></div>\n\n <div class="summary">');
// ---- UAT JS renames (avoid collisions with roadmap globals) ----
let us = U.script
.replace(/(?<![\w$])esc\(/g, "escUat(")
.replace(/(?<![\w$])setStatus\b/g, "setUatStatus")
.replace(/(?<![\w$])statusOf\b/g, "uatStatusOf")
.replace(/(?<![\w$])render\b/g, "uatRender");
us = us.replace('["dragenter", "dragover"].forEach(ev => document.addEventListener(ev, e => {',
'const uatPane = document.getElementById("tab-uat");\n["dragenter", "dragover"].forEach(ev => uatPane.addEventListener(ev, e => {');
us = us.replace('document.addEventListener("drop", e => {', 'uatPane.addEventListener("drop", e => {');
// wire up the send-to-bottom / restore button
us = us.replace(' const holdBtn = e.target.closest("[data-hold]");',
' const botBtn = e.target.closest("[data-bottom]");\n if (botBtn) { moveBottom(botBtn.dataset.bottom); return; }\n const holdBtn = e.target.closest("[data-hold]");');
// ---- replace Grouping..Events region with the launch-cycle implementation ----
const start = us.indexOf("// ---------- Grouping ----------");
const end = us.indexOf("// ---------- Events ----------");
if (start === -1 || end === -1) throw new Error("UAT script regions not found");
us = us.slice(0, start) + newMid + "\n" + us.slice(end);
const defs = (us.match(/function escUat\(/g) || []).length;
if (defs !== 1) throw new Error("escUat defined " + defs + " times");
// sanity: no leftover un-renamed globals that collide with the roadmap script
for (const bad of ["function esc(", "function setStatus(", "function statusOf(", "function render("]) {
if (us.includes(bad)) throw new Error("leftover collision: " + bad);
}
// ---- tab bar ----
const tabCss = `
/* ---------- hub tabs ---------- */
.hubbar { max-width: 1760px; margin: 0 auto; padding: 18px 20px 0; display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }
.hubbar .hub-title { font-size: 19px; font-weight: 800; letter-spacing: .01em; }
.hubbar .hub-date { color: var(--muted); font-size: 13px; }
.tabbar { display: flex; gap: 8px; margin: 14px 0 0; }
.tabbtn { display: inline-flex; align-items: center; gap: 8px; font: inherit; font-size: 14.5px; font-weight: 700;
border: 1.5px solid var(--border); background: #fff; color: #4a5266; border-radius: 11px; padding: 10px 20px; cursor: pointer; transition: all .12s; }
.tabbtn:hover { border-color: var(--accent); color: var(--accent); }
.tabbtn.active { background: var(--accent); border-color: var(--accent); color: #fff; box-shadow: 0 2px 8px rgba(74,108,247,.3); }
.tabbtn .tbadge { font-size: 11px; font-weight: 800; background: #fdecea; color: #c0392b; border-radius: 999px; padding: 2px 8px; }
.tabbtn.active .tbadge { background: rgba(255,255,255,.28); color: #fff; }
.tabpane { display: none; }
.tabpane.active { display: block; }
#tab-uat .container { max-width: 1280px; padding: 4px 0 48px; }
#tab-uat .section-head { padding: 14px 12px 6px; }
/* Web Alignment tab */
.wa-wrap { max-width: 860px; margin: 0 auto; }
.wa-when { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; background: var(--accent-soft); border: 1px solid var(--border); border-radius: 12px; padding: 12px 16px; margin: 4px 0 14px; font-size: 14px; }
.wa-when .wa-sub { color: var(--muted); font-size: 12.5px; }
.wa-when.today { background: #fff8ef; border-color: #f3c18f; font-weight: 600; }
.wa-added { margin-left: auto; font-size: 11px; color: var(--muted); white-space: nowrap; }
/* WA sub-items */
.wa-subs { margin: 1px 0 6px 36px; }
.wa-subrow { font-size: 13px !important; padding: 4px 6px !important; background: #fbfcff; }
.wa-subrow input { width: 15px !important; height: 15px !important; min-width: 15px !important; }
.wa-subcnt { font-size: 10.5px; font-weight: 700; color: #5a6478; background: #eef1f8; border-radius: 999px; padding: 1px 7px; white-space: nowrap; }
.wa-addsub { font-size: 11px; font-weight: 600; border: 1px dashed #c4c9d9; background: #fff; color: var(--muted); border-radius: 7px; padding: 2px 9px; cursor: pointer; white-space: nowrap; font-family: inherit; }
.wa-addsub:hover { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); }
.wa-subadd { margin: 2px 0 4px; }
.wa-subadd input { width: 100%; padding: 6px 10px; border: 1.5px solid var(--accent); border-radius: 8px; font: inherit; font-size: 13px; }
`;
const tabHtml = `
<div class="hubbar">
<div class="hub-title">🐱 ServiceMeow HQ</div>
<div class="hub-date" id="hubDate"></div>
<div class="tabbar">
<button class="tabbtn" id="tabbtn-roadmap" onclick="switchTab('roadmap')">📋 Roadmap &amp; Daily</button>
<button class="tabbtn" id="tabbtn-uat" onclick="switchTab('uat')">🧪 UAT Launches <span class="tbadge" id="uatBadge">🚀</span></button>
<button class="tabbtn" id="tabbtn-wa" onclick="switchTab('wa')">🤝 Web Alignment <span class="tbadge" id="waBadge">—</span></button>
</div>
</div>
`;
const tabJs = `
/* ================= HUB TABS ================= */
const HUB_TABS = ["roadmap", "uat", "wa"];
function switchTab(name) {
HUB_TABS.forEach(t => {
const pane = document.getElementById("tab-" + t), btn = document.getElementById("tabbtn-" + t);
if (pane) pane.classList.toggle("active", t === name);
if (btn) btn.classList.toggle("active", t === name);
});
localStorage.setItem("sm-hub-tab", name);
if (name === "roadmap" && window.refreshAll) refreshAll();
if (name === "uat" && window.uatRender) uatRender();
if (name === "wa" && window.renderWa) renderWa();
}
document.getElementById("hubDate").textContent =
new Date().toLocaleDateString(undefined, { weekday: "long", year: "numeric", month: "long", day: "numeric" });
switchTab(localStorage.getItem("sm-hub-tab") || "roadmap");
`;
const waHtml = `
<div id="tab-wa" class="tabpane">
<div class="page">
<div class="wa-wrap">
<div class="card">
<div class="card-head">
<div>
<h2>🤝 Web Alignment Team — bring up at Monday's sync</h2>
<div class="hint">Mondays 9:00 AM MT · check an item off once it's been raised — it moves to Covered until you clear it</div>
</div>
<button class="mini-btn" onclick="waClearCovered()" title="Remove all covered items">Clear covered</button>
</div>
<div class="wa-when" id="waWhen"></div>
<div class="add-row">
<input type="text" id="waInput" placeholder="What do you need to raise with the Web Alignment Team? (decision, blocker, ask, alignment needed…)" onkeydown="if(event.key==='Enter') addWaItem()">
<button onclick="addWaItem()">Add</button>
</div>
<div id="waList"></div>
</div>
</div>
</div>
</div>
`;
const waJs = fs.readFileSync(`${BASE}/wa_section.js`, "utf8");
const out = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ServiceMeow HQ — Roadmap + UAT Launches</title>
<style>
${R.style}
${tabCss}
${cs}
</style>
</head>
<body>
${tabHtml}
<div id="tab-roadmap" class="tabpane">
${R.body}
</div>
<div id="tab-uat" class="tabpane">
${ub}
</div>
${waHtml}
<script>
${R.script}
</script>
<script>
${us}
</script>
<script>
${tabJs}
</script>
<script>
${waJs}
</script>
</body>
</html>
`;
fs.writeFileSync(`${BASE}/ServiceMeow-HQ.html`, out);
console.log("wrote ServiceMeow-HQ.html", out.length, "bytes");

1
node_modules/.bin/specificity generated vendored Symbolic link
View File

@ -0,0 +1 @@
../@bramus/specificity/bin/cli.js

1
node_modules/.bin/tldts generated vendored Symbolic link
View File

@ -0,0 +1 @@
../tldts/bin/cli.js

486
node_modules/.package-lock.json generated vendored Normal file
View File

@ -0,0 +1,486 @@
{
"lockfileVersion": 3,
"requires": true,
"packages": {
"node_modules/@asamuzakjp/css-color": {
"version": "7.1.5",
"resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-7.1.5.tgz",
"integrity": "sha512-jCpAvj8apa7SKHZYogk0rbXB3Kb0hLFrpkWF+Ap+vBA5rirItnpv9NKyAyEuDuFizvl0qwnj6JWR70RGJ0rOlw==",
"license": "MIT",
"dependencies": {
"@csstools/css-calc": "^3.4.3",
"@csstools/css-color-parser": "^4.2.6",
"@csstools/css-parser-algorithms": "^4.0.2",
"@csstools/css-tokenizer": "^4.0.2",
"lru-cache": "^11.5.3"
},
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}
},
"node_modules/@asamuzakjp/dom-selector": {
"version": "9.2.4",
"resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-9.2.4.tgz",
"integrity": "sha512-YnVzxDxLaqL0t7Q4wfcgHZjg55Wm6y5EaO7Bhu3q9J7wq/8iw3PhsnWiOQhYekx4VexnbkgWpTT6n+QIV7kczw==",
"license": "MIT",
"dependencies": {
"bidi-js": "^1.1.0",
"css-tree": "^3.2.1",
"is-potential-custom-element-name": "^1.0.1",
"lru-cache": "^11.5.3"
},
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}
},
"node_modules/@bramus/specificity": {
"version": "2.4.3",
"resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.3.tgz",
"integrity": "sha512-0GEz8qJWokkUVYQYRukmkSHIFNoBH8QTreeHrAFbvz1XFYc3Y+puhMs8PQ5x8GNugiC2l5jvDBXKLbBIByeSBw==",
"license": "MIT",
"dependencies": {
"css-tree": "^3.2.1"
},
"bin": {
"specificity": "bin/cli.js"
}
},
"node_modules/@csstools/color-helpers": {
"version": "6.1.2",
"resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.2.tgz",
"integrity": "sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"license": "MIT-0",
"engines": {
"node": ">=20.19.0"
}
},
"node_modules/@csstools/css-calc": {
"version": "3.4.3",
"resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.3.tgz",
"integrity": "sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"license": "MIT",
"engines": {
"node": ">=20.19.0"
},
"peerDependencies": {
"@csstools/css-parser-algorithms": "^4.0.2",
"@csstools/css-tokenizer": "^4.0.2"
}
},
"node_modules/@csstools/css-color-parser": {
"version": "4.2.6",
"resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.6.tgz",
"integrity": "sha512-iiPQ3iRWwnJkeEn6RIu6SJPr7hYrLz6XZ9s/QZl+2/LI5KQVjpl2fdmDSZKuD4xP6GMmMPgHFFXg6k1Wkz0Trg==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"license": "MIT",
"dependencies": {
"@csstools/color-helpers": "^6.1.2",
"@csstools/css-calc": "^3.4.3"
},
"engines": {
"node": ">=20.19.0"
},
"peerDependencies": {
"@csstools/css-parser-algorithms": "^4.0.2",
"@csstools/css-tokenizer": "^4.0.2"
}
},
"node_modules/@csstools/css-parser-algorithms": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.2.tgz",
"integrity": "sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"license": "MIT",
"engines": {
"node": ">=20.19.0"
},
"peerDependencies": {
"@csstools/css-tokenizer": "^4.0.2"
}
},
"node_modules/@csstools/css-syntax-patches-for-csstree": {
"version": "1.1.15",
"resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.15.tgz",
"integrity": "sha512-J0u7HkVl2nzSlhsiTOp4AmwcUQ3D+mGEEKfBy/7To5/y7F2OHwyLrXfrhR0SMgr4p5Lo+eaMVSeai24zUcBIxA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"license": "MIT-0",
"peerDependencies": {
"css-tree": "^3.2.1"
},
"peerDependenciesMeta": {
"css-tree": {
"optional": true
}
}
},
"node_modules/@csstools/css-tokenizer": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.2.tgz",
"integrity": "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"license": "MIT",
"engines": {
"node": ">=20.19.0"
}
},
"node_modules/@exodus/bytes": {
"version": "1.16.0",
"resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz",
"integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==",
"license": "MIT",
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
},
"peerDependencies": {
"@noble/hashes": "^1.8.0 || ^2.0.0"
},
"peerDependenciesMeta": {
"@noble/hashes": {
"optional": true
}
}
},
"node_modules/bidi-js": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz",
"integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==",
"license": "MIT",
"dependencies": {
"require-from-string": "^2.0.2"
}
},
"node_modules/css-tree": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz",
"integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==",
"license": "MIT",
"dependencies": {
"mdn-data": "2.27.1",
"source-map-js": "^1.2.1"
},
"engines": {
"node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0"
}
},
"node_modules/data-urls": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz",
"integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==",
"license": "MIT",
"dependencies": {
"whatwg-mimetype": "^5.0.0",
"whatwg-url": "^17.1.2"
},
"engines": {
"node": "^22.14.0 || >=24.0.0"
}
},
"node_modules/decimal.js": {
"version": "10.6.0",
"resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
"integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",
"license": "MIT"
},
"node_modules/entities": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz",
"integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=20.19.0"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/html-encoding-sniffer": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz",
"integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==",
"license": "MIT",
"dependencies": {
"@exodus/bytes": "^1.15.1"
},
"engines": {
"node": "^22.13.0 || >=24.0.0"
}
},
"node_modules/is-potential-custom-element-name": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
"integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
"license": "MIT"
},
"node_modules/jsdom": {
"version": "30.1.2",
"resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.1.2.tgz",
"integrity": "sha512-0FFE/jE1rppmVfUrJUgxqXjcwolZYIGtAgj1pTussMhNZxIxi7W/PvfWaMNroGi2B36X1IKHbexpZ9DhkoOPiQ==",
"license": "MIT",
"dependencies": {
"@asamuzakjp/css-color": "^7.1.3",
"@asamuzakjp/dom-selector": "^9.2.4",
"@bramus/specificity": "^2.4.2",
"@csstools/css-syntax-patches-for-csstree": "^1.1.15",
"@exodus/bytes": "^1.16.0",
"css-tree": "^3.2.1",
"data-urls": "^8.0.0",
"decimal.js": "^10.6.0",
"html-encoding-sniffer": "^7.0.0",
"is-potential-custom-element-name": "^1.0.1",
"lru-cache": "^11.5.3",
"parse5": "^8.0.1",
"saxes": "^6.0.0",
"tough-cookie": "^6.0.2",
"undici": "^8.11.2",
"w3c-xmlserializer": "^6.0.0",
"webidl-conversions": "^8.0.1",
"whatwg-mimetype": "^5.0.0",
"whatwg-url": "^17.2.0",
"xml-name-validator": "^5.0.0"
},
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
"peerDependencies": {
"canvas": "^3.2.3"
},
"peerDependenciesMeta": {
"canvas": {
"optional": true
}
}
},
"node_modules/lru-cache": {
"version": "11.5.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
"integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
"license": "BlueOak-1.0.0",
"engines": {
"node": "20 || >=22"
}
},
"node_modules/mdn-data": {
"version": "2.27.1",
"resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",
"integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",
"license": "CC0-1.0"
},
"node_modules/parse5": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",
"integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==",
"license": "MIT",
"dependencies": {
"entities": "^8.0.0"
},
"funding": {
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/require-from-string": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
"integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/saxes": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
"integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
"license": "ISC",
"dependencies": {
"xmlchars": "^2.2.0"
},
"engines": {
"node": ">=v12.22.7"
}
},
"node_modules/source-map-js": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
"integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/tldts": {
"version": "7.4.18",
"resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.18.tgz",
"integrity": "sha512-somxA8xKAUzlAxl0TX/jMSYIbRNFIVGnI96pVGJPeMc5BsHmfVXn6mOJT6U++ELnl04eGfzpfcEuZe8WiASkXg==",
"license": "MIT",
"dependencies": {
"tldts-core": "^7.4.18"
},
"bin": {
"tldts": "bin/cli.js"
}
},
"node_modules/tldts-core": {
"version": "7.4.18",
"resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.18.tgz",
"integrity": "sha512-KI2PKvCmvQI/xD6ypPqkU0i7oxNXR/O58RLRaHR4svsgVUQ2JE/XC8BtMbG6PSehD27I8sZJRcC1ASnCy6lp3g==",
"license": "MIT"
},
"node_modules/tough-cookie": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz",
"integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==",
"license": "BSD-3-Clause",
"dependencies": {
"tldts": "^7.0.5"
},
"engines": {
"node": ">=16"
}
},
"node_modules/tr46": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz",
"integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==",
"license": "MIT",
"dependencies": {
"punycode": "^2.3.1"
},
"engines": {
"node": "^22.14.0 || >=24.0.0"
}
},
"node_modules/undici": {
"version": "8.12.1",
"resolved": "https://registry.npmjs.org/undici/-/undici-8.12.1.tgz",
"integrity": "sha512-usz3OVQBeh1LxNn0DzU0voLXMgn5CU/WUdpBsY6Ti5afNao+vTkmn4H/NxoXolc10cOqe2+YIG0Hspq2rsl64w==",
"license": "MIT",
"engines": {
"node": ">=22.19.0"
}
},
"node_modules/w3c-xmlserializer": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz",
"integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==",
"license": "MIT",
"dependencies": {
"xml-name-validator": "^5.0.0"
},
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}
},
"node_modules/webidl-conversions": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz",
"integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=20"
}
},
"node_modules/whatwg-mimetype": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz",
"integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==",
"license": "MIT",
"engines": {
"node": ">=20"
}
},
"node_modules/whatwg-url": {
"version": "17.3.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.3.0.tgz",
"integrity": "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==",
"license": "MIT",
"dependencies": {
"@exodus/bytes": "^1.16.0",
"tr46": "^7.0.0",
"webidl-conversions": "^8.0.1"
},
"engines": {
"node": "^22.14.0 || >=24.0.0"
}
},
"node_modules/xml-name-validator": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
"integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
"license": "Apache-2.0",
"engines": {
"node": ">=18"
}
},
"node_modules/xmlchars": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
"integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
"license": "MIT"
}
}
}

21
node_modules/@asamuzakjp/css-color/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 asamuzaK (Kazz)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

149
node_modules/@asamuzakjp/css-color/README.md generated vendored Normal file
View File

@ -0,0 +1,149 @@
# CSS color
[![build](https://github.com/asamuzaK/cssColor/actions/workflows/node.js.yml/badge.svg)](https://github.com/asamuzaK/cssColor/actions/workflows/node.js.yml)
[![CodeQL](https://github.com/asamuzaK/cssColor/actions/workflows/github-code-scanning/codeql/badge.svg)](https://github.com/asamuzaK/cssColor/actions/workflows/github-code-scanning/codeql)
[![npm (scoped)](https://img.shields.io/npm/v/@asamuzakjp/css-color)](https://www.npmjs.com/package/@asamuzakjp/css-color)
A robust and modern library to resolve, parse, and convert CSS colors.
Supports the latest CSS Color Module Level 4 & 5 specifications.
## Features
- **Modern CSS Color Support:** Accurately resolves `color-mix()`, `color()`, modern color spaces (`oklch`, `oklab`, `lch`, `lab`, `hwb`, etc.), and relative colors (`lab(from red l a b)`, `color(from red xyz-d50 x y z)`).
- **Deep Resolution:** Deeply resolves `var()` and `calc()` functions embedded within color values.
- **Gradient Resolution & Parsing:** Supports resolving, parsing, and validation for `linear-gradient`, `radial-gradient`, and `conic-gradient`.
- **Comprehensive Color Conversion:** Highly accurate converters between HEX, HSL, HWB, LAB, LCH, Oklab, Oklch, RGB, and XYZ color spaces.
- **Bonus Utilities:** Includes convenient functions to validate colors or gradients, extract CSS variables, and safely split CSS values.
- **Used in jsdom:** Adopted as the CSS color parser and resolver for `jsdom`.
- **Pure ESM with TypeScript Ready:** Native ESM (`type: "module"`) with comprehensive TypeScript definitions.
## Install
```console
npm i @asamuzakjp/css-color
```
## Quick Start
```javascript
import {
convert,
resolve,
resolveGradient,
utils
} from '@asamuzakjp/css-color';
```
### Samples
1. Resolve complex modern CSS colors:
```javascript
const resolvedMix = resolve(
'color-mix(in oklab, lch(67.5345 42.5 258.2), color(srgb 0 0.5 0))'
);
// => 'oklab(0.620754 -0.0931934 -0.00374881)'
```
2. Resolve with Custom Properties and calc():
```javascript
const resolvedVar = resolve('hsl(calc(var(--base-hue) * 3) 100% 50% / .5)', {
customProperty: { '--base-hue': '210deg' }
});
// => 'rgba(128, 0, 255, 0.5)'
```
3. Resolve gradients:
```javascript
const resolvedGradient = resolveGradient(
'linear-gradient(to right, red, blue)'
);
// => 'linear-gradient(to right, rgb(255 0 0), rgb(0 0 255))'
```
4. Convert between color spaces:
```javascript
const hex = convert.colorToHex('lab(46.2775% -47.5621 48.5837)');
// => '#008000'
```
5. Validate colors and gradients:
```javascript
const isColor = utils.isColor('light-dark(red, blue)');
// => true
const isGradient = utils.isGradient(
'conic-gradient(from 0.5turn at 50% 50%, red, blue)'
);
// => true
```
## API Reference
### `resolve(color, opt?)`
Resolves a CSS color string into its computed or specified value. System colors are not supported.
- **`color`** `<string>`: The CSS color value to resolve.
- **`opt`** `<object>` _(optional)_:
- `opt.currentColor`: Color to use for the `currentcolor` keyword.
- `opt.customProperty`: Object containing `--` prefixed keys and their values, or a `callback(propertyName)` function to dynamically resolve CSS variables.
- `opt.dimension`: Object mapping units (e.g., `em`, `rem`, `vw`) to pixel numbers, or a `callback(unit)` function for dynamic length resolution.
- `opt.format`: Output format. Options: `computedValue` (default), `specifiedValue`, `hex`, `hexAlpha`.
- `opt.colorScheme`: `normal` (default), `light`, or `dark` (useful for `light-dark()` resolution).
### `resolveGradient(gradient, opt?)`
Resolves a CSS gradient string (e.g., `linear-gradient`, `radial-gradient`, `conic-gradient`) into its resolved form.
- **`gradient`** `<string>`: The CSS gradient string to resolve.
- **`opt`** `<object>` _(optional)_: Same options as `resolve`.
### `convert`
A collection of color conversion utilities.
<!-- prettier-ignore -->
| Function | Returns | Options | Description |
| :-------------- | :-------------- | :-------------- | :-------------- |
| `convert.colorToHex(value, opt?)` | `string \| null` | `opt.alpha` `<boolean>`<br>_(+ see `resolve` options)_ | Returns `#rrggbb` or `#rrggbbaa` (if `opt.alpha` is true). |
| `convert.colorToHsl(value, opt?)` | `number[]` | _See `resolve` options_ | Converts to HSL channels: `[h, s, l, alpha]` |
| `convert.colorToHwb(value, opt?)` | `number[]` | _See `resolve` options_ | Converts to HWB channels: `[h, w, b, alpha]` |
| `convert.colorToLab(value, opt?)` | `number[]` | _See `resolve` options_ | Converts to CIE LAB channels: `[l, a, b, alpha]` |
| `convert.colorToLch(value, opt?)` | `number[]` | _See `resolve` options_ | Converts to CIE LCH channels: `[l, c, h, alpha]` |
| `convert.colorToOklab(value, opt?)` | `number[]` | _See `resolve` options_ | Converts to Oklab channels: `[l, a, b, alpha]` |
| `convert.colorToOklch(value, opt?)` | `number[]` | _See `resolve` options_ | Converts to Oklch channels: `[l, c, h, alpha]` |
| `convert.colorToRgb(value, opt?)` | `number[]` | _See `resolve` options_ | Converts to sRGB channels: `[r, g, b, alpha]` |
| `convert.colorToXyz(value, opt?)` | `number[]` | _See `resolve` options_ | Converts to CIE XYZ channels (defaults to D65): `[x, y, z, alpha]` |
| `convert.colorToXyzD50(value, opt?)` | `number[]` | _See `resolve` options_ | Converts to CIE XYZ channels with D50 white point. |
### `utils`
Helpful internal tools exposed for advanced usage, parsing, and validation.
<!-- prettier-ignore -->
| Function | Returns | Options (`opt`) | Description |
| :-------------- | :-------------- | :-------------- | :-------------- |
| `utils.cssCalc(value, opt?)` | `string` | `opt.dimension`<br>_(+ see `resolve` options)_ | Resolves CSS `calc()` expressions. |
| `utils.cssVar(value, opt?)` | `string` | `opt.customProperty`<br>_(+ see `resolve` options)_ | Resolves CSS `var()` expressions. |
| `utils.extractDashedIdent(value)` | `string[]` | _None_ | Extracts custom property names (dashed-ident tokens) from a value. |
| `utils.isColor(value, opt?)` | `boolean` | _See `resolve` options_ | Returns `true` if the string is a valid CSS color. |
| `utils.isGradient(value, opt?)` | `boolean` | _See `resolve` options_ | Returns `true` if the string is a valid CSS gradient. |
| `utils.resolveGradient(value, opt?)` | `string` | _See `resolve` options_ | **Deprecated:** Use `resolveGradient` directly instead. |
| `utils.resolveLengthInPixels(value, unit, opt?)` | `number` | `opt.dimension`<br>_(+ see `resolve` options)_ | Converts an absolute or relative CSS length to pixels. |
| `utils.splitValue(value, opt?)` | `string[]` | `opt.delimiter` `<string>`<br>`opt.preserveComment` `<boolean>` | Safely splits a CSS value by a specified delimiter (` `, `,`, `/`). |
## Acknowledgments
The following resources have been of great help in the development of this library:
- [csstools/postcss-plugins](https://github.com/csstools/postcss-plugins)
- [lru-cache](https://github.com/isaacs/node-lru-cache)
---
Copyright (c) 2024 [asamuzaK (Kazz)](https://github.com/asamuzaK/)

View File

@ -0,0 +1,67 @@
/**
* color
*/
import { ColorChannels, ColorChannelsWithPowerless, LinearRgbOptions, Options } from '../typedef';
/**
* convert color value to linear rgb
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [r, g, b, alpha] r|g|b|alpha: 0..1
*/
export declare const convertColorToLinearRgb: (value: string, opt?: LinearRgbOptions) => ColorChannels | null;
/**
* convert color value to rgb
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1
*/
export declare const convertColorToRgb: (value: string, opt?: Options) => ColorChannels | null;
/**
* convert color value to xyz
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [x, y, z, alpha]
*/
export declare const convertColorToXyz: (value: string, opt?: Options) => ColorChannels | null;
/**
* convert color value to hsl
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [h, s, l, alpha], hue may be powerless
*/
export declare const convertColorToHsl: (value: string, opt?: Options) => ColorChannels | ColorChannelsWithPowerless | null;
/**
* convert color value to hwb
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [h, w, b, alpha], hue may be powerless
*/
export declare const convertColorToHwb: (value: string, opt?: Options) => ColorChannels | [number | string, number, number, number] | null;
/**
* convert color value to lab
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [l, a, b, alpha]
*/
export declare const convertColorToLab: (value: string, opt?: Options) => ColorChannels | null;
/**
* convert color value to lch
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [l, c, h, alpha], hue may be powerless
*/
export declare const convertColorToLch: (value: string, opt?: Options) => ColorChannels | [number, number, number | string, number] | null;
/**
* convert color value to oklab
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [l, a, b, alpha]
*/
export declare const convertColorToOklab: (value: string, opt?: Options) => ColorChannels | null;
/**
* convert color value to oklch
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [l, c, h, alpha], hue may be powerless
*/
export declare const convertColorToOklch: (value: string, opt?: Options) => ColorChannels | [number, number, number | string, number] | null;

View File

@ -0,0 +1,47 @@
/**
* convert-hex
*/
import { ColorChannels } from '../typedef';
/**
* convert rgb to hex color
* @param rgb - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1
* @returns hex color
*/
export declare const convertRgbToHex: (rgb: ColorChannels) => string;
/**
* convert linear rgb to hex color
* @param rgb - [r, g, b, alpha] r|g|b|alpha: 0..1
* @param [skip] - skip validate
* @returns hex color
*/
export declare const convertLinearRgbToHex: (rgb: ColorChannels, skip?: boolean) => string;
/**
* convert xyz to hex color
* @param xyz - [x, y, z, alpha]
* @returns hex color
*/
export declare const convertXyzToHex: (xyz: ColorChannels) => string;
/**
* convert xyz D50 to hex color
* @param xyz - [x, y, z, alpha]
* @returns hex color
*/
export declare const convertXyzD50ToHex: (xyz: ColorChannels) => string;
/**
* convert hex color to rgb
* @param value - hex color value
* @returns ColorChannels - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1
*/
export declare const convertHexToRgb: (value: string) => ColorChannels;
/**
* convert hex color to linear rgb
* @param value - hex color value
* @returns ColorChannels - [r, g, b, alpha] r|g|b|alpha: 0..1
*/
export declare const convertHexToLinearRgb: (value: string) => ColorChannels;
/**
* convert hex color to xyz
* @param value - hex color value
* @returns ColorChannels - [x, y, z, alpha]
*/
export declare const convertHexToXyz: (value: string) => ColorChannels;

View File

@ -0,0 +1,101 @@
/**
* convert
*/
import { ColorChannels, Options } from '../typedef';
/**
* pre process
* @param value - CSS color value
* @param opt - options
* @returns value
*/
export declare const preProcess: (value: string, opt: Options) => string | null;
/**
* convert number to hex string
* @param value - numeric value
* @returns hex string: 00..ff
*/
export declare const numberToHex: (value: number) => string;
/**
* convert color to hex
* @param value - CSS color value
* @param [opt] - options
* @param [opt.alpha] - enable alpha channel
* @returns #rrggbb | #rrggbbaa | null
*/
export declare const colorToHex: (value: string, opt?: Options) => string | null;
/**
* convert color to hsl
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [h, s, l, alpha]
*/
export declare const colorToHsl: (value: string, opt?: Options) => ColorChannels;
/**
* convert color to hwb
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [h, w, b, alpha]
*/
export declare const colorToHwb: (value: string, opt?: Options) => ColorChannels;
/**
* convert color to lab
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [l, a, b, alpha]
*/
export declare const colorToLab: (value: string, opt?: Options) => ColorChannels;
/**
* convert color to lch
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [l, c, h, alpha]
*/
export declare const colorToLch: (value: string, opt?: Options) => ColorChannels;
/**
* convert color to oklab
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [l, a, b, alpha]
*/
export declare const colorToOklab: (value: string, opt?: Options) => ColorChannels;
/**
* convert color to oklch
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [l, c, h, alpha]
*/
export declare const colorToOklch: (value: string, opt?: Options) => ColorChannels;
/**
* convert color to rgb
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [r, g, b, alpha]
*/
export declare const colorToRgb: (value: string, opt?: Options) => ColorChannels;
/**
* convert color to xyz
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [x, y, z, alpha]
*/
export declare const colorToXyz: (value: string, opt?: Options) => ColorChannels;
/**
* convert color to xyz-d50
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [x, y, z, alpha]
*/
export declare const colorToXyzD50: (value: string, opt?: Options) => ColorChannels;
export declare const convert: {
colorToHex: (value: string, opt?: Options) => string | null;
colorToHsl: (value: string, opt?: Options) => ColorChannels;
colorToHwb: (value: string, opt?: Options) => ColorChannels;
colorToLab: (value: string, opt?: Options) => ColorChannels;
colorToLch: (value: string, opt?: Options) => ColorChannels;
colorToOklab: (value: string, opt?: Options) => ColorChannels;
colorToOklch: (value: string, opt?: Options) => ColorChannels;
colorToRgb: (value: string, opt?: Options) => ColorChannels;
colorToXyz: (value: string, opt?: Options) => ColorChannels;
colorToXyzD50: (value: string, opt?: Options) => ColorChannels;
numberToHex: (value: number) => string;
};

View File

@ -0,0 +1,56 @@
/**
* gradient-util
*/
import { Options, ValidateGradientLine, ValidateColorStops } from '../typedef';
/**
* get gradient type
* @param value - gradient value
* @returns gradient type
*/
export declare const getGradientType: (value: string) => string;
/**
* validate linear-gradient line
* @param value - line value
* @returns result
*/
export declare const validateLinearGradientLine: (value: string) => ValidateGradientLine;
/**
* validate radial-gradient line
* @param value - line value
* @returns result
*/
export declare const validateRadialGradientLine: (value: string) => ValidateGradientLine;
/**
* validate conic-gradient line
* @param value - line value
* @returns result
*/
export declare const validateConicGradientLine: (value: string) => ValidateGradientLine;
/**
* validate gradient line
* @param value - gradient line value
* @param type - gradient type
* @returns result
*/
export declare const validateGradientLine: (value: string, type: string) => ValidateGradientLine;
/**
* Split a color stop into its original component values.
* @param value - color stop or transition hint
* @returns color and position components, retaining comments inside functions
*/
export declare const splitColorStop: (value: string) => string[];
/**
* Validate a position in a gradient color stop or transition hint.
* @param value - original position component
* @param isConic - whether the gradient uses angle-percentage positions
* @returns whether the position is valid in this gradient context
*/
export declare const isValidPosition: (value: string, isConic: boolean) => boolean;
/**
* validate color stop list
* @param list - color stop list
* @param type - gradient type
* @param [opt] - options
* @returns validated result
*/
export declare const validateColorStopList: (list: string[], type: string, opt?: Options) => ValidateColorStops;

View File

@ -0,0 +1,18 @@
/**
* gradient
*/
import { Options } from '../typedef';
/**
* resolve CSS gradient
* @param value - CSS value
* @param [opt] - options
* @returns result
*/
export declare const resolveGradient: (value: string, opt?: Options) => string;
/**
* is CSS gradient
* @param value - CSS value
* @param [opt] - options
* @returns result
*/
export declare const isGradient: (value: string, opt?: Options) => boolean;

View File

@ -0,0 +1,11 @@
/**
* gradient
*/
import { Gradient, Options } from '../typedef';
/**
* parse CSS gradient
* @param value - gradient value
* @param [opt] - options
* @returns parsed result
*/
export declare const parseGradient: (value: string, opt?: Options) => Gradient | null;

22
node_modules/@asamuzakjp/css-color/dist/esm/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,22 @@
/*!
* CSS color - Resolve, parse, convert CSS color.
* @license MIT
* @copyright asamuzaK (Kazz)
* @see {@link https://github.com/asamuzaK/cssColor/blob/main/LICENSE}
*/
export { convert } from './converters/convert';
export { resolveGradient } from './gradients/gradient';
export { resolve } from './resolvers/resolve';
export declare const utils: {
cssCalc: (value: string, opt?: import("./typedef").Options) => string;
cssVar: (value: string, opt?: import("./typedef").Options) => string;
extractDashedIdent: (value: string) => string[];
isColor: (value: unknown, opt?: import("./typedef").Options) => boolean;
isGradient: (value: string, opt?: import("./typedef").Options) => boolean;
/**
* @deprecated Use `resolveGradient` directly instead.
*/
resolveGradient: (value: string, opt?: import("./typedef").Options) => string;
resolveLengthInPixels: (value: number | string, unit: string | undefined, opt?: import("./typedef").Options) => number;
splitValue: (value: string, opt?: import("./typedef").Options) => string[];
};

3731
node_modules/@asamuzakjp/css-color/dist/esm/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,21 @@
/**
* matrix
*/
import { ReadonlyColorMatrix, ReadonlyTriColorChannels } from '../typedef';
/**
* conversion matrices
* @see https://drafts.csswg.org/css-color-4/#color-conversion-code
*/
export declare const D50: ReadonlyTriColorChannels;
export declare const MATRIX_D50_TO_D65: ReadonlyColorMatrix;
export declare const MATRIX_D65_TO_D50: ReadonlyColorMatrix;
export declare const MATRIX_L_RGB_TO_XYZ: ReadonlyColorMatrix;
export declare const MATRIX_XYZ_TO_L_RGB: ReadonlyColorMatrix;
export declare const MATRIX_XYZ_TO_LMS: ReadonlyColorMatrix;
export declare const MATRIX_LMS_TO_XYZ: ReadonlyColorMatrix;
export declare const MATRIX_OKLAB_TO_LMS: ReadonlyColorMatrix;
export declare const MATRIX_LMS_TO_OKLAB: ReadonlyColorMatrix;
export declare const MATRIX_P3_TO_XYZ: ReadonlyColorMatrix;
export declare const MATRIX_REC2020_TO_XYZ: ReadonlyColorMatrix;
export declare const MATRIX_A98_TO_XYZ: ReadonlyColorMatrix;
export declare const MATRIX_PROPHOTO_TO_XYZ_D50: ReadonlyColorMatrix;

View File

@ -0,0 +1,122 @@
/**
* transform
*/
import { ColorChannels, NumStrColorChannels, ReadonlyColorMatrix, TriColorChannels, ValidateColorComponentsOptions } from '../typedef';
/**
* validate color components
* @param arr - color components
* @param opt - options
* @param opt.alpha - alpha channel
* @param opt.minLength - min length
* @param opt.maxLength - max length
* @param opt.minRange - min range
* @param opt.maxRange - max range
* @param opt.validateRange - validate range
* @returns result - validated color components
*/
export declare const validateColorComponents: (arr: ColorChannels | TriColorChannels, opt?: ValidateColorComponentsOptions) => ColorChannels | TriColorChannels;
/**
* normalize color components
* @param colorA - color components [v1, v2, v3, v4]
* @param colorB - color components [v1, v2, v3, v4]
* @param [skip] - skip validate
* @returns result - [colorA, colorB]
*/
export declare const normalizeColorComponents: (colorA: NumStrColorChannels, colorB: NumStrColorChannels, skip?: boolean) => [ColorChannels, ColorChannels];
/**
* transform matrix
* @param mtx - 3 * 3 matrix
* @param vct - vector
* @param [skip] - skip validate
* @returns TriColorChannels - [p1, p2, p3]
*/
export declare const transformMatrix: (mtx: ReadonlyColorMatrix, vct: TriColorChannels, skip?: boolean) => TriColorChannels;
/**
* transform rgb to linear rgb
* @param rgb - [r, g, b] r|g|b: 0..255
* @param [skip] - skip validate
* @returns TriColorChannels - [r, g, b] r|g|b: 0..1
*/
export declare const transformRgbToLinearRgb: (rgb: TriColorChannels, skip?: boolean) => TriColorChannels;
/**
* transform rgb to xyz
* @param rgb - [r, g, b] r|g|b: 0..255
* @param [skip] - skip validate
* @returns TriColorChannels - [x, y, z]
*/
export declare const transformRgbToXyz: (rgb: TriColorChannels, skip?: boolean) => TriColorChannels;
/**
* transform rgb to xyz-d50
* @param rgb - [r, g, b] r|g|b: 0..255 alpha: 0..1
* @returns TriColorChannels - [x, y, z]
*/
export declare const transformRgbToXyzD50: (rgb: TriColorChannels) => TriColorChannels;
/**
* transform linear rgb to rgb
* @param rgb - [r, g, b] r|g|b: 0..1
* @param [round] - round result
* @returns TriColorChannels - [r, g, b] r|g|b: 0..255
*/
export declare const transformLinearRgbToRgb: (rgb: TriColorChannels, round?: boolean) => TriColorChannels;
/**
* transform xyz to rgb
* @param xyz - [x, y, z]
* @param [skip] - skip validate
* @returns TriColorChannels - [r, g, b] r|g|b: 0..255
*/
export declare const transformXyzToRgb: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels;
/**
* transform xyz to xyz-d50
* @param xyz - [x, y, z]
* @returns TriColorChannels - [x, y, z]
*/
export declare const transformXyzToXyzD50: (xyz: TriColorChannels) => TriColorChannels;
/**
* transform xyz to hsl
* @param xyz - [x, y, z]
* @param [skip] - skip validate
* @returns TriColorChannels - [h, s, l]
*/
export declare const transformXyzToHsl: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels;
/**
* transform xyz to hwb
* @param xyz - [x, y, z]
* @param [skip] - skip validate
* @returns TriColorChannels - [h, w, b]
*/
export declare const transformXyzToHwb: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels;
/**
* transform xyz to oklab
* @param xyz - [x, y, z]
* @param [skip] - skip validate
* @returns TriColorChannels - [l, a, b]
*/
export declare const transformXyzToOklab: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels;
/**
* transform xyz to oklch
* @param xyz - [x, y, z]
* @param [skip] - skip validate
* @returns TriColorChannels - [l, c, h]
*/
export declare const transformXyzToOklch: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels;
/**
* transform xyz D50 to rgb
* @param xyz - [x, y, z]
* @param [skip] - skip validate
* @returns TriColorChannels - [r, g, b] r|g|b: 0..255
*/
export declare const transformXyzD50ToRgb: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels;
/**
* transform xyz-d50 to lab
* @param xyz - [x, y, z]
* @param [skip] - skip validate
* @returns TriColorChannels - [l, a, b]
*/
export declare const transformXyzD50ToLab: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels;
/**
* transform xyz-d50 to lch
* @param xyz - [x, y, z]
* @param [skip] - skip validate
* @returns TriColorChannels - [l, c, h]
*/
export declare const transformXyzD50ToLch: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels;

View File

@ -0,0 +1,166 @@
/**
* color-mix
*/
import { ChannelNoneFlags, ColorAndPct, ColorFormat, ColorResolverFn, ColorSpace, ColorSpaceParseResult, InterpolatedComponents, NormalizedPercentages, NumStrColorChannels, Options, SpecifiedColorChannels, TriColorChannels } from '../typedef';
/**
* parse color space
* @param arg - color space argument string
* @returns object containing colorSpace and hueArc, or null if invalid
*/
export declare const parseColorSpace: (arg: string) => ColorSpaceParseResult | null;
/**
* parse color and percentage
* @param arg - color and percentage argument string
* @returns object containing color string and percentage string
*/
export declare const parseColorAndPct: (arg: string) => ColorAndPct;
/**
* resolve if nested function
* @param colorStr - color string
* @param opt - options
* @param resolver - resolver function
* @returns resolved color string or original string
*/
export declare const resolveIfNested: (colorStr: string, opt: Options, resolver: ColorResolverFn) => string;
/**
* normalize percentages
* @param pctA - percentage for color A
* @param pctB - percentage for color B
* @returns object containing normalized percentages and multiplier, or null if invalid
*/
export declare const normalizePercentages: (pctA: string, pctB: string) => NormalizedPercentages | null;
/**
* process color
* @param colorStr - color string
* @param opt - options
* @returns specified color string
*/
export declare const processColor: (colorStr: string, opt: Options) => string;
/**
* build specified color mix
* @param colorSpace - color space
* @param hueArc - hue interpolation method
* @param colorA - first color
* @param pctA - percentage for first color
* @param colorB - second color
* @param pctB - percentage for second color
* @param opt - options
* @returns specified value string for color-mix()
*/
export declare const buildSpecifiedColorMix: (colorSpace: string, hueArc: string, colorA: string, pctA: string, colorB: string, pctB: string, opt: Options) => string;
/**
* Perform alpha-weighted interpolation for color components.
* @param compA - color components for color A
* @param compB - color components for color B
* @param alphaA - alpha channel value for color A
* @param alphaB - alpha channel value for color B
* @param pA - normalized ratio for first color
* @param pB - normalized ratio for second color
* @returns object containing interpolated components and combined alpha
*/
export declare const interpolateComponents: (compA: TriColorChannels, compB: TriColorChannels, alphaA: number, alphaB: number, pA: number, pB: number) => InterpolatedComponents;
/**
* Format computed color into specified or computed channel array.
* @param colorSpace - target color space
* @param comps - 3-channel color components
* @param nones - boolean flags indicating if channels are 'none'
* @param alpha - calculated alpha channel value
* @param m - multiplier factor
* @param format - output format option
* @param rgbOverride - optional pre-calculated RGB channels
* @returns specified color channels array
*/
export declare const formatMixedColor: (colorSpace: ColorSpace, comps: TriColorChannels, nones: ChannelNoneFlags, alpha: number, m: number, format: ColorFormat, rgbOverride?: TriColorChannels) => SpecifiedColorChannels;
/**
* Fetch raw channels or fallback for currentcolor
* @param color - color input string
* @param convertFn - conversion function
* @param opt - conversion options
* @returns color channel values or null if invalid
*/
export declare const getRawChannels: (color: string | NumStrColorChannels, convertFn: (c: string, opt: any) => any, opt: any) => NumStrColorChannels | null;
/**
* Mix colors in srgb or srgb-linear space.
* @param colorSpace - color space name ('srgb' | 'srgb-linear')
* @param colorA - first color string
* @param colorB - second color string
* @param pA - ratio for first color
* @param pB - ratio for second color
* @param format - output format
* @param m - multiplier factor
* @returns mixed color channels or null
*/
export declare const mixSrgbSpace: (colorSpace: ColorSpace, colorA: string, colorB: string, pA: number, pB: number, format: ColorFormat, m: number) => SpecifiedColorChannels | null;
/**
* Mix colors in xyz, xyz-d50, or xyz-d65 space.
* @param colorSpace - color space name
* @param colorA - first color string
* @param colorB - second color string
* @param pA - ratio for first color
* @param pB - ratio for second color
* @param format - output format
* @param m - multiplier factor
* @returns mixed color channels or null
*/
export declare const mixXyzSpace: (colorSpace: string, colorA: string, colorB: string, pA: number, pB: number, format: string, m: number) => SpecifiedColorChannels | null;
/**
* Mix colors in hsl or hwb space.
* @param colorSpace - color space name ('hsl' | 'hwb')
* @param hueArc - hue interpolation method
* @param colorA - first color string
* @param colorB - second color string
* @param pA - ratio for first color
* @param pB - ratio for second color
* @param format - output format
* @param m - multiplier factor
* @returns mixed color channels or null
*/
export declare const mixHslHwbSpace: (colorSpace: string, hueArc: string, colorA: string, colorB: string, pA: number, pB: number, format: string, m: number) => SpecifiedColorChannels | null;
/**
* Mix colors in lch or oklch space.
* @param colorSpace - color space name ('lch' | 'oklch')
* @param hueArc - hue interpolation method
* @param colorA - first color string
* @param colorB - second color string
* @param pA - ratio for first color
* @param pB - ratio for second color
* @param format - output format
* @param m - multiplier factor
* @returns mixed color channels or null
*/
export declare const mixLchSpace: (colorSpace: string, hueArc: string, colorA: string, colorB: string, pA: number, pB: number, format: string, m: number) => SpecifiedColorChannels | null;
/**
* Mix colors in lab or oklab space.
* @param colorSpace - color space name ('lab' | 'oklab')
* @param colorA - first color string
* @param colorB - second color string
* @param pA - ratio for first color
* @param pB - ratio for second color
* @param format - output format
* @param m - multiplier factor
* @returns mixed color channels or null
*/
export declare const mixLabSpace: (colorSpace: string, colorA: string, colorB: string, pA: number, pB: number, format: string, m: number) => SpecifiedColorChannels | null;
/**
* compute mixed color
* @param colorSpace - color space
* @param hueArc - hue interpolation method
* @param colorA - first color
* @param colorB - second color
* @param pA - normalized ratio for first color
* @param pB - normalized ratio for second color
* @param m - multiplier
* @param format - output format
* @param nullable - is nullable
* @param cacheKey - cache key
* @returns computed color channels or null
*/
export declare const computeMixedColor: (colorSpace: string, hueArc: string, colorA: string, colorB: string, pA: number, pB: number, m: number, format: string, nullable: boolean, cacheKey: string) => SpecifiedColorChannels | null;
/**
* resolve color-mix()
* @param value - color-mix color value
* @param opt - options
* @param resolver - resolver function
* @returns resolved color - [cs, v1, v2, v3, alpha], '(empty)', null
*/
export declare const resolveColorMix: (value: string, opt?: Options, resolver?: ColorResolverFn) => SpecifiedColorChannels | string | null;

View File

@ -0,0 +1,153 @@
/**
* named colors
*/
export declare const NAMED_COLORS: {
readonly aliceblue: readonly [240, 248, 255];
readonly antiquewhite: readonly [250, 235, 215];
readonly aqua: readonly [0, 255, 255];
readonly aquamarine: readonly [127, 255, 212];
readonly azure: readonly [240, 255, 255];
readonly beige: readonly [245, 245, 220];
readonly bisque: readonly [255, 228, 196];
readonly black: readonly [0, 0, 0];
readonly blanchedalmond: readonly [255, 235, 205];
readonly blue: readonly [0, 0, 255];
readonly blueviolet: readonly [138, 43, 226];
readonly brown: readonly [165, 42, 42];
readonly burlywood: readonly [222, 184, 135];
readonly cadetblue: readonly [95, 158, 160];
readonly chartreuse: readonly [127, 255, 0];
readonly chocolate: readonly [210, 105, 30];
readonly coral: readonly [255, 127, 80];
readonly cornflowerblue: readonly [100, 149, 237];
readonly cornsilk: readonly [255, 248, 220];
readonly crimson: readonly [220, 20, 60];
readonly cyan: readonly [0, 255, 255];
readonly darkblue: readonly [0, 0, 139];
readonly darkcyan: readonly [0, 139, 139];
readonly darkgoldenrod: readonly [184, 134, 11];
readonly darkgray: readonly [169, 169, 169];
readonly darkgreen: readonly [0, 100, 0];
readonly darkgrey: readonly [169, 169, 169];
readonly darkkhaki: readonly [189, 183, 107];
readonly darkmagenta: readonly [139, 0, 139];
readonly darkolivegreen: readonly [85, 107, 47];
readonly darkorange: readonly [255, 140, 0];
readonly darkorchid: readonly [153, 50, 204];
readonly darkred: readonly [139, 0, 0];
readonly darksalmon: readonly [233, 150, 122];
readonly darkseagreen: readonly [143, 188, 143];
readonly darkslateblue: readonly [72, 61, 139];
readonly darkslategray: readonly [47, 79, 79];
readonly darkslategrey: readonly [47, 79, 79];
readonly darkturquoise: readonly [0, 206, 209];
readonly darkviolet: readonly [148, 0, 211];
readonly deeppink: readonly [255, 20, 147];
readonly deepskyblue: readonly [0, 191, 255];
readonly dimgray: readonly [105, 105, 105];
readonly dimgrey: readonly [105, 105, 105];
readonly dodgerblue: readonly [30, 144, 255];
readonly firebrick: readonly [178, 34, 34];
readonly floralwhite: readonly [255, 250, 240];
readonly forestgreen: readonly [34, 139, 34];
readonly fuchsia: readonly [255, 0, 255];
readonly gainsboro: readonly [220, 220, 220];
readonly ghostwhite: readonly [248, 248, 255];
readonly gold: readonly [255, 215, 0];
readonly goldenrod: readonly [218, 165, 32];
readonly gray: readonly [128, 128, 128];
readonly green: readonly [0, 128, 0];
readonly greenyellow: readonly [173, 255, 47];
readonly grey: readonly [128, 128, 128];
readonly honeydew: readonly [240, 255, 240];
readonly hotpink: readonly [255, 105, 180];
readonly indianred: readonly [205, 92, 92];
readonly indigo: readonly [75, 0, 130];
readonly ivory: readonly [255, 255, 240];
readonly khaki: readonly [240, 230, 140];
readonly lavender: readonly [230, 230, 250];
readonly lavenderblush: readonly [255, 240, 245];
readonly lawngreen: readonly [124, 252, 0];
readonly lemonchiffon: readonly [255, 250, 205];
readonly lightblue: readonly [173, 216, 230];
readonly lightcoral: readonly [240, 128, 128];
readonly lightcyan: readonly [224, 255, 255];
readonly lightgoldenrodyellow: readonly [250, 250, 210];
readonly lightgray: readonly [211, 211, 211];
readonly lightgreen: readonly [144, 238, 144];
readonly lightgrey: readonly [211, 211, 211];
readonly lightpink: readonly [255, 182, 193];
readonly lightsalmon: readonly [255, 160, 122];
readonly lightseagreen: readonly [32, 178, 170];
readonly lightskyblue: readonly [135, 206, 250];
readonly lightslategray: readonly [119, 136, 153];
readonly lightslategrey: readonly [119, 136, 153];
readonly lightsteelblue: readonly [176, 196, 222];
readonly lightyellow: readonly [255, 255, 224];
readonly lime: readonly [0, 255, 0];
readonly limegreen: readonly [50, 205, 50];
readonly linen: readonly [250, 240, 230];
readonly magenta: readonly [255, 0, 255];
readonly maroon: readonly [128, 0, 0];
readonly mediumaquamarine: readonly [102, 205, 170];
readonly mediumblue: readonly [0, 0, 205];
readonly mediumorchid: readonly [186, 85, 211];
readonly mediumpurple: readonly [147, 112, 219];
readonly mediumseagreen: readonly [60, 179, 113];
readonly mediumslateblue: readonly [123, 104, 238];
readonly mediumspringgreen: readonly [0, 250, 154];
readonly mediumturquoise: readonly [72, 209, 204];
readonly mediumvioletred: readonly [199, 21, 133];
readonly midnightblue: readonly [25, 25, 112];
readonly mintcream: readonly [245, 255, 250];
readonly mistyrose: readonly [255, 228, 225];
readonly moccasin: readonly [255, 228, 181];
readonly navajowhite: readonly [255, 222, 173];
readonly navy: readonly [0, 0, 128];
readonly oldlace: readonly [253, 245, 230];
readonly olive: readonly [128, 128, 0];
readonly olivedrab: readonly [107, 142, 35];
readonly orange: readonly [255, 165, 0];
readonly orangered: readonly [255, 69, 0];
readonly orchid: readonly [218, 112, 214];
readonly palegoldenrod: readonly [238, 232, 170];
readonly palegreen: readonly [152, 251, 152];
readonly paleturquoise: readonly [175, 238, 238];
readonly palevioletred: readonly [219, 112, 147];
readonly papayawhip: readonly [255, 239, 213];
readonly peachpuff: readonly [255, 218, 185];
readonly peru: readonly [205, 133, 63];
readonly pink: readonly [255, 192, 203];
readonly plum: readonly [221, 160, 221];
readonly powderblue: readonly [176, 224, 230];
readonly purple: readonly [128, 0, 128];
readonly rebeccapurple: readonly [102, 51, 153];
readonly red: readonly [255, 0, 0];
readonly rosybrown: readonly [188, 143, 143];
readonly royalblue: readonly [65, 105, 225];
readonly saddlebrown: readonly [139, 69, 19];
readonly salmon: readonly [250, 128, 114];
readonly sandybrown: readonly [244, 164, 96];
readonly seagreen: readonly [46, 139, 87];
readonly seashell: readonly [255, 245, 238];
readonly sienna: readonly [160, 82, 45];
readonly silver: readonly [192, 192, 192];
readonly skyblue: readonly [135, 206, 235];
readonly slateblue: readonly [106, 90, 205];
readonly slategray: readonly [112, 128, 144];
readonly slategrey: readonly [112, 128, 144];
readonly snow: readonly [255, 250, 250];
readonly springgreen: readonly [0, 255, 127];
readonly steelblue: readonly [70, 130, 180];
readonly tan: readonly [210, 180, 140];
readonly teal: readonly [0, 128, 128];
readonly thistle: readonly [216, 191, 216];
readonly tomato: readonly [255, 99, 71];
readonly turquoise: readonly [64, 224, 208];
readonly violet: readonly [238, 130, 238];
readonly wheat: readonly [245, 222, 179];
readonly white: readonly [255, 255, 255];
readonly whitesmoke: readonly [245, 245, 245];
readonly yellow: readonly [255, 255, 0];
readonly yellowgreen: readonly [154, 205, 50];
};

View File

@ -0,0 +1,74 @@
/**
* parse
*/
import { Options, SpecifiedColorChannels } from '../typedef';
/**
* parse rgb()
* @param value - rgb color value
* @param opt - options
* @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', null
*/
export declare const parseRgb: (value: string, opt?: Options) => SpecifiedColorChannels | string | null;
/**
* parse hsl()
* @param value - hsl color value
* @param opt - options
* @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', null
*/
export declare const parseHsl: (value: string, opt?: Options) => SpecifiedColorChannels | string | null;
/**
* parse hwb()
* @param value - hwb color value
* @param opt - options
* @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', null
*/
export declare const parseHwb: (value: string, opt?: Options) => SpecifiedColorChannels | string | null;
/**
* parse lab()
* @param value - lab color value
* @param opt - options
* @returns parsed color
* - [xyz-d50, x, y, z, alpha], ['lab', l, a, b, alpha], '(empty)', null
*/
export declare const parseLab: (value: string, opt?: Options) => SpecifiedColorChannels | string | null;
/**
* parse lch()
* @param value - lch color value
* @param opt - options
* @returns parsed color
* - ['xyz-d50', x, y, z, alpha], ['lch', l, c, h, alpha], '(empty)', null
*/
export declare const parseLch: (value: string, opt?: Options) => SpecifiedColorChannels | string | null;
/**
* parse oklab()
* @param value - oklab color value
* @param opt - options
* @returns parsed color
* - ['xyz-d65', x, y, z, alpha], ['oklab', l, a, b, alpha], '(empty)', null
*/
export declare const parseOklab: (value: string, opt?: Options) => SpecifiedColorChannels | string | null;
/**
* parse oklch()
* @param value - oklch color value
* @param opt - options
* @returns parsed color
* - ['xyz-d65', x, y, z, alpha], ['oklch', l, c, h, alpha], '(empty)', null
*/
export declare const parseOklch: (value: string, opt?: Options) => SpecifiedColorChannels | string | null;
/**
* parse color()
* @param value - color function value
* @param opt - options
* @returns parsed color
* - ['xyz-(d50|d65)', x, y, z, alpha], [cs, r, g, b, alpha], '(empty)', null
*/
export declare const parseColorFunc: (value: string, opt?: Options) => SpecifiedColorChannels | string | null;
/**
* parse color value
* @param value - CSS color value
* @param opt - options
* @returns parsed color
* - ['xyz-(d50|d65)', x, y, z, alpha], ['rgb', r, g, b, alpha]
* - value, '(empty)', null
*/
export declare const parseColorValue: (value: string, opt?: Options) => SpecifiedColorChannels | string | null;

View File

@ -0,0 +1,67 @@
/**
* relative-color
*/
import { CSSToken } from '@csstools/css-tokenizer';
import { ColorChannels, Options, StringColorChannels } from '../typedef';
/**
* NumberOrStringColorChannels - color channel
*/
type NumberOrStringColorChannels = ColorChannels & StringColorChannels;
/**
* resolve relative color channels
* @param tokens - tokens
* @param [opt] - options
* @param [opt.currentColor]
* - color to use for `currentcolor` keyword
* - if omitted, it will be treated as a missing color
* i.e. `rgb(none none none / none)`
* @param [opt.customProperty]
* - custom properties
* - pair of `--` prefixed property name and value,
* e.g. `customProperty: { '--some-color': '#0000ff' }`
* - and/or `callback` function to get the value of the custom property,
* e.g. `customProperty: { callback: someDeclaration.getPropertyValue }`
* @param [opt.dimension]
* - dimension, convert relative length to pixels
* - pair of unit and it's value as a number in pixels,
* e.g. `dimension: { em: 12, rem: 16, vw: 10.26 }`
* - and/or `callback` function to get the value as a number in pixels,
* e.g. `dimension: { callback: convertUnitToPixel }`
* @param [opt.format]
* - output format, one of below
* - `computedValue` (default), [computed value][139] of the color
* - `specifiedValue`, [specified value][140] of the color
* - `hex`, hex color notation, i.e. `rrggbb`
* - `hexAlpha`, hex color notation with alpha channel, i.e. `#rrggbbaa`
* @returns
* - one of rgba?(), #rrggbb(aa)?, color-name, '(empty-string)',
* color(color-space r g b / alpha), color(color-space x y z / alpha),
* lab(l a b / alpha), lch(l c h / alpha), oklab(l a b / alpha),
* oklch(l c h / alpha), null
* - in `computedValue`, values are numbers, however `rgb()` values are
* integers
* - in `specifiedValue`, returns `empty string` for unknown and/or invalid
* color
* - in `hex`, returns `null` for `transparent`, and also returns `null` if
* any of `r`, `g`, `b`, `alpha` is not a number
* - in `hexAlpha`, returns `#00000000` for `transparent`,
* however returns `null` if any of `r`, `g`, `b`, `alpha` is not a number
*/
export declare function resolveColorChannels(tokens: CSSToken[], opt?: Options): NumberOrStringColorChannels | null;
/**
* extract origin color
* @param value - CSS color value
* @param opt - options
* @param resolver - resolver function
* @returns origin color value
*/
export declare function extractOriginColor(value: string, opt?: Options, resolver?: (v: string, o?: Options) => string | null): string | null;
/**
* resolve relative color
* @param value - CSS relative color value
* @param opt - options
* @param resolver - resolver function
* @returns resolved value
*/
export declare function resolveRelativeColor(value: string, opt?: Options, resolver?: (v: string, o?: Options) => string | null): string | null;
export {};

View File

@ -0,0 +1,33 @@
/**
* resolve-color
*/
import { Options, SpecifiedColorChannels } from '../typedef';
/**
* resolve color value
* @param value - CSS color value
* @param opt - options
* @returns resolved color
* - [cs, v1, v2, v3, alpha], value, '(empty)', null
*/
export declare const resolveColorValue: (value: string, opt?: Options) => SpecifiedColorChannels | string | null;
/**
* resolve color()
* @param value - color function value
* @param opt - options
* @returns resolved color - [cs, v1, v2, v3, alpha], '(empty)', null
*/
export declare const resolveColorFunc: (value: string, opt?: Options) => SpecifiedColorChannels | string | null;
/**
* resolve color
* @param value - CSS color value
* @param opt - options
* @returns resolved color
*/
export declare const resolveColor: (value: string, opt?: Options) => string | null;
/**
* is valid color
* @param value - CSS value
* @param opt - options
* @returns result
*/
export declare const isValidColor: (value: unknown, opt?: Options) => boolean;

View File

@ -0,0 +1,18 @@
/**
* resolve
*/
import { Options } from '../typedef';
/**
* resolve CSS color
* @param value - CSS color value. system colors are not supported
* @param opt - options
* @returns resolved value
*/
export declare const resolve: (value: string, opt?: Options) => string | null;
/**
* is color
* @param value - CSS value
* @param opt - options
* @returns result
*/
export declare const isColor: (value: unknown, opt?: Options) => boolean;

View File

@ -0,0 +1,321 @@
/**
* typedef
*/
import { CSSToken } from '@csstools/css-tokenizer';
/**
* Supported CSS gradient function types.
*/
export type GradientType = 'linear-gradient' | 'repeating-linear-gradient' | 'radial-gradient' | 'repeating-radial-gradient' | 'conic-gradient' | 'repeating-conic-gradient';
/**
* Known CSS color spaces.
*/
type KnownColorSpace = 'srgb' | 'srgb-linear' | 'display-p3' | 'a98-rgb' | 'prophoto-rgb' | 'rec2020' | 'xyz' | 'xyz-d50' | 'xyz-d65';
/**
* Supported CSS color space string or custom space.
*/
export type ColorSpace = KnownColorSpace | (string & {});
/**
* Known CSS color output and input formats.
*/
type KnownColorFormat = 'hex' | 'hexAlpha' | 'rgb' | 'hsl' | 'hwb' | 'lab' | 'lch' | 'oklab' | 'oklch' | 'computed' | 'specified' | 'mix';
/**
* Color format option or custom string.
*/
export type ColorFormat = KnownColorFormat | (string & {});
/**
* Hue interpolation methods for color spaces with hue.
*/
export type HueArc = 'shorter' | 'longer' | 'increasing' | 'decreasing';
/**
* Flags indicating missing or powerless channels [c1, c2, c3, alpha].
*/
export type ChannelNoneFlags = [
c1: boolean,
c2: boolean,
c3: boolean,
alpha: boolean
];
/**
* AST node representation for the calc() parser.
*/
export type CalcASTNode = string | CalcASTNode[];
/**
* Calculation token stream, including its terminal EOF token, and cursor.
*/
export interface CalculationState {
tokens: CSSToken[];
index: number;
}
/**
* Custom property resolver value or callback function.
*/
type CustomPropertyResolver = string | ((key: string) => string | undefined);
/**
* Dimension resolver value or callback function.
*/
type DimensionResolver = number | ((key: string) => number | undefined);
/**
* CSS dimension unit resolution map.
*/
interface DimensionMap {
[key: string]: DimensionResolver | undefined;
/** Custom dimension unit resolver callback. */
callback?: (key: string) => number | undefined;
/** Font size of the element in pixels. */
em?: number;
/** Root element font size in pixels. */
rem?: number;
/** Viewport height in pixels. */
vh?: number;
/** Viewport width in pixels. */
vw?: number;
}
/**
* Custom property lookup map or callback handler.
*/
interface CustomPropertyMap {
[key: string]: CustomPropertyResolver | undefined;
/** Custom property resolver callback function. */
callback?: (key: string) => string | undefined;
}
/**
* Parsing and resolution options.
*/
export interface Options {
/** Force alpha channel output. */
alpha?: boolean;
/** Preferred color scheme context. */
colorScheme?: string;
/** Target color space for output. */
colorSpace?: ColorSpace;
/** Value used for `currentColor` keyword. */
currentColor?: string;
/** Custom property resolvers. */
customProperty?: CustomPropertyMap;
/** Adapt XYZ coordinates to D50 illuminant. */
d50?: boolean;
/** Channel values delimiter string or list. */
delimiter?: string | readonly string[];
/** Dimension resolution settings. */
dimension?: DimensionMap;
/** Output color format. */
format?: ColorFormat;
/** Maximum length limit for parsed string. */
maxLength?: number;
/** Return null instead of throwing on invalid input. */
nullable?: boolean;
/** Retain comments during parsing. */
preserveComment?: boolean;
}
/**
* Three-element color channel tuple [x, y, z].
*/
export type TriColorChannels = [x: number, y: number, z: number];
/**
* Readonly three-element color channel tuple [x, y, z].
*/
export type ReadonlyTriColorChannels = readonly [
x: number,
y: number,
z: number
];
/**
* 3x3 color conversion matrix tuple.
*/
export type ReadonlyColorMatrix = readonly [
r1: ReadonlyTriColorChannels,
r2: ReadonlyTriColorChannels,
r3: ReadonlyTriColorChannels
];
/**
* Four-element color channel numeric tuple [x, y, z, alpha].
*/
export type ColorChannels = [x: number, y: number, z: number, alpha: number];
/**
* Four-element color channel string tuple [x, y, z, alpha].
*/
export type StringColorChannels = [
x: string,
y: string,
z: string,
alpha: string | undefined
];
/**
* Four-element color channel numeric/string tuple [x, y, z, alpha].
*/
export type NumStrColorChannels = [
x: number | string,
y: number | string,
z: number | string,
alpha: number | string
];
/**
* Color channel tuple with missing/powerless string tags.
*/
export type ColorChannelsWithPowerless = [
x: number | string,
y: number | string,
z: number | string,
alpha: number
];
/**
* Color space name and three channel strings with alpha.
*/
export type StringColorSpacedChannels = [
cs: string,
x: string,
y: string,
z: string,
alpha: string | undefined
];
/**
* Resolved computed color channel representation.
*/
export type ComputedColorChannels = [
cs: string,
x: number,
y: number,
z: number,
alpha: number
];
/**
* Resolved specified color channel representation.
*/
export type SpecifiedColorChannels = [
cs: string,
x: number | string,
y: number | string,
z: number | string,
alpha: number | string
];
/**
* RegExp match result tuple with 3 capture groups.
*/
export type MatchedRegExp3 = [
match: string,
gr1: string,
gr2: string,
gr3: string
];
/**
* RegExp match result tuple with 4 capture groups.
*/
export type MatchedRegExp4 = [
match: string,
gr1: string,
gr2: string,
gr3: string,
gr4: string
];
/**
* Standard matched RegExp tuple alias.
*/
export type MatchedRegExp = MatchedRegExp4;
/**
* Component validation configuration.
*/
export interface ValidateColorComponentsOptions {
/** Validate alpha channel presence. */
alpha?: boolean;
/** Minimum number of components. */
minLength?: number;
/** Maximum number of components. */
maxLength?: number;
/** Minimum allowed component value. */
minRange?: number;
/** Maximum allowed component value. */
maxRange?: number;
/** Whether to enforce component value range check. */
validateRange?: boolean;
}
/**
* Options for linear RGB conversion.
*/
export interface LinearRgbOptions {
/** Target color space for conversion. */
colorSpace?: ColorSpace;
/** Output color format. */
format?: ColorFormat;
}
/**
* Function type for converting color string to channel values.
*/
export type ColorConvertFn = (value: string, opt?: Options) => ColorChannels | ColorChannelsWithPowerless | null;
/**
* Function type for resolving CSS color expressions.
*/
export type ColorResolverFn = (value: string, opt?: Options) => SpecifiedColorChannels | string | null;
/**
* Parsed CSS gradient object structure.
*/
export interface Gradient {
/** Raw gradient CSS string value. */
value: string;
/** Type of gradient expression. */
type: GradientType;
/** Parsed gradient line parameter. */
gradientLine?: string;
/** List of color stops. */
colorStopList: ColorStopList;
}
/**
* Color stops validation result.
*/
export interface ValidateColorStops {
/** Extracted color stop strings. */
colorStops: string[];
/** Flag indicating stop list validity. */
valid: boolean;
}
/**
* Gradient line validation result.
*/
export interface ValidateGradientLine {
/** Extracted gradient line string. */
line: string;
/** Flag indicating line syntax validity. */
valid: boolean;
}
/**
* Tuple representing a minimum of two color stops.
*/
export type ColorStopList = [string, string, ...string[]];
/**
* Parsed color space parameter for color-mix().
*/
export interface ColorSpaceParseResult {
/** Color space name. */
colorSpace: ColorSpace;
/** Interpolation hue method. */
hueArc: HueArc | string;
}
/**
* Color and percentage pair for color-mix().
*/
export interface ColorAndPct {
/** Raw color string. */
color: string;
/** Raw percentage string. */
pct: string;
}
/**
* Normalized percentage values for color mixing.
*/
export interface NormalizedPercentages {
/** First color percentage weight (0 to 1). */
pA: number;
/** Second color percentage weight (0 to 1). */
pB: number;
/** Multiplier factor for un-normalized sums. */
m: number;
}
/**
* Interpolated channels and alpha output.
*/
export interface InterpolatedComponents {
/** Three-element color component values. */
comps: TriColorChannels;
/** Resulting alpha transparency. */
alpha: number;
}
export {};

View File

@ -0,0 +1,33 @@
/**
* cache
*/
import { LRUCache } from 'lru-cache';
import { Options } from '../typedef';
/**
* CacheItem
*/
export declare class CacheItem<T = unknown> {
#private;
constructor(item: T);
get item(): T;
}
export declare const lruCache: LRUCache<string, CacheItem<any>, unknown>;
/**
* set cache
* @param key - cache key
* @param value - value to cache
*/
export declare const setCache: <T>(key: string, value: T | CacheItem<T>) => void;
/**
* get cache
* @param key - cache key
* @returns cached item or false otherwise
*/
export declare const getCache: <T = unknown>(key: string) => CacheItem<T> | false;
/**
* create cache key
* @param keyData - key data
* @param [opt] - options
* @returns cache key
*/
export declare const createCacheKey: (keyData: Record<string, string>, opt?: Options) => string;

View File

@ -0,0 +1,21 @@
/**
* common
*/
/**
* get type
* @param o - object to check
* @returns type of object
*/
export declare const getType: (o: unknown) => string;
/**
* is string
* @param o - object to check
* @returns result
*/
export declare const isString: (o: unknown) => o is string;
/**
* is string or number
* @param o - object to check
* @returns result
*/
export declare const isStringOrNumber: (o: unknown) => o is string | number;

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,131 @@
/**
* css-calc-var
*/
import { CSSToken } from '@csstools/css-tokenizer';
import { CalcASTNode, Options } from '../typedef';
/**
* Calclator
*/
export declare class Calculator {
#private;
/**
* constructor
*/
constructor();
get hasNum(): boolean;
set hasNum(value: boolean);
get numSum(): number[];
get numMul(): number[];
get hasPct(): boolean;
set hasPct(value: boolean);
get pctSum(): number[];
get pctMul(): number[];
get hasDim(): boolean;
set hasDim(value: boolean);
get dimSum(): string[];
get dimSub(): string[];
get dimMul(): string[];
get dimDiv(): string[];
get hasEtc(): boolean;
set hasEtc(value: boolean);
get etcSum(): string[];
get etcSub(): string[];
get etcMul(): string[];
get etcDiv(): string[];
/**
* clear values
*/
clear(): void;
/**
* sort values
* @param values - values
* @returns sorted values
*/
sort(values?: string[]): string[];
/**
* multiply values
* @returns resolved value
*/
multiply(): string;
/**
* sum values
* @returns resolved value
*/
sum(): string;
}
/**
* sort calc values
* @param values - values to sort
* @param [finalize] - finalize values
* @returns sorted values
*/
export declare const sortCalcValues: (values?: (number | string)[], finalize?: boolean) => string;
/**
* sort math function terms
* @param expr - unwrapped calc expression
* @returns sorted expression
*/
export declare const sortMathFnTerms: (expr: string) => string;
/**
* resolve AST node
* @param node - AST node
* @param isRoot - is root node
* @returns resolved value
*/
export declare const resolveNode: (node: CalcASTNode[], isRoot: boolean) => string;
/**
* serialize calc
* @param value - CSS value
* @param [opt] - options
* @returns serialized value
*/
export declare const serializeCalc: (value: string, opt?: Options) => string;
/**
* resolve dimension
* @param token - CSS token
* @param [opt] - options
* @returns resolved value
*/
export declare const resolveDimension: (token: CSSToken, opt?: Options) => string | null;
/**
* parse CSS calc() tokens
* @param tokens - CSS tokens
* @param [opt] - options
* @returns parsed tokens
*/
export declare const parseCalcTokens: (tokens: CSSToken[], opt?: Options) => string[];
/**
* CSS calc()
* @param value - CSS value including calc()
* @param [opt] - options
* @returns resolved value
*/
export declare const cssCalc: (value: string, opt?: Options) => string;
/**
* resolve custom property
* @param tokens - CSS tokens
* @param [opt] - options
* @returns result - [tokens, resolvedValue]
*/
export declare function resolveCustomProperty(tokens: CSSToken[], opt?: Options): [CSSToken[], string];
/**
* parse CSS var() tokens
* @param tokens - CSS tokens
* @param [opt] - options
* @returns parsed tokens
*/
export declare function parseVarTokens(tokens: CSSToken[], opt?: Options): string[] | null;
/**
* resolve CSS var()
* @param value - CSS value including var()
* @param [opt] - options
* @returns resolved value
*/
export declare function resolveVar(value: string, opt?: Options): string | null;
/**
* CSS var()
* @param value - CSS value including var()
* @param [opt] - options
* @returns resolved value
*/
export declare const cssVar: (value: string, opt?: Options) => string;

View File

@ -0,0 +1,46 @@
/**
* length-percentage
*/
import { CSSToken } from '@csstools/css-tokenizer';
import { CalculationState } from '../typedef';
/**
* Advance past whitespace and comments in a calculation.
* @param state - token stream and cursor
*/
export declare const skipCalculationWhitespace: (state: CalculationState) => void;
/**
* Check for actual whitespace, ignoring adjacent comments.
* @param tokens - token stream
* @param start - first token to check
* @param step - direction to scan
* @returns whether whitespace occurs before another non-comment token
*/
export declare const hasCalculationWhitespace: (tokens: CSSToken[], start: number, step: 1 | -1) => boolean;
/**
* Parse multiplication and division of calculation operands.
* Multiplication requires a number on one side, division a number divisor.
* This subset intentionally excludes CSS Values Level 4 typed arithmetic.
* @param state - token stream and cursor
* @returns calculation type or null on failure
*/
export declare const parseCalculationProduct: (state: CalculationState) => number | null;
/**
* Parse addition and subtraction, requiring matching operand types.
* @param state - token stream and cursor
* @returns calculation type or null on failure
*/
export declare const parseCalculationSum: (state: CalculationState) => number | null;
/**
* Parse a scalar, length, percentage, parenthesized sum or math function.
* Percentages receive the length percent hint in this context.
* @param state - token stream and cursor
* @returns calculation type or null on failure
*/
export declare function parseCalculationValue(state: CalculationState): number | null;
/**
* Validate a calculation in a length-percentage context. Types are represented
* as 0 for numbers and 1 for lengths/percentages, with scalar products only.
* @param value - calculation
* @returns whether the calculation has type length-percentage
*/
export declare const isLengthPercentageCalculation: (value: unknown) => boolean;

View File

@ -0,0 +1,87 @@
/**
* util
*/
import { HueArc, Options, SpecifiedColorChannels } from '../typedef';
/**
* get max length
* @param [opt] - options
* @returns max length
*/
export declare const getMaxLength: (opt?: Options) => number;
/**
* split value
* NOTE: comments are stripped, it can be preserved if, in the options param,
* `delimiter` is either ',' or '/' and with `preserveComment` set to `true`
* @param value - CSS value
* @param [opt] - options
* @returns array of values
*/
export declare const splitValue: (value: string, opt?: Options) => string[];
/**
* extract dashed-ident tokens
* @param value - CSS value
* @returns array of dashed-ident tokens
*/
export declare const extractDashedIdent: (value: string) => string[];
/**
* round to specified precision
* @param value - numeric value
* @param bit - minimum bits
* @returns rounded value
*/
export declare const roundToPrecision: (value: number, bit?: number) => number;
/**
* interpolate hue
* @param hueA - hue value
* @param hueB - hue value
* @param arc - shorter | longer | increasing | decreasing
* @returns result - [hueA, hueB]
*/
export declare const interpolateHue: (hueA: number, hueB: number, arc?: HueArc | string) => [number, number];
/**
* resolve length in pixels
* @param value - value
* @param unit - unit
* @param [opt] - options
* @returns pixelated value
*/
export declare const resolveLengthInPixels: (value: number | string, unit: string | undefined, opt?: Options) => number;
/**
* angle to deg
* @param angle - angle
* @returns deg: 0..360
*/
export declare const angleToDeg: (angle: string) => number;
/**
* number to hex string
* @param value - numeric value
* @returns hex string
*/
export declare const numberToHexString: (value: number) => string;
/**
* parse alpha
* @param [alpha] - alpha value
* @returns alpha: 0..1
*/
export declare const parseAlpha: (alpha?: string) => number;
/**
* parse hex alpha
* @param value - alpha value in hex string
* @returns alpha: 0..1
*/
export declare const parseHexAlpha: (value: string) => number;
/**
* cache invalid color value
* @param cacheKey - cache key
* @param format - format
* @param nullable - is nullable
* @returns cached value
*/
export declare const cacheInvalidColorValue: (cacheKey: string, format: string, nullable?: boolean) => SpecifiedColorChannels | string | null;
/**
* resolve invalid color value
* @param format - output format
* @param nullable - is nullable
* @returns resolved value
*/
export declare const resolveInvalidColorValue: (format: string, nullable?: boolean) => SpecifiedColorChannels | string | null;

75
node_modules/@asamuzakjp/css-color/package.json generated vendored Normal file
View File

@ -0,0 +1,75 @@
{
"name": "@asamuzakjp/css-color",
"description": "CSS color - Resolve and convert CSS colors.",
"author": "asamuzaK",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/asamuzaK/cssColor.git"
},
"homepage": "https://github.com/asamuzaK/cssColor#readme",
"bugs": {
"url": "https://github.com/asamuzaK/cssColor/issues"
},
"files": [
"dist",
"src"
],
"type": "module",
"types": "./dist/esm/index.d.ts",
"exports": {
".": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@csstools/css-calc": "^3.4.3",
"@csstools/css-color-parser": "^4.2.6",
"@csstools/css-parser-algorithms": "^4.0.2",
"@csstools/css-tokenizer": "^4.0.2",
"lru-cache": "^11.5.3"
},
"devDependencies": {
"@types/node": "^26.6.5",
"@vitest/coverage-istanbul": "^5.0.3",
"esbuild": "^0.28.2",
"eslint": "^10.12.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-jsdoc": "^65.2.4",
"eslint-plugin-prettier": "^5.5.6",
"eslint-plugin-regexp": "^3.3.1",
"globals": "^17.13.0",
"knip": "^6.41.0",
"mitata": "^1.0.34",
"neostandard": "^0.14.0",
"prettier": "^3.9.10",
"prettier-plugin-brace-style": "^0.10.3",
"publint": "^0.3.25",
"rimraf": "^6.1.3",
"tsx": "^4.23.15",
"typescript": "^6.0.3",
"vite": "^8.3.4",
"vitest": "^5.0.3"
},
"allowScripts": {
"esbuild@0.28.2": true
},
"scripts": {
"bench:color": "npx tsx --expose-gc ./benchmark/bench-color.ts",
"build": "npm run clean && npm run test && npm run knip && vite build && npm run publint",
"clean": "rimraf ./coverage ./dist",
"clone": "node ./scripts/clone-txt.js",
"knip": "knip",
"lint": "eslint . --fix",
"publint": "publint --strict",
"test": "npm run lint && npm run test:types && npm run test:unit",
"test:types": "tsc",
"test:unit": "vitest"
},
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
"version": "7.1.5"
}

View File

@ -0,0 +1,518 @@
/**
* color
*/
import {
transformMatrix,
transformLinearRgbToRgb,
transformXyzD50ToLab,
transformXyzD50ToLch,
transformXyzToHsl,
transformXyzToHwb,
transformXyzToOklab,
transformXyzToOklch
} from '../matrix/transform';
import {
parseColorFunc,
parseColorValue,
parseHsl,
parseHwb,
parseLab,
parseLch,
parseOklab,
parseOklch
} from '../resolvers/parse-color';
import {
resolveColorFunc,
resolveColorValue
} from '../resolvers/resolve-color';
import {
ColorChannels,
ColorChannelsWithPowerless,
ComputedColorChannels,
LinearRgbOptions,
MatchedRegExp,
Options,
StringColorSpacedChannels,
TriColorChannels
} from '../typedef';
import { isString } from '../utils/common';
/* constants */
import { MATRIX_XYZ_TO_L_RGB } from '../matrix/matrix';
import {
FN_COLOR,
MAX_RGB,
NONE,
SYN_FN_COLOR,
SYN_HSL,
SYN_HSL_LV3,
SYN_LCH,
SYN_MOD,
VAL_COMP,
VAL_MIX
} from '../utils/constant';
/* regexp */
const REG_FN_COLOR = new RegExp(`^color\\(\\s*(${SYN_FN_COLOR})\\s*\\)$`);
const REG_HSL = new RegExp(`^hsla?\\(\\s*(${SYN_HSL}|${SYN_HSL_LV3})\\s*\\)$`);
const REG_HWB = new RegExp(`^hwb\\(\\s*(${SYN_HSL})\\s*\\)$`);
const REG_LAB = new RegExp(`^lab\\(\\s*(${SYN_MOD})\\s*\\)$`);
const REG_LCH = new RegExp(`^lch\\(\\s*(${SYN_LCH})\\s*\\)$`);
const REG_OKLAB = new RegExp(`^oklab\\(\\s*(${SYN_MOD})\\s*\\)$`);
const REG_OKLCH = new RegExp(`^oklch\\(\\s*(${SYN_LCH})\\s*\\)$`);
/**
* convert color value to linear rgb
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [r, g, b, alpha] r|g|b|alpha: 0..1
*/
export const convertColorToLinearRgb = (
value: string,
opt: LinearRgbOptions = {}
): ColorChannels | null => {
if (isString(value)) {
value = value.trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { colorSpace = '', format = '' } = opt;
let cs = '';
let r, g, b, alpha, x, y, z;
if (format === VAL_MIX) {
let xyz;
if (value.startsWith(FN_COLOR)) {
xyz = parseColorFunc(value, opt);
} else {
xyz = parseColorValue(value, opt);
}
if (xyz === null) {
return null;
}
[cs, x, y, z, alpha] = xyz as ComputedColorChannels;
if (cs === colorSpace) {
return [x, y, z, alpha];
}
[r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [x, y, z], true);
} else if (value.startsWith(FN_COLOR)) {
const [, val] = value.match(REG_FN_COLOR) as MatchedRegExp;
const [cs] = val.match(/[^\s,/]+/g) as StringColorSpacedChannels;
if (cs === 'srgb-linear') {
[, r, g, b, alpha] = resolveColorFunc(value, {
format: VAL_COMP
}) as ComputedColorChannels;
} else {
[, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels;
[r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [x, y, z], true);
}
} else {
[, x, y, z, alpha] = parseColorValue(value) as ComputedColorChannels;
[r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [x, y, z], true);
}
return [
Math.min(Math.max(r, 0), 1),
Math.min(Math.max(g, 0), 1),
Math.min(Math.max(b, 0), 1),
alpha
];
};
/**
* convert color value to rgb
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1
*/
export const convertColorToRgb = (
value: string,
opt: Options = {}
): ColorChannels | null => {
if (isString(value)) {
value = value.trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { format = '' } = opt;
let r, g, b, alpha;
if (format === VAL_MIX) {
let rgb;
if (value.startsWith(FN_COLOR)) {
rgb = resolveColorFunc(value, opt);
} else {
rgb = resolveColorValue(value, opt);
}
if (rgb === null) {
return null;
}
[, r, g, b, alpha] = rgb as ComputedColorChannels;
} else if (value.startsWith(FN_COLOR)) {
const [, val] = value.match(REG_FN_COLOR) as MatchedRegExp;
const [cs] = val.match(/[^\s,/]+/g) as StringColorSpacedChannels;
if (cs === 'srgb') {
[, r, g, b, alpha] = resolveColorFunc(value, {
format: VAL_COMP
}) as ComputedColorChannels;
r *= MAX_RGB;
g *= MAX_RGB;
b *= MAX_RGB;
} else {
[, r, g, b, alpha] = resolveColorFunc(value) as ComputedColorChannels;
}
} else if (/^(?:ok)?l(?:ab|ch)/.test(value)) {
[r, g, b, alpha] = convertColorToLinearRgb(value) as ColorChannels;
[r, g, b] = transformLinearRgbToRgb([r, g, b]);
} else {
[, r, g, b, alpha] = resolveColorValue(value, {
format: VAL_COMP
}) as ComputedColorChannels;
}
return [r, g, b, alpha];
};
/**
* convert color value to xyz
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [x, y, z, alpha]
*/
export const convertColorToXyz = (
value: string,
opt: Options = {}
): ColorChannels | null => {
if (isString(value)) {
value = value.trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { d50 = false, format = '' } = opt;
let x, y, z, alpha;
if (format === VAL_MIX) {
let xyz;
if (value.startsWith(FN_COLOR)) {
xyz = parseColorFunc(value, opt);
} else {
xyz = parseColorValue(value, opt);
}
if (xyz === null) {
return null;
}
[, x, y, z, alpha] = xyz as ComputedColorChannels;
} else if (value.startsWith(FN_COLOR)) {
const [, val] = value.match(REG_FN_COLOR) as MatchedRegExp;
const [cs] = val.match(/[^\s,/]+/g) as StringColorSpacedChannels;
if (d50) {
if (cs === 'xyz-d50') {
[, x, y, z, alpha] = resolveColorFunc(value, {
format: VAL_COMP
}) as ComputedColorChannels;
} else {
[, x, y, z, alpha] = parseColorFunc(
value,
opt
) as ComputedColorChannels;
}
} else if (/^xyz(?:-d65)?$/.test(cs)) {
[, x, y, z, alpha] = resolveColorFunc(value, {
format: VAL_COMP
}) as ComputedColorChannels;
} else {
[, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels;
}
} else {
[, x, y, z, alpha] = parseColorValue(value, opt) as ComputedColorChannels;
}
return [x, y, z, alpha];
};
/**
* convert color value to hsl
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [h, s, l, alpha], hue may be powerless
*/
export const convertColorToHsl = (
value: string,
opt: Options = {}
): ColorChannels | ColorChannelsWithPowerless | null => {
if (isString(value)) {
value = value.trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { format = '' } = opt;
let h, s, l, alpha;
if (REG_HSL.test(value)) {
[, h, s, l, alpha] = parseHsl(value, {
format: 'hsl'
}) as ComputedColorChannels;
if (format === 'hsl') {
return [Math.round(h), Math.round(s), Math.round(l), alpha];
}
return [h, s, l, alpha];
}
let x, y, z;
if (format === VAL_MIX) {
let xyz;
if (value.startsWith(FN_COLOR)) {
xyz = parseColorFunc(value, opt);
} else {
xyz = parseColorValue(value, opt);
}
if (xyz === null) {
return null;
}
[, x, y, z, alpha] = xyz as ComputedColorChannels;
} else if (value.startsWith(FN_COLOR)) {
[, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels;
} else {
[, x, y, z, alpha] = parseColorValue(value) as ComputedColorChannels;
}
[h, s, l] = transformXyzToHsl([x, y, z], true) as TriColorChannels;
if (format === 'hsl') {
return [Math.round(h), Math.round(s), Math.round(l), alpha];
}
return [format === VAL_MIX && s === 0 ? NONE : h, s, l, alpha];
};
/**
* convert color value to hwb
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [h, w, b, alpha], hue may be powerless
*/
export const convertColorToHwb = (
value: string,
opt: Options = {}
): ColorChannels | [number | string, number, number, number] | null => {
if (isString(value)) {
value = value.trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { format = '' } = opt;
let h, w, b, alpha;
if (REG_HWB.test(value)) {
[, h, w, b, alpha] = parseHwb(value, {
format: 'hwb'
}) as ComputedColorChannels;
if (format === 'hwb') {
return [Math.round(h), Math.round(w), Math.round(b), alpha];
}
return [h, w, b, alpha];
}
let x, y, z;
if (format === VAL_MIX) {
let xyz;
if (value.startsWith(FN_COLOR)) {
xyz = parseColorFunc(value, opt);
} else {
xyz = parseColorValue(value, opt);
}
if (xyz === null) {
return null;
}
[, x, y, z, alpha] = xyz as ComputedColorChannels;
} else if (value.startsWith(FN_COLOR)) {
[, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels;
} else {
[, x, y, z, alpha] = parseColorValue(value) as ComputedColorChannels;
}
[h, w, b] = transformXyzToHwb([x, y, z], true) as TriColorChannels;
if (format === 'hwb') {
return [Math.round(h), Math.round(w), Math.round(b), alpha];
}
return [format === VAL_MIX && w + b >= 100 ? NONE : h, w, b, alpha];
};
/**
* convert color value to lab
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [l, a, b, alpha]
*/
export const convertColorToLab = (
value: string,
opt: Options = {}
): ColorChannels | null => {
if (isString(value)) {
value = value.trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { format = '' } = opt;
let l, a, b, alpha;
if (REG_LAB.test(value)) {
[, l, a, b, alpha] = parseLab(value, {
format: VAL_COMP
}) as ComputedColorChannels;
return [l, a, b, alpha];
}
let x, y, z;
if (format === VAL_MIX) {
let xyz;
const options = {
...opt,
d50: true
};
if (value.startsWith(FN_COLOR)) {
xyz = parseColorFunc(value, options);
} else {
xyz = parseColorValue(value, options);
}
if (xyz === null) {
return null;
}
[, x, y, z, alpha] = xyz as ComputedColorChannels;
} else if (value.startsWith(FN_COLOR)) {
[, x, y, z, alpha] = parseColorFunc(value, {
d50: true
}) as ComputedColorChannels;
} else {
[, x, y, z, alpha] = parseColorValue(value, {
d50: true
}) as ComputedColorChannels;
}
[l, a, b] = transformXyzD50ToLab([x, y, z], true);
return [l, a, b, alpha];
};
/**
* convert color value to lch
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [l, c, h, alpha], hue may be powerless
*/
export const convertColorToLch = (
value: string,
opt: Options = {}
): ColorChannels | [number, number, number | string, number] | null => {
if (isString(value)) {
value = value.trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { format = '' } = opt;
let l, c, h, alpha;
if (REG_LCH.test(value)) {
[, l, c, h, alpha] = parseLch(value, {
format: VAL_COMP
}) as ComputedColorChannels;
return [l, c, h, alpha];
}
let x, y, z;
if (format === VAL_MIX) {
let xyz;
const options = {
...opt,
d50: true
};
if (value.startsWith(FN_COLOR)) {
xyz = parseColorFunc(value, options);
} else {
xyz = parseColorValue(value, options);
}
if (xyz === null) {
return null;
}
[, x, y, z, alpha] = xyz as ComputedColorChannels;
} else if (value.startsWith(FN_COLOR)) {
[, x, y, z, alpha] = parseColorFunc(value, {
d50: true
}) as ComputedColorChannels;
} else {
[, x, y, z, alpha] = parseColorValue(value, {
d50: true
}) as ComputedColorChannels;
}
[l, c, h] = transformXyzD50ToLch([x, y, z], true);
return [l, c, format === VAL_MIX && c === 0 ? NONE : h, alpha];
};
/**
* convert color value to oklab
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [l, a, b, alpha]
*/
export const convertColorToOklab = (
value: string,
opt: Options = {}
): ColorChannels | null => {
if (isString(value)) {
value = value.trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { format = '' } = opt;
let l, a, b, alpha;
if (REG_OKLAB.test(value)) {
[, l, a, b, alpha] = parseOklab(value, {
format: VAL_COMP
}) as ComputedColorChannels;
return [l, a, b, alpha];
}
let x, y, z;
if (format === VAL_MIX) {
let xyz;
if (value.startsWith(FN_COLOR)) {
xyz = parseColorFunc(value, opt);
} else {
xyz = parseColorValue(value, opt);
}
if (xyz === null) {
return null;
}
[, x, y, z, alpha] = xyz as ComputedColorChannels;
} else if (value.startsWith(FN_COLOR)) {
[, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels;
} else {
[, x, y, z, alpha] = parseColorValue(value) as ComputedColorChannels;
}
[l, a, b] = transformXyzToOklab([x, y, z], true);
return [l, a, b, alpha];
};
/**
* convert color value to oklch
* @param value - CSS color value
* @param opt - options
* @returns ColorChannels | null - [l, c, h, alpha], hue may be powerless
*/
export const convertColorToOklch = (
value: string,
opt: Options = {}
): ColorChannels | [number, number, number | string, number] | null => {
if (isString(value)) {
value = value.trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { format = '' } = opt;
let l, c, h, alpha;
if (REG_OKLCH.test(value)) {
[, l, c, h, alpha] = parseOklch(value, {
format: VAL_COMP
}) as ComputedColorChannels;
return [l, c, h, alpha];
}
let x, y, z;
if (format === VAL_MIX) {
let xyz;
if (value.startsWith(FN_COLOR)) {
xyz = parseColorFunc(value, opt);
} else {
xyz = parseColorValue(value, opt);
}
if (xyz === null) {
return null;
}
[, x, y, z, alpha] = xyz as ComputedColorChannels;
} else if (value.startsWith(FN_COLOR)) {
[, x, y, z, alpha] = parseColorFunc(value) as ComputedColorChannels;
} else {
[, x, y, z, alpha] = parseColorValue(value) as ComputedColorChannels;
}
[l, c, h] = transformXyzToOklch([x, y, z], true) as TriColorChannels;
return [l, c, format === VAL_MIX && c === 0 ? NONE : h, alpha];
};

View File

@ -0,0 +1,187 @@
/**
* convert-hex
*/
import {
transformMatrix,
validateColorComponents,
transformLinearRgbToRgb,
transformRgbToLinearRgb
} from '../matrix/transform';
import { ColorChannels, MatchedRegExp3, MatchedRegExp4 } from '../typedef';
import { isString } from '../utils/common';
import { numberToHexString, parseHexAlpha } from '../utils/util';
/* constants */
import {
MATRIX_D50_TO_D65,
MATRIX_L_RGB_TO_XYZ,
MATRIX_XYZ_TO_L_RGB
} from '../matrix/matrix';
import { HEX, QUAD, MAX_RGB } from '../utils/constant';
/**
* convert rgb to hex color
* @param rgb - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1
* @returns hex color
*/
export const convertRgbToHex = (rgb: ColorChannels): string => {
const [r, g, b, alpha] = validateColorComponents(rgb, {
alpha: true,
maxRange: MAX_RGB
}) as ColorChannels;
const rr = numberToHexString(r);
const gg = numberToHexString(g);
const bb = numberToHexString(b);
const aa = numberToHexString(alpha * MAX_RGB);
return aa === 'ff' ? `#${rr}${gg}${bb}` : `#${rr}${gg}${bb}${aa}`;
};
/**
* convert linear rgb to hex color
* @param rgb - [r, g, b, alpha] r|g|b|alpha: 0..1
* @param [skip] - skip validate
* @returns hex color
*/
export const convertLinearRgbToHex = (
rgb: ColorChannels,
skip: boolean = false
): string => {
let r: number, g: number, b: number, alpha: number;
if (skip) {
[r, g, b, alpha] = rgb;
} else {
[r, g, b, alpha] = validateColorComponents(rgb, {
minLength: QUAD
}) as ColorChannels;
}
[r, g, b] = transformLinearRgbToRgb([r, g, b], true);
const rr = numberToHexString(r);
const gg = numberToHexString(g);
const bb = numberToHexString(b);
const aa = numberToHexString(alpha * MAX_RGB);
return aa === 'ff' ? `#${rr}${gg}${bb}` : `#${rr}${gg}${bb}${aa}`;
};
/**
* convert xyz to hex color
* @param xyz - [x, y, z, alpha]
* @returns hex color
*/
export const convertXyzToHex = (xyz: ColorChannels): string => {
const [x, y, z, alpha] = validateColorComponents(xyz, {
minLength: QUAD,
validateRange: false
}) as ColorChannels;
const [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [x, y, z], true);
return convertLinearRgbToHex(
[
Math.min(Math.max(r, 0), 1),
Math.min(Math.max(g, 0), 1),
Math.min(Math.max(b, 0), 1),
alpha
],
true
);
};
/**
* convert xyz D50 to hex color
* @param xyz - [x, y, z, alpha]
* @returns hex color
*/
export const convertXyzD50ToHex = (xyz: ColorChannels): string => {
const [x, y, z, alpha] = validateColorComponents(xyz, {
minLength: QUAD,
validateRange: false
}) as ColorChannels;
const xyzD65 = transformMatrix(MATRIX_D50_TO_D65, [x, y, z], true);
const [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, xyzD65, true);
return convertLinearRgbToHex([
Math.min(Math.max(r, 0), 1),
Math.min(Math.max(g, 0), 1),
Math.min(Math.max(b, 0), 1),
alpha
]);
};
/**
* convert hex color to rgb
* @param value - hex color value
* @returns ColorChannels - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1
*/
export const convertHexToRgb = (value: string): ColorChannels => {
if (isString(value)) {
value = value.toLowerCase().trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
if (!(
/^#[\da-f]{6}$/.test(value) ||
/^#[\da-f]{3}$/.test(value) ||
/^#[\da-f]{8}$/.test(value) ||
/^#[\da-f]{4}$/.test(value)
)) {
throw new SyntaxError(`Invalid property value: ${value}`);
}
const arr: number[] = [];
if (/^#[\da-f]{3}$/.test(value)) {
const [, r, g, b] = value.match(
/^#([\da-f])([\da-f])([\da-f])$/
) as MatchedRegExp3;
arr.push(
parseInt(`${r}${r}`, HEX),
parseInt(`${g}${g}`, HEX),
parseInt(`${b}${b}`, HEX),
1
);
} else if (/^#[\da-f]{4}$/.test(value)) {
const [, r, g, b, alpha] = value.match(
/^#([\da-f])([\da-f])([\da-f])([\da-f])$/
) as MatchedRegExp4;
arr.push(
parseInt(`${r}${r}`, HEX),
parseInt(`${g}${g}`, HEX),
parseInt(`${b}${b}`, HEX),
parseHexAlpha(`${alpha}${alpha}`)
);
} else if (/^#[\da-f]{8}$/.test(value)) {
const [, r, g, b, alpha] = value.match(
/^#([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})$/
) as MatchedRegExp4;
arr.push(
parseInt(r, HEX),
parseInt(g, HEX),
parseInt(b, HEX),
parseHexAlpha(alpha)
);
} else {
const [, r, g, b] = value.match(
/^#([\da-f]{2})([\da-f]{2})([\da-f]{2})$/
) as MatchedRegExp3;
arr.push(parseInt(r, HEX), parseInt(g, HEX), parseInt(b, HEX), 1);
}
return arr as ColorChannels;
};
/**
* convert hex color to linear rgb
* @param value - hex color value
* @returns ColorChannels - [r, g, b, alpha] r|g|b|alpha: 0..1
*/
export const convertHexToLinearRgb = (value: string): ColorChannels => {
const [rr, gg, bb, alpha] = convertHexToRgb(value);
const [r, g, b] = transformRgbToLinearRgb([rr, gg, bb], true);
return [r, g, b, alpha];
};
/**
* convert hex color to xyz
* @param value - hex color value
* @returns ColorChannels - [x, y, z, alpha]
*/
export const convertHexToXyz = (value: string): ColorChannels => {
const [r, g, b, alpha] = convertHexToLinearRgb(value);
const [x, y, z] = transformMatrix(MATRIX_L_RGB_TO_XYZ, [r, g, b], true);
return [x, y, z, alpha];
};

View File

@ -0,0 +1,338 @@
/**
* convert
*/
import { parseColorFunc, parseColorValue } from '../resolvers/parse-color';
import { resolveRelativeColor } from '../resolvers/relative-color';
import { resolveColor } from '../resolvers/resolve-color';
import {
ColorChannels,
ColorConvertFn,
ComputedColorChannels,
Options
} from '../typedef';
import { createCacheKey, getCache, setCache } from '../utils/cache';
import { isString } from '../utils/common';
import { cssCalc, resolveVar } from '../utils/css-calc-var';
import { getMaxLength, numberToHexString } from '../utils/util';
import {
convertColorToHsl,
convertColorToHwb,
convertColorToLab,
convertColorToLch,
convertColorToOklab,
convertColorToOklch,
convertColorToRgb
} from './convert-color';
/* constants */
import {
SYN_FN_CALC,
SYN_FN_REL,
SYN_FN_VAR,
VAL_COMP
} from '../utils/constant';
const NAMESPACE = 'convert';
/* regexp */
const REG_FN_CALC = new RegExp(SYN_FN_CALC);
const REG_FN_REL = new RegExp(SYN_FN_REL);
const REG_FN_VAR = new RegExp(SYN_FN_VAR);
/**
* pre process
* @param value - CSS color value
* @param opt - options
* @returns value
*/
export const preProcess = (value: string, opt: Options): string | null => {
if (!isString(value)) {
return null;
}
value = value.trim();
const maxLength = getMaxLength(opt);
if (!value || value.length > maxLength) {
return null;
}
const cacheKey: string = createCacheKey(
{ namespace: NAMESPACE, name: 'preProcess', value },
opt
);
const cachedResult = getCache(cacheKey);
if (cachedResult !== false) {
return cachedResult.item as string | null;
}
let res: string | null = value;
if (REG_FN_VAR.test(value)) {
const resolved = resolveVar(value, opt);
if (isString(resolved)) {
res = resolved;
} else {
setCache(cacheKey, null);
return null;
}
}
if (REG_FN_REL.test(res)) {
const resolved = resolveRelativeColor(res, opt);
if (isString(resolved)) {
res = resolved;
} else {
setCache(cacheKey, null);
return null;
}
} else if (REG_FN_CALC.test(res)) {
res = cssCalc(res, opt);
}
if (res.startsWith('color-mix')) {
const resolvedColorMix = resolveColor(res, {
...opt,
format: VAL_COMP,
nullable: true
});
res = typeof resolvedColorMix === 'string' ? resolvedColorMix : null;
}
if (!res || res.length > maxLength) {
setCache(cacheKey, null);
return null;
}
setCache(cacheKey, res);
return res;
};
/**
* converter factory to reduce boilerplate
* @param name - function name for cache
* @param format - color format
* @param convertFn - conversion function
* @returns color converter function
*/
const createColorConverter = (
name: string,
format: string,
convertFn: ColorConvertFn
) => {
return (value: string, opt: Options = {}): ColorChannels => {
if (!isString(value)) {
throw new TypeError(`${value} is not a string.`);
}
const options = {
...opt
};
const resolved = preProcess(value, options);
if (resolved === null) {
return [0, 0, 0, 0];
}
const val = resolved.toLowerCase();
const cacheKey = createCacheKey(
{ namespace: NAMESPACE, name, value: val },
options
);
const cached = getCache(cacheKey);
if (cached !== false) {
return [...(cached.item as ColorChannels)] as ColorChannels;
}
const result = convertFn(val, { ...options, format }) as ColorChannels;
setCache(cacheKey, result);
return [...result];
};
};
/**
* convert number to hex string
* @param value - numeric value
* @returns hex string: 00..ff
*/
export const numberToHex = (value: number): string => numberToHexString(value);
/**
* convert color to hex
* @param value - CSS color value
* @param [opt] - options
* @param [opt.alpha] - enable alpha channel
* @returns #rrggbb | #rrggbbaa | null
*/
export const colorToHex = (value: string, opt: Options = {}): string | null => {
if (!isString(value)) {
throw new TypeError(`${value} is not a string.`);
}
const options = {
...opt
};
const resolved = preProcess(value, options);
if (resolved === null) {
return null;
}
const val = resolved.toLowerCase();
const cacheKey = createCacheKey(
{ namespace: NAMESPACE, name: 'colorToHex', value: val },
options
);
const cached = getCache(cacheKey);
if (cached !== false) {
return cached.item as string | null;
}
const hex = resolveColor(val, {
...options,
nullable: true,
format: options.alpha ? 'hexAlpha' : 'hex'
});
if (isString(hex)) {
setCache(cacheKey, hex);
return hex;
}
setCache(cacheKey, null);
return null;
};
/**
* convert color to hsl
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [h, s, l, alpha]
*/
export const colorToHsl = createColorConverter(
'colorToHsl',
'hsl',
convertColorToHsl
);
/**
* convert color to hwb
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [h, w, b, alpha]
*/
export const colorToHwb = createColorConverter(
'colorToHwb',
'hwb',
convertColorToHwb
);
/**
* convert color to lab
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [l, a, b, alpha]
*/
export const colorToLab = createColorConverter(
'colorToLab',
'lab',
convertColorToLab
);
/**
* convert color to lch
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [l, c, h, alpha]
*/
export const colorToLch = createColorConverter(
'colorToLch',
'lch',
convertColorToLch
);
/**
* convert color to oklab
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [l, a, b, alpha]
*/
export const colorToOklab = createColorConverter(
'colorToOklab',
'oklab',
convertColorToOklab
);
/**
* convert color to oklch
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [l, c, h, alpha]
*/
export const colorToOklch = createColorConverter(
'colorToOklch',
'oklch',
convertColorToOklch
);
/**
* convert color to rgb
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [r, g, b, alpha]
*/
export const colorToRgb = createColorConverter(
'colorToRgb',
'rgb',
convertColorToRgb
);
/**
* convert color to xyz
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [x, y, z, alpha]
*/
export const colorToXyz = (value: string, opt: Options = {}): ColorChannels => {
if (!isString(value)) {
throw new TypeError(`${value} is not a string.`);
}
const options = {
...opt
};
const resolved = preProcess(value, options);
if (resolved === null) {
return [0, 0, 0, 0];
}
const val = resolved.toLowerCase();
const cacheKey = createCacheKey(
{ namespace: NAMESPACE, name: 'colorToXyz', value: val },
options
);
const cached = getCache(cacheKey);
if (cached !== false) {
return [...(cached.item as ColorChannels)] as ColorChannels;
}
let parsed;
if (val.startsWith('color(')) {
parsed = parseColorFunc(val, options);
} else {
parsed = parseColorValue(val, options);
}
const [, ...xyz] = parsed as ComputedColorChannels;
setCache(cacheKey, xyz);
return [...xyz] as ColorChannels;
};
/**
* convert color to xyz-d50
* @param value - CSS color value
* @param [opt] - options
* @returns ColorChannels - [x, y, z, alpha]
*/
export const colorToXyzD50 = (
value: string,
opt: Options = {}
): ColorChannels => {
const options = {
...opt,
d50: true
};
return colorToXyz(value, options);
};
/* convert */
export const convert = {
colorToHex,
colorToHsl,
colorToHwb,
colorToLab,
colorToLch,
colorToOklab,
colorToOklch,
colorToRgb,
colorToXyz,
colorToXyzD50,
numberToHex
};

View File

@ -0,0 +1,325 @@
/**
* gradient-util
*/
import {
isCommentNode,
isWhitespaceNode,
parseListOfComponentValues
} from '@csstools/css-parser-algorithms';
import { TokenType, tokenize } from '@csstools/css-tokenizer';
import { isValidColor, resolveColor } from '../resolvers/resolve-color';
import { Options, ValidateGradientLine, ValidateColorStops } from '../typedef';
import { isString } from '../utils/common';
import { cssCalc } from '../utils/css-calc-var';
import { isLengthPercentageCalculation } from '../utils/length-percentage';
import { splitValue } from '../utils/util';
/* constants */
import {
ANGLE,
CS_HUE,
CS_RECT,
LENGTH,
NUM,
NUM_POSITIVE,
PCT,
VAL_SPEC
} from '../utils/constant';
const { Function: FUNC } = TokenType;
const DIM_ANGLE = `${NUM}(?:${ANGLE})`;
const DIM_ANGLE_PCT = `${DIM_ANGLE}|${PCT}`;
const DIM_LEN = `${NUM}(?:${LENGTH})|0`;
const DIM_LEN_PCT = `${DIM_LEN}|${PCT}`;
const DIM_LEN_PCT_POSI = `${NUM_POSITIVE}(?:${LENGTH}|%)|0`;
const DIM_LEN_POSI = `${NUM_POSITIVE}(?:${LENGTH})|0`;
const CTR = 'center';
const L_R = 'left|right';
const T_B = 'top|bottom';
const S_E = 'start|end';
const AXIS_X = `${L_R}|x-(?:${S_E})`;
const AXIS_Y = `${T_B}|y-(?:${S_E})`;
const BLOCK = `block-(?:${S_E})`;
const INLINE = `inline-(?:${S_E})`;
const POS_1 = `${CTR}|${AXIS_X}|${AXIS_Y}|${BLOCK}|${INLINE}|${DIM_LEN_PCT}`;
const POS_2 = [
`(?:${CTR}|${AXIS_X})\\s+(?:${CTR}|${AXIS_Y})`,
`(?:${CTR}|${AXIS_Y})\\s+(?:${CTR}|${AXIS_X})`,
`(?:${CTR}|${AXIS_X}|${DIM_LEN_PCT})\\s+(?:${CTR}|${AXIS_Y}|${DIM_LEN_PCT})`,
`(?:${CTR}|${BLOCK})\\s+(?:${CTR}|${INLINE})`,
`(?:${CTR}|${INLINE})\\s+(?:${CTR}|${BLOCK})`,
`(?:${CTR}|${S_E})\\s+(?:${CTR}|${S_E})`
].join('|');
const POS_4 = [
`(?:${AXIS_X})\\s+(?:${DIM_LEN_PCT})\\s+(?:${AXIS_Y})\\s+(?:${DIM_LEN_PCT})`,
`(?:${AXIS_Y})\\s+(?:${DIM_LEN_PCT})\\s+(?:${AXIS_X})\\s+(?:${DIM_LEN_PCT})`,
`(?:${BLOCK})\\s+(?:${DIM_LEN_PCT})\\s+(?:${AXIS_Y})\\s+(?:${DIM_LEN_PCT})`,
`(?:${INLINE})\\s+(?:${DIM_LEN_PCT})\\s+(?:${BLOCK})\\s+(?:${DIM_LEN_PCT})`,
`(?:${S_E})\\s+(?:${DIM_LEN_PCT})\\s+(?:${S_E})\\s+(?:${DIM_LEN_PCT})`
].join('|');
const RAD_EXTENT = '(?:clos|farth)est-(?:corner|side)';
const RAD_SIZE = [
`${RAD_EXTENT}(?:\\s+${RAD_EXTENT})?`,
`${DIM_LEN_POSI}`,
`(?:${DIM_LEN_PCT_POSI})\\s+(?:${DIM_LEN_PCT_POSI})`
].join('|');
const RAD_SHAPE = 'circle|ellipse';
const FROM_ANGLE = `from\\s+${DIM_ANGLE}`;
const AT_POSITION = `at\\s+(?:${POS_1}|${POS_2}|${POS_4})`;
const TO_SIDE_CORNER = `to\\s+(?:(?:${L_R})(?:\\s(?:${T_B}))?|(?:${T_B})(?:\\s(?:${L_R}))?)`;
const IN_COLOR_SPACE = `in\\s+(?:${CS_RECT}|${CS_HUE})`;
const LINE_SYNTAX_LINEAR = [
`(?:${DIM_ANGLE}|${TO_SIDE_CORNER})(?:\\s+${IN_COLOR_SPACE})?`,
`${IN_COLOR_SPACE}(?:\\s+(?:${DIM_ANGLE}|${TO_SIDE_CORNER}))?`
].join('|');
const LINE_SYNTAX_RADIAL = [
`(?:${RAD_SHAPE})(?:\\s+(?:${RAD_SIZE}))?(?:\\s+${AT_POSITION})?(?:\\s+${IN_COLOR_SPACE})?`,
`(?:${RAD_SIZE})(?:\\s+(?:${RAD_SHAPE}))?(?:\\s+${AT_POSITION})?(?:\\s+${IN_COLOR_SPACE})?`,
`${AT_POSITION}(?:\\s+${IN_COLOR_SPACE})?`,
`${IN_COLOR_SPACE}(?:\\s+${RAD_SHAPE})(?:\\s+(?:${RAD_SIZE}))?(?:\\s+${AT_POSITION})?`,
`${IN_COLOR_SPACE}(?:\\s+${RAD_SIZE})(?:\\s+(?:${RAD_SHAPE}))?(?:\\s+${AT_POSITION})?`,
`${IN_COLOR_SPACE}(?:\\s+${AT_POSITION})?`
].join('|');
const LINE_SYNTAX_CONIC = [
`${FROM_ANGLE}(?:\\s+${AT_POSITION})?(?:\\s+${IN_COLOR_SPACE})?`,
`${AT_POSITION}(?:\\s+${IN_COLOR_SPACE})?`,
`${IN_COLOR_SPACE}(?:\\s+${FROM_ANGLE})?(?:\\s+${AT_POSITION})?`
].join('|');
const DEFAULT_RADIAL = [/ellipse/, /farthest-corner/, /at\s+center/];
const DEFAULT_CONIC = [/at\s+center/];
const COLOR_OPT = {
format: VAL_SPEC,
nullable: true
};
/* regexp */
const IS_CONIC = /^(?:repeating-)?conic-gradient$/;
const IS_LINEAR = /^(?:repeating-)?linear-gradient$/;
const IS_RADIAL = /^(?:repeating-)?radial-gradient$/;
const IS_GRADIENT_FN = /^(?:repeating-)?(?:conic|linear|radial)-gradient$/i;
const REG_COLOR_HINT_CONIC = new RegExp(`^(?:${DIM_ANGLE_PCT})$`);
const REG_COLOR_HINT_NON_CONIC = new RegExp(`^(?:${DIM_LEN_PCT})$`);
const REG_LINE_CONIC = new RegExp(`^(?:${LINE_SYNTAX_CONIC})$`);
const REG_LINE_LINEAR = new RegExp(`^(?:${LINE_SYNTAX_LINEAR})$`);
const REG_LINE_RADIAL = new RegExp(`^(?:${LINE_SYNTAX_RADIAL})$`);
const REG_TO_BOTTOM = /^to\s+bottom$/i;
/**
* get gradient type
* @param value - gradient value
* @returns gradient type
*/
export const getGradientType = (value: string): string => {
if (isString(value)) {
const trimmed = value.trim();
if (trimmed) {
const tokens = tokenize({ css: trimmed });
const [firstToken] = tokens;
if (firstToken && firstToken[0] === FUNC) {
const fnName = firstToken[1].slice(0, -1).toLowerCase();
if (IS_GRADIENT_FN.test(fnName)) {
return fnName;
}
}
}
}
return '';
};
/**
* validate linear-gradient line
* @param value - line value
* @returns result
*/
export const validateLinearGradientLine = (
value: string
): ValidateGradientLine => {
const valid = REG_LINE_LINEAR.test(value);
if (!valid) {
return { line: value, valid: false };
}
const normalized = value.replace(/\s+/g, ' ').trim();
if (REG_TO_BOTTOM.test(normalized)) {
return { line: '', valid: true };
}
const line = normalized
.replace(/^to\sbottom\s/i, '')
.replace(/\sto\sbottom$/i, '')
.trim();
return { line, valid: true };
};
/**
* validate radial-gradient line
* @param value - line value
* @returns result
*/
export const validateRadialGradientLine = (
value: string
): ValidateGradientLine => {
const valid = REG_LINE_RADIAL.test(value);
if (!valid) {
return { line: value, valid: false };
}
let line = value;
for (const defaultValue of DEFAULT_RADIAL) {
line = line.replace(defaultValue, '');
}
line = line.replace(/\s{2,}/g, ' ').trim();
return { line, valid: true };
};
/**
* validate conic-gradient line
* @param value - line value
* @returns result
*/
export const validateConicGradientLine = (
value: string
): ValidateGradientLine => {
const valid = REG_LINE_CONIC.test(value);
if (!valid) {
return { line: value, valid: false };
}
let line = value;
for (const defaultValue of DEFAULT_CONIC) {
line = line.replace(defaultValue, '');
}
line = line.replace(/\s{2,}/g, ' ').trim();
return { line, valid: true };
};
/**
* validate gradient line
* @param value - gradient line value
* @param type - gradient type
* @returns result
*/
export const validateGradientLine = (
value: string,
type: string
): ValidateGradientLine => {
if (isString(value) && isString(type)) {
const trimmedValue = value.trim();
const trimmedType = type.trim();
if (IS_LINEAR.test(trimmedType)) {
return validateLinearGradientLine(trimmedValue);
}
if (IS_RADIAL.test(trimmedType)) {
return validateRadialGradientLine(trimmedValue);
}
if (IS_CONIC.test(trimmedType)) {
return validateConicGradientLine(trimmedValue);
}
}
return { line: value, valid: false };
};
/**
* Split a color stop into its original component values.
* @param value - color stop or transition hint
* @returns color and position components, retaining comments inside functions
*/
export const splitColorStop = (value: string): string[] => {
const components = parseListOfComponentValues(tokenize({ css: value }));
const parts: string[] = [];
for (const component of components) {
if (!isCommentNode(component) && !isWhitespaceNode(component)) {
parts.push(component.toString());
}
}
return parts;
};
/**
* Validate a position in a gradient color stop or transition hint.
* @param value - original position component
* @param isConic - whether the gradient uses angle-percentage positions
* @returns whether the position is valid in this gradient context
*/
export const isValidPosition = (value: string, isConic: boolean): boolean => {
const regColorHint = isConic
? REG_COLOR_HINT_CONIC
: REG_COLOR_HINT_NON_CONIC;
return (
regColorHint.test(value) ||
(!isConic && isLengthPercentageCalculation(value))
);
};
/**
* validate color stop list
* @param list - color stop list
* @param type - gradient type
* @param [opt] - options
* @returns validated result
*/
export const validateColorStopList = (
list: string[],
type: string,
opt: Options = {}
): ValidateColorStops => {
if (Array.isArray(list) && list.length > 1) {
const isConic = IS_CONIC.test(type);
const valueList: string[] = [];
// State tracker: 'color' or 'hint'
let prevType = '';
// for (let i = 0; i < list.length; i++) から entries() に変更
for (const [i, item] of list.entries()) {
if (!isString(item)) {
return { colorStops: list, valid: false };
}
const parts = splitColorStop(item);
const [firstPart, ...posParts] = parts;
if (!firstPart || parts.length > 3) {
return { colorStops: list, valid: false };
}
if (parts.length === 1 && isValidPosition(firstPart, isConic)) {
// Color hint
if (i === 0 || prevType === 'hint') {
return { colorStops: list, valid: false };
}
prevType = 'hint';
// Resolve calc() expressions and clean up comments
const resolvedHint = isLengthPercentageCalculation(firstPart)
? cssCalc(firstPart, opt)
: firstPart;
valueList.push(resolvedHint);
} else {
// Color stop (1 color + 0 to 2 stop positions)
const resolvedPosParts: string[] = [];
for (const position of posParts) {
if (!isValidPosition(position, isConic)) {
return { colorStops: list, valid: false };
}
// Resolve calc() expressions and clean up comments
const resolvedPosition = isLengthPercentageCalculation(position)
? cssCalc(position, opt)
: position;
resolvedPosParts.push(resolvedPosition);
}
const color = splitValue(firstPart).join(' ');
if (isValidColor(color, COLOR_OPT)) {
const resolvedColor = resolveColor(color, opt);
if (!resolvedColor || !isValidColor(resolvedColor, COLOR_OPT)) {
return { colorStops: list, valid: false };
}
prevType = 'color';
const resolvedItem =
resolvedPosParts.length > 0
? `${resolvedColor} ${resolvedPosParts.join(' ')}`
: resolvedColor;
valueList.push(resolvedItem);
} else {
return { colorStops: list, valid: false };
}
}
}
// The last item must be a color, not a hint
if (prevType !== 'color') {
return { colorStops: list, valid: false };
}
return { valid: true, colorStops: valueList };
}
return { colorStops: list, valid: false };
};

View File

@ -0,0 +1,47 @@
/**
* gradient
*/
import { Options } from '../typedef';
import { getMaxLength } from '../utils/util';
import { parseGradient } from './parse-gradient';
/* constants */
import { VAL_SPEC } from '../utils/constant';
/**
* resolve CSS gradient
* @param value - CSS value
* @param [opt] - options
* @returns result
*/
export const resolveGradient = (value: string, opt: Options = {}): string => {
const options = {
...opt
};
const maxLength = getMaxLength(options);
if (value && value.length <= maxLength) {
const gradient = parseGradient(value, options);
if (gradient) {
const { type, gradientLine, colorStopList } = gradient;
if (gradientLine) {
return `${type}(${gradientLine}, ${colorStopList.join(', ')})`;
}
return `${type}(${colorStopList.join(', ')})`;
}
}
return options.format === VAL_SPEC ? '' : 'none';
};
/**
* is CSS gradient
* @param value - CSS value
* @param [opt] - options
* @returns result
*/
export const isGradient = (value: string, opt: Options = {}): boolean => {
const options = {
...opt
};
return !!parseGradient(value, options);
};

View File

@ -0,0 +1,98 @@
/**
* gradient
*/
import { isValidColor } from '../resolvers/resolve-color';
import { ColorStopList, Gradient, GradientType, Options } from '../typedef';
import { createCacheKey, getCache, setCache } from '../utils/cache';
import { isString } from '../utils/common';
import { splitValue } from '../utils/util';
import {
getGradientType,
splitColorStop,
validateColorStopList,
validateGradientLine
} from './gradient-util';
/* constants */
import { VAL_SPEC } from '../utils/constant';
const NAMESPACE = 'gradient';
const COLOR_OPT = {
format: VAL_SPEC,
nullable: true
};
/* regexp */
const REG_GRAD = /^(?:repeating-)?(?:conic|linear|radial)-gradient\(/;
/**
* parse CSS gradient
* @param value - gradient value
* @param [opt] - options
* @returns parsed result
*/
export const parseGradient = (
value: string,
opt: Options = {}
): Gradient | null => {
if (!isString(value)) {
return null;
}
const trimmedValue = value.trim();
const cacheKey: string = createCacheKey(
{ namespace: NAMESPACE, name: 'parseGradient', value: trimmedValue },
opt
);
const cachedResult = getCache(cacheKey);
if (cachedResult !== false) {
return cachedResult.item as Gradient | null;
}
const type = getGradientType(trimmedValue);
const gradValue = trimmedValue.replace(REG_GRAD, '').replace(/\)$/, '');
if (type && gradValue) {
const [lineOrColorStop, ...itemList] = splitValue(gradValue, {
delimiter: ',',
preserveComment: true
});
if (!lineOrColorStop) {
setCache(cacheKey, null);
return null;
}
const [firstPart] = splitColorStop(lineOrColorStop);
if (firstPart && isValidColor(splitValue(firstPart).join(' '), COLOR_OPT)) {
itemList.unshift(lineOrColorStop);
const { colorStops, valid } = validateColorStopList(itemList, type, opt);
if (valid) {
const res: Gradient = {
value: trimmedValue,
type: type as GradientType,
colorStopList: colorStops as ColorStopList
};
setCache(cacheKey, res);
return res;
}
} else if (itemList.length > 1) {
const { line: gradientLine, valid: validLine } = validateGradientLine(
splitValue(lineOrColorStop).join(' '),
type
);
const { colorStops, valid: validColorStops } = validateColorStopList(
itemList,
type,
opt
);
if (validLine && validColorStops) {
const res: Gradient = {
value: trimmedValue,
type: type as GradientType,
gradientLine,
colorStopList: colorStops as ColorStopList
};
setCache(cacheKey, res);
return res;
}
}
}
setCache(cacheKey, null);
return null;
};

34
node_modules/@asamuzakjp/css-color/src/index.ts generated vendored Normal file
View File

@ -0,0 +1,34 @@
/*!
* CSS color - Resolve, parse, convert CSS color.
* @license MIT
* @copyright asamuzaK (Kazz)
* @see {@link https://github.com/asamuzaK/cssColor/blob/main/LICENSE}
*/
import { isGradient, resolveGradient } from './gradients/gradient';
import { isColor } from './resolvers/resolve';
import { cssCalc, cssVar } from './utils/css-calc-var';
import {
extractDashedIdent,
resolveLengthInPixels,
splitValue
} from './utils/util';
export { convert } from './converters/convert';
export { resolveGradient } from './gradients/gradient';
export { resolve } from './resolvers/resolve';
/* utils */
export const utils = {
cssCalc,
cssVar,
extractDashedIdent,
isColor,
isGradient,
/**
* @deprecated Use `resolveGradient` directly instead.
*/
resolveGradient,
resolveLengthInPixels,
splitValue
};

View File

@ -0,0 +1,87 @@
/**
* matrix
*/
import { ReadonlyColorMatrix, ReadonlyTriColorChannels } from '../typedef';
/**
* conversion matrices
* @see https://drafts.csswg.org/css-color-4/#color-conversion-code
*/
export const D50: ReadonlyTriColorChannels = [
0.3457 / 0.3585,
1.0,
(1.0 - 0.3457 - 0.3585) / 0.3585
] as const;
export const MATRIX_D50_TO_D65: ReadonlyColorMatrix = [
[0.955473421488075, -0.02309845494876471, 0.06325924320057072],
[-0.0283697093338637, 1.0099953980813041, 0.021041441191917323],
[0.012314014864481998, -0.020507649298898964, 1.330365926242124]
] as const;
export const MATRIX_D65_TO_D50: ReadonlyColorMatrix = [
[1.0479297925449969, 0.022946870601609652, -0.05019226628920524],
[0.02962780877005599, 0.9904344267538799, -0.017073799063418826],
[-0.009243040646204504, 0.015055191490298152, 0.7518742814281371]
] as const;
export const MATRIX_L_RGB_TO_XYZ: ReadonlyColorMatrix = [
[506752 / 1228815, 87881 / 245763, 12673 / 70218],
[87098 / 409605, 175762 / 245763, 12673 / 175545],
[7918 / 409605, 87881 / 737289, 1001167 / 1053270]
] as const;
export const MATRIX_XYZ_TO_L_RGB: ReadonlyColorMatrix = [
[12831 / 3959, -329 / 214, -1974 / 3959],
[-851781 / 878810, 1648619 / 878810, 36519 / 878810],
[705 / 12673, -2585 / 12673, 705 / 667]
] as const;
export const MATRIX_XYZ_TO_LMS: ReadonlyColorMatrix = [
[0.819022437996703, 0.3619062600528904, -0.1288737815209879],
[0.0329836539323885, 0.9292868615863434, 0.0361446663506424],
[0.0481771893596242, 0.2642395317527308, 0.6335478284694309]
] as const;
export const MATRIX_LMS_TO_XYZ: ReadonlyColorMatrix = [
[1.2268798758459243, -0.5578149944602171, 0.2813910456659647],
[-0.0405757452148008, 1.112286803280317, -0.0717110580655164],
[-0.0763729366746601, -0.4214933324022432, 1.5869240198367816]
] as const;
export const MATRIX_OKLAB_TO_LMS: ReadonlyColorMatrix = [
[1.0, 0.3963377773761749, 0.2158037573099136],
[1.0, -0.1055613458156586, -0.0638541728258133],
[1.0, -0.0894841775298119, -1.2914855480194092]
] as const;
export const MATRIX_LMS_TO_OKLAB: ReadonlyColorMatrix = [
[0.210454268309314, 0.7936177747023054, -0.0040720430116193],
[1.9779985324311684, -2.4285922420485799, 0.450593709617411],
[0.0259040424655478, 0.7827717124575296, -0.8086757549230774]
] as const;
export const MATRIX_P3_TO_XYZ: ReadonlyColorMatrix = [
[608311 / 1250200, 189793 / 714400, 198249 / 1000160],
[35783 / 156275, 247089 / 357200, 198249 / 2500400],
[0 / 1, 32229 / 714400, 5220557 / 5000800]
] as const;
export const MATRIX_REC2020_TO_XYZ: ReadonlyColorMatrix = [
[63426534 / 99577255, 20160776 / 139408157, 47086771 / 278816314],
[26158966 / 99577255, 472592308 / 697040785, 8267143 / 139408157],
[0 / 1, 19567812 / 697040785, 295819943 / 278816314]
] as const;
export const MATRIX_A98_TO_XYZ: ReadonlyColorMatrix = [
[573536 / 994567, 263643 / 1420810, 187206 / 994567],
[591459 / 1989134, 6239551 / 9945670, 374412 / 4972835],
[53769 / 1989134, 351524 / 4972835, 4929758 / 4972835]
] as const;
export const MATRIX_PROPHOTO_TO_XYZ_D50: ReadonlyColorMatrix = [
[0.7977666449006423, 0.13518129740053308, 0.0313477341283922],
[0.2880748288194013, 0.711835234241873, 0.00008993693872564],
[0.0, 0.0, 0.8251046025104602]
] as const;

View File

@ -0,0 +1,557 @@
/**
* transform
*/
import {
ColorChannels,
NumStrColorChannels,
ReadonlyColorMatrix,
TriColorChannels,
ValidateColorComponentsOptions
} from '../typedef';
/* constants */
import {
DEG,
DEG_HALF,
DUO,
HALF,
HEX,
LAB_A,
LAB_B,
LAB_EPSILON,
LAB_KAPPA,
LAB_L,
LINEAR_COEF,
LINEAR_OFFSET,
MAX_PCT,
MAX_RGB,
NONE,
POW_LINEAR,
POW_SQR,
QUAD,
SEXA,
TRIA
} from '../utils/constant';
import {
D50,
MATRIX_D50_TO_D65,
MATRIX_D65_TO_D50,
MATRIX_LMS_TO_OKLAB,
MATRIX_L_RGB_TO_XYZ,
MATRIX_XYZ_TO_LMS,
MATRIX_XYZ_TO_L_RGB
} from './matrix';
/**
* validate color components
* @param arr - color components
* @param opt - options
* @param opt.alpha - alpha channel
* @param opt.minLength - min length
* @param opt.maxLength - max length
* @param opt.minRange - min range
* @param opt.maxRange - max range
* @param opt.validateRange - validate range
* @returns result - validated color components
*/
export const validateColorComponents = (
arr: ColorChannels | TriColorChannels,
opt: ValidateColorComponentsOptions = {}
): ColorChannels | TriColorChannels => {
if (!Array.isArray(arr)) {
throw new TypeError(`${arr} is not an array.`);
}
const {
alpha = false,
minLength = TRIA,
maxLength = QUAD,
minRange = 0,
maxRange = 1,
validateRange = true
} = opt;
if (!Number.isFinite(minLength)) {
throw new TypeError(`${minLength} is not a number.`);
}
if (!Number.isFinite(maxLength)) {
throw new TypeError(`${maxLength} is not a number.`);
}
if (!Number.isFinite(minRange)) {
throw new TypeError(`${minRange} is not a number.`);
}
if (!Number.isFinite(maxRange)) {
throw new TypeError(`${maxRange} is not a number.`);
}
const l = arr.length;
if (l < minLength || l > maxLength) {
throw new Error(`Unexpected array length ${l}.`);
}
let i = 0;
while (i < l) {
const v = arr[i] as number;
if (!Number.isFinite(v)) {
throw new TypeError(`${v} is not a number.`);
} else if (i < TRIA && validateRange && (v < minRange || v > maxRange)) {
throw new RangeError(`${v} is not between ${minRange} and ${maxRange}.`);
} else if (i === TRIA && (v < 0 || v > 1)) {
throw new RangeError(`${v} is not between 0 and 1.`);
}
i++;
}
if (alpha && l === TRIA) {
arr.push(1);
}
return arr;
};
/**
* normalize color components
* @param colorA - color components [v1, v2, v3, v4]
* @param colorB - color components [v1, v2, v3, v4]
* @param [skip] - skip validate
* @returns result - [colorA, colorB]
*/
export const normalizeColorComponents = (
colorA: NumStrColorChannels,
colorB: NumStrColorChannels,
skip: boolean = false
): [ColorChannels, ColorChannels] => {
if (!Array.isArray(colorA)) {
throw new TypeError(`${colorA} is not an array.`);
} else if (colorA.length !== QUAD) {
throw new Error(`Unexpected array length ${colorA.length}.`);
}
if (!Array.isArray(colorB)) {
throw new TypeError(`${colorB} is not an array.`);
} else if (colorB.length !== QUAD) {
throw new Error(`Unexpected array length ${colorB.length}.`);
}
let i = 0;
while (i < QUAD) {
if (colorA[i] === NONE && colorB[i] === NONE) {
colorA[i] = 0;
colorB[i] = 0;
} else if (colorA[i] === NONE) {
colorA[i] = colorB[i] as number;
} else if (colorB[i] === NONE) {
colorB[i] = colorA[i] as number;
}
i++;
}
if (skip) {
return [colorA as ColorChannels, colorB as ColorChannels];
}
const validatedColorA = validateColorComponents(colorA as ColorChannels, {
minLength: QUAD,
validateRange: false
});
const validatedColorB = validateColorComponents(colorB as ColorChannels, {
minLength: QUAD,
validateRange: false
});
return [validatedColorA as ColorChannels, validatedColorB as ColorChannels];
};
/**
* transform matrix
* @param mtx - 3 * 3 matrix
* @param vct - vector
* @param [skip] - skip validate
* @returns TriColorChannels - [p1, p2, p3]
*/
export const transformMatrix = (
mtx: ReadonlyColorMatrix,
vct: TriColorChannels,
skip: boolean = false
): TriColorChannels => {
if (!Array.isArray(mtx)) {
throw new TypeError(`${mtx} is not an array.`);
} else if (mtx.length !== TRIA) {
throw new Error(`Unexpected array length ${mtx.length}.`);
} else if (!skip) {
for (let i of mtx) {
i = validateColorComponents(i as TriColorChannels, {
maxLength: TRIA,
validateRange: false
}) as TriColorChannels;
}
}
const [[r1c1, r1c2, r1c3], [r2c1, r2c2, r2c3], [r3c1, r3c2, r3c3]] = mtx;
let v1, v2, v3;
if (skip) {
[v1, v2, v3] = vct;
} else {
[v1, v2, v3] = validateColorComponents(vct, {
maxLength: TRIA,
validateRange: false
});
}
const p1 = r1c1 * v1 + r1c2 * v2 + r1c3 * v3;
const p2 = r2c1 * v1 + r2c2 * v2 + r2c3 * v3;
const p3 = r3c1 * v1 + r3c2 * v2 + r3c3 * v3;
return [p1, p2, p3];
};
/**
* transform rgb to linear rgb
* @param rgb - [r, g, b] r|g|b: 0..255
* @param [skip] - skip validate
* @returns TriColorChannels - [r, g, b] r|g|b: 0..1
*/
export const transformRgbToLinearRgb = (
rgb: TriColorChannels,
skip: boolean = false
): TriColorChannels => {
let rr, gg, bb;
if (skip) {
[rr, gg, bb] = rgb;
} else {
[rr, gg, bb] = validateColorComponents(rgb, {
maxLength: TRIA,
maxRange: MAX_RGB
});
}
let r = rr / MAX_RGB;
let g = gg / MAX_RGB;
let b = bb / MAX_RGB;
const COND_POW = 0.04045;
if (r > COND_POW) {
r = Math.pow((r + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR);
} else {
r /= LINEAR_COEF;
}
if (g > COND_POW) {
g = Math.pow((g + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR);
} else {
g /= LINEAR_COEF;
}
if (b > COND_POW) {
b = Math.pow((b + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR);
} else {
b /= LINEAR_COEF;
}
return [r, g, b];
};
/**
* transform rgb to xyz
* @param rgb - [r, g, b] r|g|b: 0..255
* @param [skip] - skip validate
* @returns TriColorChannels - [x, y, z]
*/
export const transformRgbToXyz = (
rgb: TriColorChannels,
skip: boolean = false
): TriColorChannels => {
if (!skip) {
rgb = validateColorComponents(rgb, {
maxLength: TRIA,
maxRange: MAX_RGB
}) as TriColorChannels;
}
rgb = transformRgbToLinearRgb(rgb, true);
const xyz = transformMatrix(MATRIX_L_RGB_TO_XYZ, rgb, true);
return xyz;
};
/**
* transform rgb to xyz-d50
* @param rgb - [r, g, b] r|g|b: 0..255 alpha: 0..1
* @returns TriColorChannels - [x, y, z]
*/
export const transformRgbToXyzD50 = (
rgb: TriColorChannels
): TriColorChannels => {
let xyz = transformRgbToXyz(rgb);
xyz = transformMatrix(MATRIX_D65_TO_D50, xyz, true);
return xyz;
};
/**
* transform linear rgb to rgb
* @param rgb - [r, g, b] r|g|b: 0..1
* @param [round] - round result
* @returns TriColorChannels - [r, g, b] r|g|b: 0..255
*/
export const transformLinearRgbToRgb = (
rgb: TriColorChannels,
round: boolean = false
): TriColorChannels => {
let [r, g, b] = validateColorComponents(rgb, {
maxLength: TRIA
});
const COND_POW = 809 / 258400;
if (r > COND_POW) {
r = Math.pow(r, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET;
} else {
r *= LINEAR_COEF;
}
r *= MAX_RGB;
if (g > COND_POW) {
g = Math.pow(g, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET;
} else {
g *= LINEAR_COEF;
}
g *= MAX_RGB;
if (b > COND_POW) {
b = Math.pow(b, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET;
} else {
b *= LINEAR_COEF;
}
b *= MAX_RGB;
return [
round ? Math.round(r) : r,
round ? Math.round(g) : g,
round ? Math.round(b) : b
];
};
/**
* transform xyz to rgb
* @param xyz - [x, y, z]
* @param [skip] - skip validate
* @returns TriColorChannels - [r, g, b] r|g|b: 0..255
*/
export const transformXyzToRgb = (
xyz: TriColorChannels,
skip: boolean = false
): TriColorChannels => {
if (!skip) {
xyz = validateColorComponents(xyz, {
maxLength: TRIA,
validateRange: false
}) as TriColorChannels;
}
let [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, xyz, true);
[r, g, b] = transformLinearRgbToRgb(
[
Math.min(Math.max(r, 0), 1),
Math.min(Math.max(g, 0), 1),
Math.min(Math.max(b, 0), 1)
],
true
);
return [r, g, b];
};
/**
* transform xyz to xyz-d50
* @param xyz - [x, y, z]
* @returns TriColorChannels - [x, y, z]
*/
export const transformXyzToXyzD50 = (
xyz: TriColorChannels
): TriColorChannels => {
xyz = validateColorComponents(xyz, {
maxLength: TRIA,
validateRange: false
}) as TriColorChannels;
xyz = transformMatrix(MATRIX_D65_TO_D50, xyz, true);
return xyz;
};
/**
* transform xyz to hsl
* @param xyz - [x, y, z]
* @param [skip] - skip validate
* @returns TriColorChannels - [h, s, l]
*/
export const transformXyzToHsl = (
xyz: TriColorChannels,
skip: boolean = false
): TriColorChannels => {
const [rr, gg, bb] = transformXyzToRgb(xyz, skip);
const r = rr / MAX_RGB;
const g = gg / MAX_RGB;
const b = bb / MAX_RGB;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const d = max - min;
const l = (max + min) * HALF * MAX_PCT;
let h, s;
if (Math.round(l) === 0 || Math.round(l) === MAX_PCT) {
h = 0;
s = 0;
} else {
s = (d / (1 - Math.abs(max + min - 1))) * MAX_PCT;
if (s === 0) {
h = 0;
} else {
switch (max) {
case r:
h = (g - b) / d;
break;
case g:
h = (b - r) / d + DUO;
break;
case b:
default:
h = (r - g) / d + QUAD;
break;
}
h = (h * SEXA) % DEG;
if (h < 0) {
h += DEG;
}
}
}
return [h, s, l];
};
/**
* transform xyz to hwb
* @param xyz - [x, y, z]
* @param [skip] - skip validate
* @returns TriColorChannels - [h, w, b]
*/
export const transformXyzToHwb = (
xyz: TriColorChannels,
skip: boolean = false
): TriColorChannels => {
const [r, g, b] = transformXyzToRgb(xyz, skip);
const wh = Math.min(r, g, b) / MAX_RGB;
const bk = 1 - Math.max(r, g, b) / MAX_RGB;
let h;
if (wh + bk === 1) {
h = 0;
} else {
[h] = transformXyzToHsl(xyz);
}
return [h, wh * MAX_PCT, bk * MAX_PCT];
};
/**
* transform xyz to oklab
* @param xyz - [x, y, z]
* @param [skip] - skip validate
* @returns TriColorChannels - [l, a, b]
*/
export const transformXyzToOklab = (
xyz: TriColorChannels,
skip: boolean = false
): TriColorChannels => {
if (!skip) {
xyz = validateColorComponents(xyz, {
maxLength: TRIA,
validateRange: false
}) as TriColorChannels;
}
const lms = transformMatrix(MATRIX_XYZ_TO_LMS, xyz, true);
const xyzLms = lms.map((c: number) => Math.cbrt(c)) as TriColorChannels;
let [l, a, b] = transformMatrix(MATRIX_LMS_TO_OKLAB, xyzLms, true);
l = Math.min(Math.max(l, 0), 1);
const lPct = Math.round(parseFloat(l.toFixed(QUAD)) * MAX_PCT);
if (lPct === 0 || lPct === MAX_PCT) {
a = 0;
b = 0;
}
return [l, a, b];
};
/**
* transform xyz to oklch
* @param xyz - [x, y, z]
* @param [skip] - skip validate
* @returns TriColorChannels - [l, c, h]
*/
export const transformXyzToOklch = (
xyz: TriColorChannels,
skip: boolean = false
): TriColorChannels => {
const [l, a, b] = transformXyzToOklab(xyz, skip);
let c, h;
const lPct = Math.round(parseFloat(l.toFixed(QUAD)) * MAX_PCT);
if (lPct === 0 || lPct === MAX_PCT) {
c = 0;
h = 0;
} else {
c = Math.max(Math.sqrt(Math.pow(a, POW_SQR) + Math.pow(b, POW_SQR)), 0);
if (parseFloat(c.toFixed(QUAD)) === 0) {
h = 0;
} else {
h = (Math.atan2(b, a) * DEG_HALF) / Math.PI;
if (h < 0) {
h += DEG;
}
}
}
return [l, c, h];
};
/**
* transform xyz D50 to rgb
* @param xyz - [x, y, z]
* @param [skip] - skip validate
* @returns TriColorChannels - [r, g, b] r|g|b: 0..255
*/
export const transformXyzD50ToRgb = (
xyz: TriColorChannels,
skip: boolean = false
): TriColorChannels => {
if (!skip) {
xyz = validateColorComponents(xyz, {
maxLength: TRIA,
validateRange: false
}) as TriColorChannels;
}
const xyzD65 = transformMatrix(MATRIX_D50_TO_D65, xyz, true);
const rgb = transformXyzToRgb(xyzD65, true);
return rgb;
};
/**
* transform xyz-d50 to lab
* @param xyz - [x, y, z]
* @param [skip] - skip validate
* @returns TriColorChannels - [l, a, b]
*/
export const transformXyzD50ToLab = (
xyz: TriColorChannels,
skip: boolean = false
): TriColorChannels => {
if (!skip) {
xyz = validateColorComponents(xyz, {
maxLength: TRIA,
validateRange: false
}) as TriColorChannels;
}
const xyzD50 = xyz.map((val: number, i: number) => val / (D50[i] as number));
const [f0, f1, f2] = xyzD50.map((val: number) =>
val > LAB_EPSILON ? Math.cbrt(val) : (LAB_KAPPA * val + 16) / LAB_L
) as TriColorChannels;
const l = Math.min(Math.max(LAB_L * f1 - HEX, 0), MAX_PCT);
let a, b;
if (l === 0 || l === MAX_PCT) {
a = 0;
b = 0;
} else {
a = (f0 - f1) * LAB_A;
b = (f1 - f2) * LAB_B;
}
return [l, a, b];
};
/**
* transform xyz-d50 to lch
* @param xyz - [x, y, z]
* @param [skip] - skip validate
* @returns TriColorChannels - [l, c, h]
*/
export const transformXyzD50ToLch = (
xyz: TriColorChannels,
skip: boolean = false
): TriColorChannels => {
const [l, a, b] = transformXyzD50ToLab(xyz, skip);
let c, h;
if (l === 0 || l === MAX_PCT) {
c = 0;
h = 0;
} else {
c = Math.max(Math.sqrt(Math.pow(a, POW_SQR) + Math.pow(b, POW_SQR)), 0);
h = (Math.atan2(b, a) * DEG_HALF) / Math.PI;
if (h < 0) {
h += DEG;
}
}
return [l, c, h];
};

View File

@ -0,0 +1,896 @@
/**
* color-mix
*/
import {
convertColorToHsl,
convertColorToHwb,
convertColorToLab,
convertColorToLch,
convertColorToLinearRgb,
convertColorToOklab,
convertColorToOklch,
convertColorToRgb,
convertColorToXyz
} from '../converters/convert-color';
import {
ChannelNoneFlags,
ColorAndPct,
ColorChannels,
ColorFormat,
ColorResolverFn,
ColorSpace,
ColorSpaceParseResult,
ComputedColorChannels,
InterpolatedComponents,
NormalizedPercentages,
NumStrColorChannels,
Options,
SpecifiedColorChannels,
TriColorChannels
} from '../typedef';
import {
normalizeColorComponents,
transformXyzD50ToRgb,
transformXyzToRgb
} from '../matrix/transform';
import { parseColorFunc, parseColorValue } from '../resolvers/parse-color';
import { resolveColorValue } from '../resolvers/resolve-color';
import { createCacheKey, getCache, setCache } from '../utils/cache';
import { isString } from '../utils/common';
import {
cacheInvalidColorValue,
interpolateHue,
roundToPrecision,
splitValue
} from '../utils/util';
/* constants */
import {
DEG,
FN_COLOR,
FN_LIGHT_DARK,
FN_MIX,
HALF,
HEX,
MAX_PCT,
MAX_RGB,
NONE,
VAL_COMP,
VAL_MIX,
VAL_SPEC
} from '../utils/constant';
const NAMESPACE = 'color-mix';
/**
* parse color space
* @param arg - color space argument string
* @returns object containing colorSpace and hueArc, or null if invalid
*/
export const parseColorSpace = (arg: string): ColorSpaceParseResult | null => {
const csTokens = splitValue(arg).filter(Boolean);
if (csTokens[0] !== 'in' || csTokens.length < 2) {
return null;
}
const hueIndex = csTokens.indexOf('hue');
if (csTokens.length > 2 && hueIndex > -1) {
return {
colorSpace: csTokens[1] as string,
hueArc: csTokens.slice(2, hueIndex).join(' ')
};
}
return {
colorSpace: csTokens.slice(1).join(' '),
hueArc: ''
};
};
/**
* parse color and percentage
* @param arg - color and percentage argument string
* @returns object containing color string and percentage string
*/
export const parseColorAndPct = (arg: string): ColorAndPct => {
const tokens = splitValue(arg).filter(Boolean);
let color = '';
let pct = '';
if (tokens.length === 1) {
color = tokens[0] as string;
} else {
const isPct = (t: string) => {
return t.endsWith('%') || t.startsWith('calc(') || t === 'none';
};
if (isPct(tokens[tokens.length - 1] as string)) {
pct = tokens.pop() as string;
color = tokens.join(' ');
} else if (isPct(tokens[0] as string)) {
pct = tokens.shift() as string;
color = tokens.join(' ');
} else {
color = tokens.join(' ');
}
}
return { color, pct };
};
/**
* resolve if nested function
* @param colorStr - color string
* @param opt - options
* @param resolver - resolver function
* @returns resolved color string or original string
*/
export const resolveIfNested = (
colorStr: string,
opt: Options,
resolver: ColorResolverFn
): string => {
let current = colorStr;
while (
isString(current) &&
(current.startsWith('color-mix(') ||
current.startsWith('var(') ||
current.startsWith('light-dark('))
) {
const resolved = resolver(current, {
...opt,
format: opt.format === VAL_SPEC ? opt.format : VAL_COMP
});
if (!resolved) {
break;
}
if (Array.isArray(resolved)) {
const [cs, v1, v2, v3, v4] = resolved;
if (v4 === 1 || v4 === undefined) {
current =
cs === 'rgb'
? `${cs}(${v1}, ${v2}, ${v3})`
: `${cs}(${v1} ${v2} ${v3})`;
} else {
current =
cs === 'rgb'
? `${cs}a(${v1}, ${v2}, ${v3}, ${v4})`
: `${cs}(${v1} ${v2} ${v3} / ${v4})`;
}
break;
}
if (typeof resolved === 'string') {
if (resolved === current) {
break;
}
current = resolved;
} else {
break;
}
}
return current;
};
/**
* normalize percentages
* @param pctA - percentage for color A
* @param pctB - percentage for color B
* @returns object containing normalized percentages and multiplier, or null if invalid
*/
export const normalizePercentages = (
pctA: string,
pctB: string
): NormalizedPercentages | null => {
let pA, pB, m;
if (pctA && pctB) {
const p1 = parseFloat(pctA) / MAX_PCT;
const p2 = parseFloat(pctB) / MAX_PCT;
if (
Number.isNaN(p1) ||
Number.isNaN(p2) ||
p1 < 0 ||
p1 > 1 ||
p2 < 0 ||
p2 > 1 ||
(p1 === 0 && p2 === 0)
) {
return null;
}
const factor = p1 + p2;
pA = p1 / factor;
pB = p2 / factor;
m = factor < 1 ? factor : 1;
} else {
if (pctA) {
const numA = parseFloat(pctA);
if (Number.isNaN(numA) || numA < 0 || numA > MAX_PCT) {
return null;
}
pA = numA / MAX_PCT;
pB = (MAX_PCT - numA) / MAX_PCT;
} else if (pctB) {
const numB = parseFloat(pctB);
if (Number.isNaN(numB) || numB < 0 || numB > MAX_PCT) {
return null;
}
pB = numB / MAX_PCT;
pA = (MAX_PCT - numB) / MAX_PCT;
} else {
pA = HALF;
pB = HALF;
}
m = 1;
}
return { pA, pB, m };
};
/**
* process color
* @param colorStr - color string
* @param opt - options
* @returns specified color string
*/
export const processColor = (colorStr: string, opt: Options): string => {
if (!isString(colorStr)) {
return '';
}
if (colorStr.startsWith(FN_MIX) || colorStr.startsWith(FN_LIGHT_DARK)) {
return colorStr;
}
if (colorStr.startsWith(FN_COLOR)) {
const [cs, v1, v2, v3, v4] = parseColorFunc(
colorStr,
opt
) as SpecifiedColorChannels;
if (v4 === 1) {
return `color(${cs} ${v1} ${v2} ${v3})`;
} else {
return `color(${cs} ${v1} ${v2} ${v3} / ${v4})`;
}
}
const val = parseColorValue(colorStr, opt);
if (Array.isArray(val)) {
const [cs, v1, v2, v3, v4] = val;
if (v4 === 1) {
if (cs === 'rgb') {
return `${cs}(${v1}, ${v2}, ${v3})`;
}
return `${cs}(${v1} ${v2} ${v3})`;
} else {
if (cs === 'rgb') {
return `${cs}a(${v1}, ${v2}, ${v3}, ${v4})`;
}
return `${cs}(${v1} ${v2} ${v3} / ${v4})`;
}
}
if (!isString(val) || !val) {
return '';
}
return val as string;
};
/**
* build specified color mix
* @param colorSpace - color space
* @param hueArc - hue interpolation method
* @param colorA - first color
* @param pctA - percentage for first color
* @param colorB - second color
* @param pctB - percentage for second color
* @param opt - options
* @returns specified value string for color-mix()
*/
export const buildSpecifiedColorMix = (
colorSpace: string,
hueArc: string,
colorA: string,
pctA: string,
colorB: string,
pctB: string,
opt: Options
): string => {
let valueA = processColor(colorA, opt);
let valueB = processColor(colorB, opt);
if (!valueA || !valueB) {
return '';
}
if (pctA && pctB) {
valueA += ` ${parseFloat(pctA)}%`;
valueB += ` ${parseFloat(pctB)}%`;
} else if (pctA) {
const numPctA = parseFloat(pctA);
if (numPctA !== MAX_PCT * HALF) {
valueA += ` ${numPctA}%`;
}
} else if (pctB) {
const numPctA = MAX_PCT - parseFloat(pctB);
if (numPctA !== MAX_PCT * HALF) {
valueA += ` ${numPctA}%`;
}
}
if (hueArc) {
return `color-mix(in ${colorSpace} ${hueArc} hue, ${valueA}, ${valueB})`;
}
return `color-mix(in ${colorSpace}, ${valueA}, ${valueB})`;
};
/**
* Perform alpha-weighted interpolation for color components.
* @param compA - color components for color A
* @param compB - color components for color B
* @param alphaA - alpha channel value for color A
* @param alphaB - alpha channel value for color B
* @param pA - normalized ratio for first color
* @param pB - normalized ratio for second color
* @returns object containing interpolated components and combined alpha
*/
export const interpolateComponents = (
compA: TriColorChannels,
compB: TriColorChannels,
alphaA: number,
alphaB: number,
pA: number,
pB: number
): InterpolatedComponents => {
const factorA = alphaA * pA;
const factorB = alphaB * pB;
const alpha = factorA + factorB;
let comps: TriColorChannels;
if (alpha === 0) {
comps = [
compA[0] * pA + compB[0] * pB,
compA[1] * pA + compB[1] * pB,
compA[2] * pA + compB[2] * pB
];
} else {
comps = [
(compA[0] * factorA + compB[0] * factorB) / alpha,
(compA[1] * factorA + compB[1] * factorB) / alpha,
(compA[2] * factorA + compB[2] * factorB) / alpha
];
}
return { comps, alpha };
};
/**
* Format computed color into specified or computed channel array.
* @param colorSpace - target color space
* @param comps - 3-channel color components
* @param nones - boolean flags indicating if channels are 'none'
* @param alpha - calculated alpha channel value
* @param m - multiplier factor
* @param format - output format option
* @param rgbOverride - optional pre-calculated RGB channels
* @returns specified color channels array
*/
export const formatMixedColor = (
colorSpace: ColorSpace,
comps: TriColorChannels,
nones: ChannelNoneFlags,
alpha: number,
m: number,
format: ColorFormat,
rgbOverride?: TriColorChannels
): SpecifiedColorChannels => {
const [c1None, c2None, c3None, alphaNone] = nones;
const [c1, c2, c3] = comps;
if (format === VAL_COMP) {
return [
colorSpace,
c1None ? NONE : roundToPrecision(c1, HEX),
c2None ? NONE : roundToPrecision(c2, HEX),
c3None ? NONE : roundToPrecision(c3, HEX),
alphaNone ? NONE : alpha * m
];
}
const [r, g, b] = rgbOverride ?? comps;
return [
'rgb',
Math.round(r),
Math.round(g),
Math.round(b),
parseFloat((alpha * m).toFixed(3))
];
};
/**
* Fetch raw channels or fallback for currentcolor
* @param color - color input string
* @param convertFn - conversion function
* @param opt - conversion options
* @returns color channel values or null if invalid
*/
export const getRawChannels = (
color: string | NumStrColorChannels,
convertFn: (c: string, opt: any) => any,
opt: any
): NumStrColorChannels | null => {
if (Array.isArray(color)) {
return color as NumStrColorChannels;
}
if (color === 'currentcolor') {
return [NONE, NONE, NONE, NONE];
}
return convertFn(color, opt);
};
/**
* Mix colors in srgb or srgb-linear space.
* @param colorSpace - color space name ('srgb' | 'srgb-linear')
* @param colorA - first color string
* @param colorB - second color string
* @param pA - ratio for first color
* @param pB - ratio for second color
* @param format - output format
* @param m - multiplier factor
* @returns mixed color channels or null
*/
export const mixSrgbSpace = (
colorSpace: ColorSpace,
colorA: string,
colorB: string,
pA: number,
pB: number,
format: ColorFormat,
m: number
): SpecifiedColorChannels | null => {
const convertFn =
colorSpace === 'srgb' ? convertColorToRgb : convertColorToLinearRgb;
const rgbA = getRawChannels(colorA, convertFn, {
colorSpace,
format: VAL_MIX
});
const rgbB = getRawChannels(colorB, convertFn, {
colorSpace,
format: VAL_MIX
});
if (!rgbA || !rgbB) {
return null;
}
const [rrA, ggA, bbA, aaA] = rgbA;
const [rrB, ggB, bbB, aaB] = rgbB;
const nones: [boolean, boolean, boolean, boolean] = [
rrA === NONE && rrB === NONE,
ggA === NONE && ggB === NONE,
bbA === NONE && bbB === NONE,
aaA === NONE && aaB === NONE
];
const [[rA, gA, bA, alphaA], [rB, gB, bB, alphaB]] = normalizeColorComponents(
rgbA,
rgbB,
true
);
const { comps, alpha } = interpolateComponents(
[rA, gA, bA],
[rB, gB, bB],
alphaA,
alphaB,
pA,
pB
);
const rgbOverride: [number, number, number] = [
comps[0] * MAX_RGB,
comps[1] * MAX_RGB,
comps[2] * MAX_RGB
];
return formatMixedColor(
colorSpace,
comps,
nones,
alpha,
m,
format,
rgbOverride
);
};
/**
* Mix colors in xyz, xyz-d50, or xyz-d65 space.
* @param colorSpace - color space name
* @param colorA - first color string
* @param colorB - second color string
* @param pA - ratio for first color
* @param pB - ratio for second color
* @param format - output format
* @param m - multiplier factor
* @returns mixed color channels or null
*/
export const mixXyzSpace = (
colorSpace: string,
colorA: string,
colorB: string,
pA: number,
pB: number,
format: string,
m: number
): SpecifiedColorChannels | null => {
const isD50 = colorSpace === 'xyz-d50';
const opt = { colorSpace, d50: isD50, format: VAL_MIX };
const xyzA = getRawChannels(colorA, convertColorToXyz, opt);
const xyzB = getRawChannels(colorB, convertColorToXyz, opt);
if (!xyzA || !xyzB) {
return null;
}
const [xxA, yyA, zzA, aaA] = xyzA;
const [xxB, yyB, zzB, aaB] = xyzB;
const nones: [boolean, boolean, boolean, boolean] = [
xxA === NONE && xxB === NONE,
yyA === NONE && yyB === NONE,
zzA === NONE && zzB === NONE,
aaA === NONE && aaB === NONE
];
const [[xA, yA, zA, alphaA], [xB, yB, zB, alphaB]] = normalizeColorComponents(
xyzA,
xyzB,
true
);
const { comps, alpha } = interpolateComponents(
[xA, yA, zA],
[xB, yB, zB],
alphaA,
alphaB,
pA,
pB
);
const rgb = isD50
? transformXyzD50ToRgb(comps, true)
: transformXyzToRgb(comps, true);
return formatMixedColor(colorSpace, comps, nones, alpha, m, format, rgb);
};
/**
* Mix colors in hsl or hwb space.
* @param colorSpace - color space name ('hsl' | 'hwb')
* @param hueArc - hue interpolation method
* @param colorA - first color string
* @param colorB - second color string
* @param pA - ratio for first color
* @param pB - ratio for second color
* @param format - output format
* @param m - multiplier factor
* @returns mixed color channels or null
*/
export const mixHslHwbSpace = (
colorSpace: string,
hueArc: string,
colorA: string,
colorB: string,
pA: number,
pB: number,
format: string,
m: number
): SpecifiedColorChannels | null => {
const convertFn =
colorSpace === 'hsl' ? convertColorToHsl : convertColorToHwb;
const opt = { colorSpace, format: VAL_MIX };
const hslA = getRawChannels(colorA, convertFn, opt);
const hslB = getRawChannels(colorB, convertFn, opt);
if (!hslA || !hslB) {
return null;
}
const [, , , aaA] = hslA;
const [, , , aaB] = hslB;
const nones: [boolean, boolean, boolean, boolean] = [
false,
false,
false,
aaA === NONE && aaB === NONE
];
let [[hA, sA, lA, alphaA], [hB, sB, lB, alphaB]] = normalizeColorComponents(
hslA,
hslB,
true
);
if (hueArc) {
[hA, hB] = interpolateHue(hA, hB, hueArc);
}
const factorA = alphaA * pA;
const factorB = alphaB * pB;
const alpha = factorA + factorB;
const h = (hA * pA + hB * pB) % DEG;
let s: number, l: number;
if (alpha === 0) {
s = sA * pA + sB * pB;
l = lA * pA + lB * pB;
} else {
s = (sA * factorA + sB * factorB) / alpha;
l = (lA * factorA + lB * factorB) / alpha;
}
const [r, g, b] = convertColorToRgb(
`${colorSpace}(${h} ${s} ${l})`
) as ColorChannels;
const compsForValComp: TriColorChannels = [
r / MAX_RGB,
g / MAX_RGB,
b / MAX_RGB
];
const targetSpace = format === VAL_COMP ? 'srgb' : colorSpace;
return formatMixedColor(
targetSpace,
compsForValComp,
nones,
alpha,
m,
format,
[r, g, b]
);
};
/**
* Mix colors in lch or oklch space.
* @param colorSpace - color space name ('lch' | 'oklch')
* @param hueArc - hue interpolation method
* @param colorA - first color string
* @param colorB - second color string
* @param pA - ratio for first color
* @param pB - ratio for second color
* @param format - output format
* @param m - multiplier factor
* @returns mixed color channels or null
*/
export const mixLchSpace = (
colorSpace: string,
hueArc: string,
colorA: string,
colorB: string,
pA: number,
pB: number,
format: string,
m: number
): SpecifiedColorChannels | null => {
const convertFn =
colorSpace === 'lch' ? convertColorToLch : convertColorToOklch;
const opt = { colorSpace, format: VAL_MIX };
const lchA = getRawChannels(colorA, convertFn, opt);
const lchB = getRawChannels(colorB, convertFn, opt);
if (!lchA || !lchB) {
return null;
}
const [llA, ccA, hhA, aaA] = lchA;
const [llB, ccB, hhB, aaB] = lchB;
const nones: [boolean, boolean, boolean, boolean] = [
llA === NONE && llB === NONE,
ccA === NONE && ccB === NONE,
hhA === NONE && hhB === NONE,
aaA === NONE && aaB === NONE
];
let [[lA, cA, hA, alphaA], [lB, cB, hB, alphaB]] = normalizeColorComponents(
lchA,
lchB,
true
);
if (hueArc) {
[hA, hB] = interpolateHue(hA, hB, hueArc);
}
const factorA = alphaA * pA;
const factorB = alphaB * pB;
const alpha = factorA + factorB;
const h = (hA * pA + hB * pB) % DEG;
let l: number, c: number;
if (alpha === 0) {
l = lA * pA + lB * pB;
c = cA * pA + cB * pB;
} else {
l = (lA * factorA + lB * factorB) / alpha;
c = (cA * factorA + cB * factorB) / alpha;
}
let rgbOverride: [number, number, number] | undefined;
if (format !== VAL_COMP) {
const [, r, g, b] = resolveColorValue(
`${colorSpace}(${l} ${c} ${h})`
) as ComputedColorChannels;
rgbOverride = [r, g, b];
}
return formatMixedColor(
colorSpace,
[l, c, h],
nones,
alpha,
m,
format,
rgbOverride
);
};
/**
* Mix colors in lab or oklab space.
* @param colorSpace - color space name ('lab' | 'oklab')
* @param colorA - first color string
* @param colorB - second color string
* @param pA - ratio for first color
* @param pB - ratio for second color
* @param format - output format
* @param m - multiplier factor
* @returns mixed color channels or null
*/
export const mixLabSpace = (
colorSpace: string,
colorA: string,
colorB: string,
pA: number,
pB: number,
format: string,
m: number
): SpecifiedColorChannels | null => {
const convertFn =
colorSpace === 'lab' ? convertColorToLab : convertColorToOklab;
const opt = { colorSpace, format: VAL_MIX };
const labA = getRawChannels(colorA, convertFn, opt);
const labB = getRawChannels(colorB, convertFn, opt);
if (!labA || !labB) {
return null;
}
const [llA, aaA, bbA, alA] = labA;
const [llB, aaB, bbB, alB] = labB;
const nones: [boolean, boolean, boolean, boolean] = [
llA === NONE && llB === NONE,
aaA === NONE && aaB === NONE,
bbA === NONE && bbB === NONE,
alA === NONE && alB === NONE
];
const [[lA, aA, bA, alphaA], [lB, aB, bB, alphaB]] = normalizeColorComponents(
labA,
labB,
true
);
const { comps, alpha } = interpolateComponents(
[lA, aA, bA],
[lB, aB, bB],
alphaA,
alphaB,
pA,
pB
);
let rgbOverride: [number, number, number] | undefined;
if (format !== VAL_COMP) {
const [, r, g, b] = resolveColorValue(
`${colorSpace}(${comps[0]} ${comps[1]} ${comps[2]})`
) as ComputedColorChannels;
rgbOverride = [r, g, b];
}
return formatMixedColor(
colorSpace,
comps,
nones,
alpha,
m,
format,
rgbOverride
);
};
/**
* compute mixed color
* @param colorSpace - color space
* @param hueArc - hue interpolation method
* @param colorA - first color
* @param colorB - second color
* @param pA - normalized ratio for first color
* @param pB - normalized ratio for second color
* @param m - multiplier
* @param format - output format
* @param nullable - is nullable
* @param cacheKey - cache key
* @returns computed color channels or null
*/
export const computeMixedColor = (
colorSpace: string,
hueArc: string,
colorA: string,
colorB: string,
pA: number,
pB: number,
m: number,
format: string,
nullable: boolean,
cacheKey: string
): SpecifiedColorChannels | null => {
let res: SpecifiedColorChannels | null = null;
if (/^srgb(?:-linear)?$/.test(colorSpace)) {
res = mixSrgbSpace(colorSpace, colorA, colorB, pA, pB, format, m);
} else if (/^xyz(?:-d65|-d50)?$/.test(colorSpace)) {
res = mixXyzSpace(colorSpace, colorA, colorB, pA, pB, format, m);
} else if (/^h(?:sl|wb)$/.test(colorSpace)) {
res = mixHslHwbSpace(colorSpace, hueArc, colorA, colorB, pA, pB, format, m);
} else if (/^(?:ok)?lch$/.test(colorSpace)) {
res = mixLchSpace(colorSpace, hueArc, colorA, colorB, pA, pB, format, m);
} else if (/^(?:ok)?lab$/.test(colorSpace)) {
res = mixLabSpace(colorSpace, colorA, colorB, pA, pB, format, m);
}
if (res === null) {
return cacheInvalidColorValue(cacheKey, format, nullable) as null;
}
return res;
};
/**
* resolve color-mix()
* @param value - color-mix color value
* @param opt - options
* @param resolver - resolver function
* @returns resolved color - [cs, v1, v2, v3, alpha], '(empty)', null
*/
export const resolveColorMix = (
value: string,
opt: Options = {},
resolver: ColorResolverFn = () => null
): SpecifiedColorChannels | string | null => {
if (!isString(value)) {
throw new TypeError(`${value} is not a string.`);
}
value = value.toLowerCase().trim();
const { format = '', nullable = false } = opt;
const cacheKey: string = createCacheKey(
{ namespace: NAMESPACE, name: 'resolveColorMix', value },
opt
);
const cachedResult = getCache(cacheKey);
if (cachedResult !== false) {
const { item } = cachedResult;
if (Array.isArray(item)) {
return [...item] as SpecifiedColorChannels;
}
if (isString(item)) {
return item;
}
return null;
}
if (!value.startsWith('color-mix(') || !value.endsWith(')')) {
return cacheInvalidColorValue(cacheKey, format, nullable);
}
const innerContent = value.slice(10, -1).trim();
const args = splitValue(innerContent, { delimiter: ',' }).map(s => s.trim());
if (args.length !== 3) {
return cacheInvalidColorValue(cacheKey, format, nullable);
}
// 1. Parse Color Space
const csResult = parseColorSpace(args[0] as string);
if (!csResult) {
return cacheInvalidColorValue(cacheKey, format, nullable);
}
let { colorSpace, hueArc } = csResult;
// 2. Extract Color and Percentages
let { color: colorA, pct: pctA } = parseColorAndPct(args[1] as string);
let { color: colorB, pct: pctB } = parseColorAndPct(args[2] as string);
// 3. Resolve Nested Functions
colorA = resolveIfNested(colorA, opt, resolver);
colorB = resolveIfNested(colorB, opt, resolver);
// 4. Normalize Percentages
const pResult = normalizePercentages(pctA, pctB);
if (!pResult) {
return cacheInvalidColorValue(cacheKey, format, nullable);
}
const { pA, pB, m } = pResult;
if (colorSpace === 'xyz') {
colorSpace = 'xyz-d65';
}
// 5. Format & Return
if (format === VAL_SPEC) {
const specifiedRes = buildSpecifiedColorMix(
colorSpace,
hueArc,
colorA,
pctA,
colorB,
pctB,
opt
);
if (!specifiedRes) {
const invalidRes = cacheInvalidColorValue(cacheKey, format, nullable);
return invalidRes;
}
setCache(cacheKey, specifiedRes);
return specifiedRes;
}
const computedRes = computeMixedColor(
colorSpace,
hueArc,
colorA,
colorB,
pA,
pB,
m,
format,
nullable,
cacheKey
);
if (computedRes) {
setCache(cacheKey, computedRes);
}
return computedRes;
};

View File

@ -0,0 +1,159 @@
/**
* named-color
*/
import type { ReadonlyTriColorChannels } from '../typedef';
/**
* named colors
*/
export const NAMED_COLORS = {
aliceblue: [0xf0, 0xf8, 0xff],
antiquewhite: [0xfa, 0xeb, 0xd7],
aqua: [0x00, 0xff, 0xff],
aquamarine: [0x7f, 0xff, 0xd4],
azure: [0xf0, 0xff, 0xff],
beige: [0xf5, 0xf5, 0xdc],
bisque: [0xff, 0xe4, 0xc4],
black: [0x00, 0x00, 0x00],
blanchedalmond: [0xff, 0xeb, 0xcd],
blue: [0x00, 0x00, 0xff],
blueviolet: [0x8a, 0x2b, 0xe2],
brown: [0xa5, 0x2a, 0x2a],
burlywood: [0xde, 0xb8, 0x87],
cadetblue: [0x5f, 0x9e, 0xa0],
chartreuse: [0x7f, 0xff, 0x00],
chocolate: [0xd2, 0x69, 0x1e],
coral: [0xff, 0x7f, 0x50],
cornflowerblue: [0x64, 0x95, 0xed],
cornsilk: [0xff, 0xf8, 0xdc],
crimson: [0xdc, 0x14, 0x3c],
cyan: [0x00, 0xff, 0xff],
darkblue: [0x00, 0x00, 0x8b],
darkcyan: [0x00, 0x8b, 0x8b],
darkgoldenrod: [0xb8, 0x86, 0x0b],
darkgray: [0xa9, 0xa9, 0xa9],
darkgreen: [0x00, 0x64, 0x00],
darkgrey: [0xa9, 0xa9, 0xa9],
darkkhaki: [0xbd, 0xb7, 0x6b],
darkmagenta: [0x8b, 0x00, 0x8b],
darkolivegreen: [0x55, 0x6b, 0x2f],
darkorange: [0xff, 0x8c, 0x00],
darkorchid: [0x99, 0x32, 0xcc],
darkred: [0x8b, 0x00, 0x00],
darksalmon: [0xe9, 0x96, 0x7a],
darkseagreen: [0x8f, 0xbc, 0x8f],
darkslateblue: [0x48, 0x3d, 0x8b],
darkslategray: [0x2f, 0x4f, 0x4f],
darkslategrey: [0x2f, 0x4f, 0x4f],
darkturquoise: [0x00, 0xce, 0xd1],
darkviolet: [0x94, 0x00, 0xd3],
deeppink: [0xff, 0x14, 0x93],
deepskyblue: [0x00, 0xbf, 0xff],
dimgray: [0x69, 0x69, 0x69],
dimgrey: [0x69, 0x69, 0x69],
dodgerblue: [0x1e, 0x90, 0xff],
firebrick: [0xb2, 0x22, 0x22],
floralwhite: [0xff, 0xfa, 0xf0],
forestgreen: [0x22, 0x8b, 0x22],
fuchsia: [0xff, 0x00, 0xff],
gainsboro: [0xdc, 0xdc, 0xdc],
ghostwhite: [0xf8, 0xf8, 0xff],
gold: [0xff, 0xd7, 0x00],
goldenrod: [0xda, 0xa5, 0x20],
gray: [0x80, 0x80, 0x80],
green: [0x00, 0x80, 0x00],
greenyellow: [0xad, 0xff, 0x2f],
grey: [0x80, 0x80, 0x80],
honeydew: [0xf0, 0xff, 0xf0],
hotpink: [0xff, 0x69, 0xb4],
indianred: [0xcd, 0x5c, 0x5c],
indigo: [0x4b, 0x00, 0x82],
ivory: [0xff, 0xff, 0xf0],
khaki: [0xf0, 0xe6, 0x8c],
lavender: [0xe6, 0xe6, 0xfa],
lavenderblush: [0xff, 0xf0, 0xf5],
lawngreen: [0x7c, 0xfc, 0x00],
lemonchiffon: [0xff, 0xfa, 0xcd],
lightblue: [0xad, 0xd8, 0xe6],
lightcoral: [0xf0, 0x80, 0x80],
lightcyan: [0xe0, 0xff, 0xff],
lightgoldenrodyellow: [0xfa, 0xfa, 0xd2],
lightgray: [0xd3, 0xd3, 0xd3],
lightgreen: [0x90, 0xee, 0x90],
lightgrey: [0xd3, 0xd3, 0xd3],
lightpink: [0xff, 0xb6, 0xc1],
lightsalmon: [0xff, 0xa0, 0x7a],
lightseagreen: [0x20, 0xb2, 0xaa],
lightskyblue: [0x87, 0xce, 0xfa],
lightslategray: [0x77, 0x88, 0x99],
lightslategrey: [0x77, 0x88, 0x99],
lightsteelblue: [0xb0, 0xc4, 0xde],
lightyellow: [0xff, 0xff, 0xe0],
lime: [0x00, 0xff, 0x00],
limegreen: [0x32, 0xcd, 0x32],
linen: [0xfa, 0xf0, 0xe6],
magenta: [0xff, 0x00, 0xff],
maroon: [0x80, 0x00, 0x00],
mediumaquamarine: [0x66, 0xcd, 0xaa],
mediumblue: [0x00, 0x00, 0xcd],
mediumorchid: [0xba, 0x55, 0xd3],
mediumpurple: [0x93, 0x70, 0xdb],
mediumseagreen: [0x3c, 0xb3, 0x71],
mediumslateblue: [0x7b, 0x68, 0xee],
mediumspringgreen: [0x00, 0xfa, 0x9a],
mediumturquoise: [0x48, 0xd1, 0xcc],
mediumvioletred: [0xc7, 0x15, 0x85],
midnightblue: [0x19, 0x19, 0x70],
mintcream: [0xf5, 0xff, 0xfa],
mistyrose: [0xff, 0xe4, 0xe1],
moccasin: [0xff, 0xe4, 0xb5],
navajowhite: [0xff, 0xde, 0xad],
navy: [0x00, 0x00, 0x80],
oldlace: [0xfd, 0xf5, 0xe6],
olive: [0x80, 0x80, 0x00],
olivedrab: [0x6b, 0x8e, 0x23],
orange: [0xff, 0xa5, 0x00],
orangered: [0xff, 0x45, 0x00],
orchid: [0xda, 0x70, 0xd6],
palegoldenrod: [0xee, 0xe8, 0xaa],
palegreen: [0x98, 0xfb, 0x98],
paleturquoise: [0xaf, 0xee, 0xee],
palevioletred: [0xdb, 0x70, 0x93],
papayawhip: [0xff, 0xef, 0xd5],
peachpuff: [0xff, 0xda, 0xb9],
peru: [0xcd, 0x85, 0x3f],
pink: [0xff, 0xc0, 0xcb],
plum: [0xdd, 0xa0, 0xdd],
powderblue: [0xb0, 0xe0, 0xe6],
purple: [0x80, 0x00, 0x80],
rebeccapurple: [0x66, 0x33, 0x99],
red: [0xff, 0x00, 0x00],
rosybrown: [0xbc, 0x8f, 0x8f],
royalblue: [0x41, 0x69, 0xe1],
saddlebrown: [0x8b, 0x45, 0x13],
salmon: [0xfa, 0x80, 0x72],
sandybrown: [0xf4, 0xa4, 0x60],
seagreen: [0x2e, 0x8b, 0x57],
seashell: [0xff, 0xf5, 0xee],
sienna: [0xa0, 0x52, 0x2d],
silver: [0xc0, 0xc0, 0xc0],
skyblue: [0x87, 0xce, 0xeb],
slateblue: [0x6a, 0x5a, 0xcd],
slategray: [0x70, 0x80, 0x90],
slategrey: [0x70, 0x80, 0x90],
snow: [0xff, 0xfa, 0xfa],
springgreen: [0x00, 0xff, 0x7f],
steelblue: [0x46, 0x82, 0xb4],
tan: [0xd2, 0xb4, 0x8c],
teal: [0x00, 0x80, 0x80],
thistle: [0xd8, 0xbf, 0xd8],
tomato: [0xff, 0x63, 0x47],
turquoise: [0x40, 0xe0, 0xd0],
violet: [0xee, 0x82, 0xee],
wheat: [0xf5, 0xde, 0xb3],
white: [0xff, 0xff, 0xff],
whitesmoke: [0xf5, 0xf5, 0xf5],
yellow: [0xff, 0xff, 0x00],
yellowgreen: [0x9a, 0xcd, 0x32]
} as const satisfies {
[key: string]: ReadonlyTriColorChannels;
};

View File

@ -0,0 +1,910 @@
/**
* parse
*/
import { convertHexToRgb, convertHexToXyz } from '../converters/convert-hex';
import {
transformMatrix,
transformRgbToLinearRgb,
transformRgbToXyz
} from '../matrix/transform';
import {
ComputedColorChannels,
Options,
MatchedRegExp,
SpecifiedColorChannels,
StringColorChannels,
StringColorSpacedChannels,
TriColorChannels
} from '../typedef';
import { isString } from '../utils/common';
import {
angleToDeg,
parseAlpha,
resolveInvalidColorValue,
roundToPrecision
} from '../utils/util';
/* constants */
import {
D50,
MATRIX_A98_TO_XYZ,
MATRIX_D50_TO_D65,
MATRIX_D65_TO_D50,
MATRIX_LMS_TO_XYZ,
MATRIX_L_RGB_TO_XYZ,
MATRIX_OKLAB_TO_LMS,
MATRIX_P3_TO_XYZ,
MATRIX_PROPHOTO_TO_XYZ_D50,
MATRIX_REC2020_TO_XYZ
} from '../matrix/matrix';
import {
DEC,
DEG,
DEG_HALF,
DOZ,
DUO,
HEX,
LAB_A,
LAB_B,
LAB_EPSILON,
LAB_KAPPA,
LAB_L,
MAX_PCT,
MAX_RGB,
NONE,
OCT,
POW_CUBE,
POW_SQR,
SYN_COLOR_TYPE,
SYN_FN_COLOR,
SYN_HSL,
SYN_HSL_LV3,
SYN_LCH,
SYN_MOD,
SYN_RGB_LV3,
TRIA,
VAL_COMP,
VAL_MIX,
VAL_SPEC
} from '../utils/constant';
import { NAMED_COLORS } from './named-color';
/* regexp */
const REG_COLOR = new RegExp(`^(?:${SYN_COLOR_TYPE})$`);
const REG_CURRENT = /^currentColor$/i;
const REG_FN_COLOR = new RegExp(`^color\\(\\s*(${SYN_FN_COLOR})\\s*\\)$`);
const REG_HSL = new RegExp(`^hsla?\\(\\s*(${SYN_HSL}|${SYN_HSL_LV3})\\s*\\)$`);
const REG_HWB = new RegExp(`^hwb\\(\\s*(${SYN_HSL})\\s*\\)$`);
const REG_LAB = new RegExp(`^lab\\(\\s*(${SYN_MOD})\\s*\\)$`);
const REG_LCH = new RegExp(`^lch\\(\\s*(${SYN_LCH})\\s*\\)$`);
const REG_OKLAB = new RegExp(`^oklab\\(\\s*(${SYN_MOD})\\s*\\)$`);
const REG_OKLCH = new RegExp(`^oklch\\(\\s*(${SYN_LCH})\\s*\\)$`);
const REG_SPEC = /^(?:specifi|comput)edValue$/;
const REG_PARSE_RGB = new RegExp(
`^rgba?\\(\\s*(${SYN_MOD}|${SYN_RGB_LV3})\\s*\\)$`
);
/**
* parse rgb()
* @param value - rgb color value
* @param opt - options
* @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', null
*/
export const parseRgb = (
value: string,
opt: Options = {}
): SpecifiedColorChannels | string | null => {
if (isString(value)) {
value = value.toLowerCase().trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { format = '', nullable = false } = opt;
if (!REG_PARSE_RGB.test(value)) {
const res = resolveInvalidColorValue(format, nullable);
if (res === null) {
return null;
} else if (isString(res)) {
return res as string;
}
return res as SpecifiedColorChannels;
}
const [, val] = value.match(REG_PARSE_RGB) as MatchedRegExp;
const [v1, v2, v3, v4 = ''] = val.match(/[^\s,/]+/g) as StringColorChannels;
let r, g, b;
if (v1 === NONE) {
r = 0;
} else {
if (v1.endsWith('%')) {
r = (parseFloat(v1) * MAX_RGB) / MAX_PCT;
} else {
r = parseFloat(v1);
}
r = Math.min(Math.max(roundToPrecision(r, OCT), 0), MAX_RGB);
}
if (v2 === NONE) {
g = 0;
} else {
if (v2.endsWith('%')) {
g = (parseFloat(v2) * MAX_RGB) / MAX_PCT;
} else {
g = parseFloat(v2);
}
g = Math.min(Math.max(roundToPrecision(g, OCT), 0), MAX_RGB);
}
if (v3 === NONE) {
b = 0;
} else {
if (v3.endsWith('%')) {
b = (parseFloat(v3) * MAX_RGB) / MAX_PCT;
} else {
b = parseFloat(v3);
}
b = Math.min(Math.max(roundToPrecision(b, OCT), 0), MAX_RGB);
}
const alpha = parseAlpha(v4);
return ['rgb', r, g, b, format === VAL_MIX && v4 === NONE ? NONE : alpha];
};
/**
* parse hsl()
* @param value - hsl color value
* @param opt - options
* @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', null
*/
export const parseHsl = (
value: string,
opt: Options = {}
): SpecifiedColorChannels | string | null => {
if (isString(value)) {
value = value.trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { format = '', nullable = false } = opt;
if (!REG_HSL.test(value)) {
const res = resolveInvalidColorValue(format, nullable);
if (res === null) {
return null;
} else if (isString(res)) {
return res as string;
}
return res as SpecifiedColorChannels;
}
const [, val] = value.match(REG_HSL) as MatchedRegExp;
const [v1, v2, v3, v4 = ''] = val.match(/[^\s,/]+/g) as StringColorChannels;
let h, s, l;
if (v1 === NONE) {
h = 0;
} else {
h = angleToDeg(v1);
}
if (v2 === NONE) {
s = 0;
} else {
s = Math.min(Math.max(parseFloat(v2), 0), MAX_PCT);
}
if (v3 === NONE) {
l = 0;
} else {
l = Math.min(Math.max(parseFloat(v3), 0), MAX_PCT);
}
const alpha = parseAlpha(v4);
if (format === 'hsl') {
return [
format,
v1 === NONE ? v1 : h,
v2 === NONE ? v2 : s,
v3 === NONE ? v3 : l,
v4 === NONE ? v4 : alpha
];
}
h = (h / DEG) * DOZ;
l /= MAX_PCT;
const sa = (s / MAX_PCT) * Math.min(l, 1 - l);
const rk = h % DOZ;
const gk = (8 + h) % DOZ;
const bk = (4 + h) % DOZ;
const r = l - sa * Math.max(-1, Math.min(rk - TRIA, TRIA ** POW_SQR - rk, 1));
const g = l - sa * Math.max(-1, Math.min(gk - TRIA, TRIA ** POW_SQR - gk, 1));
const b = l - sa * Math.max(-1, Math.min(bk - TRIA, TRIA ** POW_SQR - bk, 1));
return [
'rgb',
Math.min(Math.max(roundToPrecision(r * MAX_RGB, OCT), 0), MAX_RGB),
Math.min(Math.max(roundToPrecision(g * MAX_RGB, OCT), 0), MAX_RGB),
Math.min(Math.max(roundToPrecision(b * MAX_RGB, OCT), 0), MAX_RGB),
alpha
];
};
/**
* parse hwb()
* @param value - hwb color value
* @param opt - options
* @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', null
*/
export const parseHwb = (
value: string,
opt: Options = {}
): SpecifiedColorChannels | string | null => {
if (isString(value)) {
value = value.trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { format = '', nullable = false } = opt;
if (!REG_HWB.test(value)) {
const res = resolveInvalidColorValue(format, nullable);
if (res === null) {
return null;
} else if (isString(res)) {
return res as string;
}
return res as SpecifiedColorChannels;
}
const [, val] = value.match(REG_HWB) as MatchedRegExp;
const [v1, v2, v3, v4 = ''] = val.match(/[^\s,/]+/g) as StringColorChannels;
let h, wh, bk;
if (v1 === NONE) {
h = 0;
} else {
h = angleToDeg(v1);
}
if (v2 === NONE) {
wh = 0;
} else {
wh = Math.min(Math.max(parseFloat(v2), 0), MAX_PCT) / MAX_PCT;
}
if (v3 === NONE) {
bk = 0;
} else {
bk = Math.min(Math.max(parseFloat(v3), 0), MAX_PCT) / MAX_PCT;
}
const alpha = parseAlpha(v4);
if (format === 'hwb') {
return [
format,
v1 === NONE ? v1 : h,
v2 === NONE ? v2 : wh * MAX_PCT,
v3 === NONE ? v3 : bk * MAX_PCT,
v4 === NONE ? v4 : alpha
];
}
if (wh + bk >= 1) {
const v = roundToPrecision((wh / (wh + bk)) * MAX_RGB, OCT);
return ['rgb', v, v, v, alpha];
}
const factor = (1 - wh - bk) / MAX_RGB;
let [, r, g, b] = parseHsl(`hsl(${h} 100 50)`) as ComputedColorChannels;
r = roundToPrecision((r * factor + wh) * MAX_RGB, OCT);
g = roundToPrecision((g * factor + wh) * MAX_RGB, OCT);
b = roundToPrecision((b * factor + wh) * MAX_RGB, OCT);
return [
'rgb',
Math.min(Math.max(r, 0), MAX_RGB),
Math.min(Math.max(g, 0), MAX_RGB),
Math.min(Math.max(b, 0), MAX_RGB),
alpha
];
};
/**
* parse lab()
* @param value - lab color value
* @param opt - options
* @returns parsed color
* - [xyz-d50, x, y, z, alpha], ['lab', l, a, b, alpha], '(empty)', null
*/
export const parseLab = (
value: string,
opt: Options = {}
): SpecifiedColorChannels | string | null => {
if (isString(value)) {
value = value.trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { format = '', nullable = false } = opt;
if (!REG_LAB.test(value)) {
const res = resolveInvalidColorValue(format, nullable);
if (res === null) {
return null;
} else if (isString(res)) {
return res as string;
}
return res as SpecifiedColorChannels;
}
const COEF_PCT = 1.25;
const COND_POW = 8;
const [, val] = value.match(REG_LAB) as MatchedRegExp;
const [v1, v2, v3, v4 = ''] = val.match(/[^\s,/]+/g) as StringColorChannels;
let l, a, b;
if (v1 === NONE) {
l = 0;
} else {
if (v1.endsWith('%')) {
l = parseFloat(v1);
if (l > MAX_PCT) {
l = MAX_PCT;
}
} else {
l = parseFloat(v1);
}
if (l < 0) {
l = 0;
}
}
if (v2 === NONE) {
a = 0;
} else {
a = v2.endsWith('%') ? parseFloat(v2) * COEF_PCT : parseFloat(v2);
}
if (v3 === NONE) {
b = 0;
} else {
b = v3.endsWith('%') ? parseFloat(v3) * COEF_PCT : parseFloat(v3);
}
const alpha = parseAlpha(v4);
if (REG_SPEC.test(format)) {
return [
'lab',
v1 === NONE ? v1 : roundToPrecision(l, HEX),
v2 === NONE ? v2 : roundToPrecision(a, HEX),
v3 === NONE ? v3 : roundToPrecision(b, HEX),
v4 === NONE ? v4 : alpha
];
}
const fl = (l + HEX) / LAB_L;
const fa = a / LAB_A + fl;
const fb = fl - b / LAB_B;
const powFl = Math.pow(fl, POW_CUBE);
const powFa = Math.pow(fa, POW_CUBE);
const powFb = Math.pow(fb, POW_CUBE);
const xyz = [
powFa > LAB_EPSILON ? powFa : (fa * LAB_L - HEX) / LAB_KAPPA,
l > COND_POW ? powFl : l / LAB_KAPPA,
powFb > LAB_EPSILON ? powFb : (fb * LAB_L - HEX) / LAB_KAPPA
];
const [x, y, z] = xyz.map(
(val, i) => val * (D50[i] as number)
) as TriColorChannels;
return [
'xyz-d50',
roundToPrecision(x, HEX),
roundToPrecision(y, HEX),
roundToPrecision(z, HEX),
alpha
];
};
/**
* parse lch()
* @param value - lch color value
* @param opt - options
* @returns parsed color
* - ['xyz-d50', x, y, z, alpha], ['lch', l, c, h, alpha], '(empty)', null
*/
export const parseLch = (
value: string,
opt: Options = {}
): SpecifiedColorChannels | string | null => {
if (isString(value)) {
value = value.trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { format = '', nullable = false } = opt;
if (!REG_LCH.test(value)) {
const res = resolveInvalidColorValue(format, nullable);
if (res === null) {
return null;
} else if (isString(res)) {
return res as string;
}
return res as SpecifiedColorChannels;
}
const COEF_PCT = 1.5;
const [, val] = value.match(REG_LCH) as MatchedRegExp;
const [v1, v2, v3, v4 = ''] = val.match(/[^\s,/]+/g) as StringColorChannels;
let l, c, h;
if (v1 === NONE) {
l = 0;
} else {
l = parseFloat(v1);
if (l < 0) {
l = 0;
}
}
if (v2 === NONE) {
c = 0;
} else {
c = v2.endsWith('%') ? parseFloat(v2) * COEF_PCT : parseFloat(v2);
}
if (v3 === NONE) {
h = 0;
} else {
h = angleToDeg(v3);
}
const alpha = parseAlpha(v4);
if (REG_SPEC.test(format)) {
return [
'lch',
v1 === NONE ? v1 : roundToPrecision(l, HEX),
v2 === NONE ? v2 : roundToPrecision(c, HEX),
v3 === NONE ? v3 : roundToPrecision(h, HEX),
v4 === NONE ? v4 : alpha
];
}
const a = c * Math.cos((h * Math.PI) / DEG_HALF);
const b = c * Math.sin((h * Math.PI) / DEG_HALF);
const [, x, y, z] = parseLab(`lab(${l} ${a} ${b})`) as ComputedColorChannels;
return [
'xyz-d50',
roundToPrecision(x, HEX),
roundToPrecision(y, HEX),
roundToPrecision(z, HEX),
alpha as number
];
};
/**
* parse oklab()
* @param value - oklab color value
* @param opt - options
* @returns parsed color
* - ['xyz-d65', x, y, z, alpha], ['oklab', l, a, b, alpha], '(empty)', null
*/
export const parseOklab = (
value: string,
opt: Options = {}
): SpecifiedColorChannels | string | null => {
if (isString(value)) {
value = value.trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { format = '', nullable = false } = opt;
if (!REG_OKLAB.test(value)) {
const res = resolveInvalidColorValue(format, nullable);
if (res === null) {
return null;
} else if (isString(res)) {
return res as string;
}
return res as SpecifiedColorChannels;
}
const COEF_PCT = 0.4;
const [, val] = value.match(REG_OKLAB) as MatchedRegExp;
const [v1, v2, v3, v4 = ''] = val.match(/[^\s,/]+/g) as StringColorChannels;
let l, a, b;
if (v1 === NONE) {
l = 0;
} else {
l = v1.endsWith('%') ? parseFloat(v1) / MAX_PCT : parseFloat(v1);
if (l < 0) {
l = 0;
}
}
if (v2 === NONE) {
a = 0;
} else if (v2.endsWith('%')) {
a = (parseFloat(v2) * COEF_PCT) / MAX_PCT;
} else {
a = parseFloat(v2);
}
if (v3 === NONE) {
b = 0;
} else if (v3.endsWith('%')) {
b = (parseFloat(v3) * COEF_PCT) / MAX_PCT;
} else {
b = parseFloat(v3);
}
const alpha = parseAlpha(v4);
if (REG_SPEC.test(format)) {
return [
'oklab',
v1 === NONE ? v1 : roundToPrecision(l, HEX),
v2 === NONE ? v2 : roundToPrecision(a, HEX),
v3 === NONE ? v3 : roundToPrecision(b, HEX),
v4 === NONE ? v4 : alpha
];
}
const lms = transformMatrix(MATRIX_OKLAB_TO_LMS, [l, a, b]);
const xyzLms = lms.map((c: number) =>
Math.pow(c, POW_CUBE)
) as TriColorChannels;
const [x, y, z] = transformMatrix(MATRIX_LMS_TO_XYZ, xyzLms, true);
return [
'xyz-d65',
roundToPrecision(x, HEX),
roundToPrecision(y, HEX),
roundToPrecision(z, HEX),
alpha as number
];
};
/**
* parse oklch()
* @param value - oklch color value
* @param opt - options
* @returns parsed color
* - ['xyz-d65', x, y, z, alpha], ['oklch', l, c, h, alpha], '(empty)', null
*/
export const parseOklch = (
value: string,
opt: Options = {}
): SpecifiedColorChannels | string | null => {
if (isString(value)) {
value = value.trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { format = '', nullable = false } = opt;
if (!REG_OKLCH.test(value)) {
const res = resolveInvalidColorValue(format, nullable);
if (res === null) {
return null;
} else if (isString(res)) {
return res as string;
}
return res as SpecifiedColorChannels;
}
const COEF_PCT = 0.4;
const [, val] = value.match(REG_OKLCH) as MatchedRegExp;
const [v1, v2, v3, v4 = ''] = val.match(/[^\s,/]+/g) as StringColorChannels;
let l, c, h;
if (v1 === NONE) {
l = 0;
} else {
l = v1.endsWith('%') ? parseFloat(v1) / MAX_PCT : parseFloat(v1);
if (l < 0) {
l = 0;
}
}
if (v2 === NONE) {
c = 0;
} else {
if (v2.endsWith('%')) {
c = (parseFloat(v2) * COEF_PCT) / MAX_PCT;
} else {
c = parseFloat(v2);
}
if (c < 0) {
c = 0;
}
}
if (v3 === NONE) {
h = 0;
} else {
h = angleToDeg(v3);
}
const alpha = parseAlpha(v4);
if (REG_SPEC.test(format)) {
return [
'oklch',
v1 === NONE ? v1 : roundToPrecision(l, HEX),
v2 === NONE ? v2 : roundToPrecision(c, HEX),
v3 === NONE ? v3 : roundToPrecision(h, HEX),
v4 === NONE ? v4 : alpha
];
}
const a = c * Math.cos((h * Math.PI) / DEG_HALF);
const b = c * Math.sin((h * Math.PI) / DEG_HALF);
const lms = transformMatrix(MATRIX_OKLAB_TO_LMS, [l, a, b]);
const xyzLms = lms.map((cc: number) =>
Math.pow(cc, POW_CUBE)
) as TriColorChannels;
const [x, y, z] = transformMatrix(MATRIX_LMS_TO_XYZ, xyzLms, true);
return [
'xyz-d65',
roundToPrecision(x, HEX),
roundToPrecision(y, HEX),
roundToPrecision(z, HEX),
alpha
];
};
/**
* parse color()
* @param value - color function value
* @param opt - options
* @returns parsed color
* - ['xyz-(d50|d65)', x, y, z, alpha], [cs, r, g, b, alpha], '(empty)', null
*/
export const parseColorFunc = (
value: string,
opt: Options = {}
): SpecifiedColorChannels | string | null => {
if (isString(value)) {
value = value.trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { colorSpace = '', d50 = false, format = '', nullable = false } = opt;
if (!REG_FN_COLOR.test(value)) {
const res = resolveInvalidColorValue(format, nullable);
if (res === null) {
return null;
} else if (isString(res)) {
return res as string;
}
return res as SpecifiedColorChannels;
}
const [, val] = value.match(REG_FN_COLOR) as MatchedRegExp;
let [cs, v1, v2, v3, v4 = ''] = val.match(
/[^\s,/]+/g
) as StringColorSpacedChannels;
let r, g, b;
if (cs === 'xyz') {
cs = 'xyz-d65';
}
if (v1 === NONE) {
r = 0;
} else {
r = v1.endsWith('%') ? parseFloat(v1) / MAX_PCT : parseFloat(v1);
}
if (v2 === NONE) {
g = 0;
} else {
g = v2.endsWith('%') ? parseFloat(v2) / MAX_PCT : parseFloat(v2);
}
if (v3 === NONE) {
b = 0;
} else {
b = v3.endsWith('%') ? parseFloat(v3) / MAX_PCT : parseFloat(v3);
}
const alpha = parseAlpha(v4);
if (REG_SPEC.test(format) || (format === VAL_MIX && cs === colorSpace)) {
return [
cs,
v1 === NONE ? v1 : roundToPrecision(r, DEC),
v2 === NONE ? v2 : roundToPrecision(g, DEC),
v3 === NONE ? v3 : roundToPrecision(b, DEC),
v4 === NONE ? v4 : alpha
];
}
let x = 0;
let y = 0;
let z = 0;
// srgb-linear
if (cs === 'srgb-linear') {
[x, y, z] = transformMatrix(MATRIX_L_RGB_TO_XYZ, [r, g, b]);
if (d50) {
[x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);
}
// display-p3
} else if (cs === 'display-p3') {
const linearRgb = transformRgbToLinearRgb([
r * MAX_RGB,
g * MAX_RGB,
b * MAX_RGB
]);
[x, y, z] = transformMatrix(MATRIX_P3_TO_XYZ, linearRgb);
if (d50) {
[x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);
}
// rec2020
} else if (cs === 'rec2020') {
const ALPHA = 1.09929682680944;
const BETA = 0.018053968510807;
const REC_COEF = 0.45;
const rgb = [r, g, b].map(c => {
let cl;
if (c < BETA * REC_COEF * DEC) {
cl = c / (REC_COEF * DEC);
} else {
cl = Math.pow((c + ALPHA - 1) / ALPHA, 1 / REC_COEF);
}
return cl;
}) as TriColorChannels;
[x, y, z] = transformMatrix(MATRIX_REC2020_TO_XYZ, rgb);
if (d50) {
[x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);
}
// a98-rgb
} else if (cs === 'a98-rgb') {
const POW_A98 = 563 / 256;
const rgb = [r, g, b].map(c => {
const cl = Math.pow(c, POW_A98);
return cl;
}) as TriColorChannels;
[x, y, z] = transformMatrix(MATRIX_A98_TO_XYZ, rgb);
if (d50) {
[x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);
}
// prophoto-rgb
} else if (cs === 'prophoto-rgb') {
const POW_PROPHOTO = 1.8;
const rgb = [r, g, b].map(c => {
let cl;
if (c > 1 / (HEX * DUO)) {
cl = Math.pow(c, POW_PROPHOTO);
} else {
cl = c / HEX;
}
return cl;
}) as TriColorChannels;
[x, y, z] = transformMatrix(MATRIX_PROPHOTO_TO_XYZ_D50, rgb);
if (!d50) {
[x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [x, y, z], true);
}
// xyz, xyz-d50, xyz-d65
} else if (/^xyz(?:-d(?:50|65))?$/.test(cs)) {
[x, y, z] = [r, g, b];
if (cs === 'xyz-d50') {
if (!d50) {
[x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [x, y, z]);
}
} else if (d50) {
[x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);
}
// srgb
} else {
[x, y, z] = transformRgbToXyz([r * MAX_RGB, g * MAX_RGB, b * MAX_RGB]);
if (d50) {
[x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);
}
}
return [
d50 ? 'xyz-d50' : 'xyz-d65',
roundToPrecision(x, HEX),
roundToPrecision(y, HEX),
roundToPrecision(z, HEX),
format === VAL_MIX && v4 === NONE ? v4 : alpha
];
};
/**
* parse color value
* @param value - CSS color value
* @param opt - options
* @returns parsed color
* - ['xyz-(d50|d65)', x, y, z, alpha], ['rgb', r, g, b, alpha]
* - value, '(empty)', null
*/
export const parseColorValue = (
value: string,
opt: Options = {}
): SpecifiedColorChannels | string | null => {
if (isString(value)) {
value = value.toLowerCase().trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { d50 = false, format = '', nullable = false } = opt;
if (!REG_COLOR.test(value)) {
const res = resolveInvalidColorValue(format, nullable);
if (res === null) {
return null;
} else if (isString(res)) {
return res as string;
}
return res as SpecifiedColorChannels;
}
let x = 0;
let y = 0;
let z = 0;
let alpha = 0;
// complement currentcolor as a missing color
if (REG_CURRENT.test(value)) {
if (format === VAL_COMP) {
return ['rgb', 0, 0, 0, 0];
}
if (format === VAL_SPEC) {
return value;
}
// named-color
} else if (/^[a-z]+$/.test(value)) {
if (Object.hasOwn(NAMED_COLORS, value)) {
if (format === VAL_SPEC) {
return value;
}
const [r, g, b] = NAMED_COLORS[
value as keyof typeof NAMED_COLORS
] as TriColorChannels;
alpha = 1;
if (format === VAL_COMP) {
return ['rgb', r, g, b, alpha];
}
[x, y, z] = transformRgbToXyz([r, g, b], true);
if (d50) {
[x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);
}
} else {
switch (format) {
case VAL_COMP: {
if (nullable && value !== 'transparent') {
return null;
}
return ['rgb', 0, 0, 0, 0];
}
case VAL_SPEC: {
if (value === 'transparent') {
return value;
}
return '';
}
case VAL_MIX: {
if (value === 'transparent') {
return ['rgb', 0, 0, 0, 0];
}
return null;
}
default:
}
}
// hex-color
} else if (value[0] === '#') {
if (REG_SPEC.test(format)) {
const rgb = convertHexToRgb(value);
return ['rgb', ...rgb];
}
[x, y, z, alpha] = convertHexToXyz(value);
if (d50) {
[x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);
}
// lab()
} else if (value.startsWith('lab')) {
if (REG_SPEC.test(format)) {
return parseLab(value, opt);
}
[, x, y, z, alpha] = parseLab(value) as ComputedColorChannels;
if (!d50) {
[x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [x, y, z], true);
}
// lch()
} else if (value.startsWith('lch')) {
if (REG_SPEC.test(format)) {
return parseLch(value, opt);
}
[, x, y, z, alpha] = parseLch(value) as ComputedColorChannels;
if (!d50) {
[x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [x, y, z], true);
}
// oklab()
} else if (value.startsWith('oklab')) {
if (REG_SPEC.test(format)) {
return parseOklab(value, opt);
}
[, x, y, z, alpha] = parseOklab(value) as ComputedColorChannels;
if (d50) {
[x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);
}
// oklch()
} else if (value.startsWith('oklch')) {
if (REG_SPEC.test(format)) {
return parseOklch(value, opt);
}
[, x, y, z, alpha] = parseOklch(value) as ComputedColorChannels;
if (d50) {
[x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);
}
} else {
let r, g, b;
// hsl()
if (value.startsWith('hsl')) {
[, r, g, b, alpha] = parseHsl(value) as ComputedColorChannels;
// hwb()
} else if (value.startsWith('hwb')) {
[, r, g, b, alpha] = parseHwb(value) as ComputedColorChannels;
// rgb()
} else {
[, r, g, b, alpha] = parseRgb(value, opt) as ComputedColorChannels;
}
if (REG_SPEC.test(format)) {
return ['rgb', Math.round(r), Math.round(g), Math.round(b), alpha];
}
[x, y, z] = transformRgbToXyz([r, g, b]);
if (d50) {
[x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [x, y, z], true);
}
}
return [
d50 ? 'xyz-d50' : 'xyz-d65',
roundToPrecision(x, HEX),
roundToPrecision(y, HEX),
roundToPrecision(z, HEX),
alpha
];
};

View File

@ -0,0 +1,673 @@
/**
* relative-color
*/
import { SyntaxFlag, color as colorParser } from '@csstools/css-color-parser';
import {
ComponentValue,
parseComponentValue
} from '@csstools/css-parser-algorithms';
import { CSSToken, TokenType, tokenize } from '@csstools/css-tokenizer';
import { convertColorToRgb } from '../converters/convert-color';
import {
ColorChannels,
MatchedRegExp,
Options,
StringColorChannels
} from '../typedef';
import { createCacheKey, getCache, setCache } from '../utils/cache';
import { isString, isStringOrNumber } from '../utils/common';
import { resolveDimension, serializeCalc } from '../utils/css-calc-var';
import { roundToPrecision, splitValue } from '../utils/util';
/* constants */
import {
CS_LAB,
CS_LCH,
DEC,
FN_LIGHT_DARK,
FN_REL,
FN_REL_CAPT,
FN_VAR,
HEX,
MAX_PCT,
MAX_RGB,
NONE,
OCT,
SYN_COLOR_TYPE,
SYN_FN_MATH_START,
SYN_FN_VAR,
SYN_MIX,
VAL_SPEC
} from '../utils/constant';
import { NAMED_COLORS } from './named-color';
const NAMESPACE = 'relative-color';
const {
CloseParen: PAREN_CLOSE,
Comment: COMMENT,
Delim: DELIM,
Dimension: DIM,
EOF,
Function: FUNC,
Ident: IDENT,
Number: NUM,
OpenParen: PAREN_OPEN,
Percentage: PCT,
Whitespace: W_SPACE
} = TokenType;
const { HasNoneKeywords: KEY_NONE } = SyntaxFlag;
/* color channels */
const colorChannels = new Map([
['color', ['r', 'g', 'b', 'alpha']],
['hsl', ['h', 's', 'l', 'alpha']],
['hsla', ['h', 's', 'l', 'alpha']],
['hwb', ['h', 'w', 'b', 'alpha']],
['lab', ['l', 'a', 'b', 'alpha']],
['lch', ['l', 'c', 'h', 'alpha']],
['oklab', ['l', 'a', 'b', 'alpha']],
['oklch', ['l', 'c', 'h', 'alpha']],
['rgb', ['r', 'g', 'b', 'alpha']],
['rgba', ['r', 'g', 'b', 'alpha']]
]);
/* type definitions */
/**
* NumberOrStringColorChannels - color channel
*/
type NumberOrStringColorChannels = ColorChannels & StringColorChannels;
/* regexp */
const REG_COLOR_CAPT = new RegExp(
`^${FN_REL}(${SYN_COLOR_TYPE}|${SYN_MIX})\\s+`
);
const REG_CS_HSL = /(?:hsla?|hwb)$/;
const REG_CS_CIE = new RegExp(`^(?:${CS_LAB}|${CS_LCH})$`);
const REG_FN_CALC_SUM = /^(?:abs|sig?n|cos|tan)\(/;
const REG_FN_MATH_START = new RegExp(SYN_FN_MATH_START);
const REG_FN_REL = new RegExp(FN_REL);
const REG_FN_REL_CAPT = new RegExp(`^${FN_REL_CAPT}`);
const REG_FN_REL_START = new RegExp(`^${FN_REL}`);
const REG_FN_VAR = new RegExp(SYN_FN_VAR);
/**
* resolve relative color channels
* @param tokens - tokens
* @param [opt] - options
* @param [opt.currentColor]
* - color to use for `currentcolor` keyword
* - if omitted, it will be treated as a missing color
* i.e. `rgb(none none none / none)`
* @param [opt.customProperty]
* - custom properties
* - pair of `--` prefixed property name and value,
* e.g. `customProperty: { '--some-color': '#0000ff' }`
* - and/or `callback` function to get the value of the custom property,
* e.g. `customProperty: { callback: someDeclaration.getPropertyValue }`
* @param [opt.dimension]
* - dimension, convert relative length to pixels
* - pair of unit and it's value as a number in pixels,
* e.g. `dimension: { em: 12, rem: 16, vw: 10.26 }`
* - and/or `callback` function to get the value as a number in pixels,
* e.g. `dimension: { callback: convertUnitToPixel }`
* @param [opt.format]
* - output format, one of below
* - `computedValue` (default), [computed value][139] of the color
* - `specifiedValue`, [specified value][140] of the color
* - `hex`, hex color notation, i.e. `rrggbb`
* - `hexAlpha`, hex color notation with alpha channel, i.e. `#rrggbbaa`
* @returns
* - one of rgba?(), #rrggbb(aa)?, color-name, '(empty-string)',
* color(color-space r g b / alpha), color(color-space x y z / alpha),
* lab(l a b / alpha), lch(l c h / alpha), oklab(l a b / alpha),
* oklch(l c h / alpha), null
* - in `computedValue`, values are numbers, however `rgb()` values are
* integers
* - in `specifiedValue`, returns `empty string` for unknown and/or invalid
* color
* - in `hex`, returns `null` for `transparent`, and also returns `null` if
* any of `r`, `g`, `b`, `alpha` is not a number
* - in `hexAlpha`, returns `#00000000` for `transparent`,
* however returns `null` if any of `r`, `g`, `b`, `alpha` is not a number
*/
export function resolveColorChannels(
tokens: CSSToken[],
opt: Options = {}
): NumberOrStringColorChannels | null {
if (!Array.isArray(tokens)) {
throw new TypeError(`${tokens} is not an array.`);
}
const { colorSpace = '', format = '' } = opt;
const colorChannel = colorChannels.get(colorSpace);
// invalid color channel
if (!colorChannel) {
return null;
}
const mathFunc = new Set();
const channels: [
(number | string)[],
(number | string)[],
(number | string)[],
(number | string)[]
] = [[], [], [], []];
let i = 0;
let nest = 0;
let func = '';
let precededPct = false;
for (const token of tokens) {
if (!Array.isArray(token)) {
throw new TypeError(`${token} is not an array.`);
}
const [type, value, , , detail] = token as [
TokenType,
string,
number,
number,
{ value: string | number } | undefined
];
const channel = channels[i];
if (Array.isArray(channel)) {
switch (type) {
case DELIM: {
if (func) {
if (
(value === '+' || value === '-') &&
precededPct &&
!REG_FN_CALC_SUM.test(func)
) {
return null;
}
precededPct = false;
channel.push(value);
}
break;
}
case DIM: {
if (!func || !REG_FN_CALC_SUM.test(func)) {
return null;
}
const resolvedValue = resolveDimension(token, opt);
if (isString(resolvedValue)) {
channel.push(resolvedValue);
} else {
channel.push(value);
}
break;
}
case FUNC: {
channel.push(value);
func = value;
nest++;
if (REG_FN_MATH_START.test(value)) {
mathFunc.add(nest);
}
break;
}
case IDENT: {
// invalid channel key
if (!colorChannel.includes(value)) {
return null;
}
channel.push(value);
if (!func) {
i++;
}
break;
}
case NUM: {
channel.push(Number(detail?.value));
if (!func) {
i++;
}
break;
}
case PAREN_OPEN: {
channel.push(value);
nest++;
break;
}
case PAREN_CLOSE: {
if (func) {
const lastValue = channel.at(-1);
if (lastValue === ' ') {
channel[channel.length - 1] = value;
} else {
channel.push(value);
}
if (mathFunc.has(nest)) {
mathFunc.delete(nest);
}
nest--;
if (nest === 0) {
func = '';
i++;
}
}
break;
}
case PCT: {
if (!func) {
return null;
} else if (!REG_FN_CALC_SUM.test(func)) {
let lastValue: string | number | undefined;
for (let j = channel.length - 1; j >= 0; j--) {
if (channel[j] !== ' ') {
lastValue = channel[j];
break;
}
}
if (lastValue === '+' || lastValue === '-') {
return null;
} else if (lastValue === '*' || lastValue === '/') {
precededPct = false;
} else {
precededPct = true;
}
}
channel.push(Number(detail?.value) / MAX_PCT);
break;
}
case W_SPACE: {
if (channel.length && func) {
const lastValue = channel.at(-1);
if (typeof lastValue === 'number') {
channel.push(value);
} else if (
isString(lastValue) &&
!lastValue.endsWith('(') &&
lastValue !== ' '
) {
channel.push(value);
}
}
break;
}
default: {
if (type !== COMMENT && type !== EOF && func) {
channel.push(value);
}
}
}
}
}
const channelValues = [];
for (const channel of channels) {
if (channel.length === 1) {
const [resolvedValue] = channel;
if (isStringOrNumber(resolvedValue)) {
channelValues.push(resolvedValue);
}
} else if (channel.length) {
const resolvedValue = serializeCalc(channel.join(''), {
format
});
channelValues.push(resolvedValue);
}
}
return channelValues as NumberOrStringColorChannels;
}
/**
* extract origin color
* @param value - CSS color value
* @param opt - options
* @param resolver - resolver function
* @returns origin color value
*/
export function extractOriginColor(
value: string,
opt: Options = {},
resolver: (v: string, o?: Options) => string | null = () => null
): string | null {
const { colorScheme = 'normal', currentColor = '', format = '' } = opt;
if (isString(value)) {
value = value.toLowerCase().trim();
if (!value) {
return null;
}
if (!REG_FN_REL_START.test(value)) {
return value;
}
} else {
return null;
}
const cacheKey: string = createCacheKey(
{
namespace: NAMESPACE,
name: 'extractOriginColor',
value
},
opt
);
const cachedResult = getCache(cacheKey);
if (cachedResult !== false) {
return cachedResult.item as string | null;
}
if (/currentcolor/.test(value)) {
if (currentColor) {
value = value.replace(/currentcolor/g, currentColor);
} else {
setCache(cacheKey, null);
return null;
}
}
const matchRelFunc = value.match(REG_FN_REL_CAPT);
const [, colorSpace] = matchRelFunc as MatchedRegExp;
const options = {
...opt,
colorSpace
};
if (value.includes(FN_LIGHT_DARK)) {
const colorParts = value
.replace(new RegExp(`^${colorSpace}\\(`), '')
.replace(/\)$/, '');
const matchedColorParts = splitValue(colorParts);
const [, originColor] = matchedColorParts as MatchedRegExp;
const specifiedOriginColor = resolver(originColor, {
colorScheme,
format: VAL_SPEC
}) as string;
if (!specifiedOriginColor) {
setCache(cacheKey, null);
return null;
}
if (format === VAL_SPEC) {
value = value.replace(originColor, specifiedOriginColor);
} else {
const resolvedOriginColor = resolver(specifiedOriginColor, options);
if (isString(resolvedOriginColor)) {
value = value.replace(originColor, resolvedOriginColor);
} else {
setCache(cacheKey, null);
return null;
}
}
}
if (REG_COLOR_CAPT.test(value)) {
const [, originColor] = value.match(REG_COLOR_CAPT) as MatchedRegExp;
const [, restValue] = value.split(originColor) as MatchedRegExp;
if (/^[a-z]+$/.test(originColor)) {
if (
!/^transparent$/.test(originColor) &&
!Object.hasOwn(NAMED_COLORS, originColor)
) {
setCache(cacheKey, null);
return null;
}
} else if (format === VAL_SPEC) {
const resolvedOriginColor = resolver(originColor, options) as string;
value = value.replace(originColor, resolvedOriginColor);
}
if (format === VAL_SPEC) {
const tokens = tokenize({ css: restValue });
const channelValues = resolveColorChannels(tokens, options);
if (channelValues === null) {
setCache(cacheKey, null);
return null;
}
const [v1, v2, v3, v4] = channelValues;
let channelValue = '';
if (isStringOrNumber(v4)) {
channelValue = ` ${v1} ${v2} ${v3} / ${v4})`;
} else {
channelValue = ` ${channelValues.join(' ')})`;
}
if (restValue !== channelValue) {
value = value.replace(restValue, channelValue);
}
}
} else {
// nested relative color
const [, restValue] = value.split(REG_FN_REL_START) as MatchedRegExp;
const tokens = tokenize({ css: restValue });
const originColor: string[] = [];
let nest = 0;
let tokenIndex = 0;
for (const [type, tokenValue] of tokens) {
tokenIndex++;
switch (type) {
case FUNC:
case PAREN_OPEN: {
originColor.push(tokenValue);
nest++;
break;
}
case PAREN_CLOSE: {
const lastValue = originColor.at(-1);
if (lastValue === ' ') {
originColor[originColor.length - 1] = tokenValue;
} else {
originColor.push(tokenValue);
}
nest--;
break;
}
case W_SPACE: {
const lastValue = originColor.at(-1);
if (
isString(lastValue) &&
!lastValue.endsWith('(') &&
lastValue !== ' '
) {
originColor.push(tokenValue);
}
break;
}
default: {
if (type !== COMMENT && type !== EOF) {
originColor.push(tokenValue);
}
}
}
if (nest === 0) {
break;
}
}
const resolvedOriginColor = resolveRelativeColor(
originColor.join('').trim(),
options,
resolver
);
if (resolvedOriginColor === null) {
setCache(cacheKey, null);
return null;
}
const channelValues = resolveColorChannels(
tokens.slice(tokenIndex),
options
);
if (channelValues === null) {
setCache(cacheKey, null);
return null;
}
const [v1, v2, v3, v4] = channelValues;
let channelValue = '';
if (isStringOrNumber(v4)) {
channelValue = ` ${v1} ${v2} ${v3} / ${v4})`;
} else {
channelValue = ` ${channelValues.join(' ')})`;
}
value = value.replace(restValue, `${resolvedOriginColor}${channelValue}`);
}
setCache(cacheKey, value);
return value;
}
/**
* resolve relative color
* @param value - CSS relative color value
* @param opt - options
* @param resolver - resolver function
* @returns resolved value
*/
export function resolveRelativeColor(
value: string,
opt: Options = {},
resolver: (v: string, o?: Options) => string | null = () => null
): string | null {
const options = {
...opt
};
const { format = '' } = options;
if (isString(value)) {
if (REG_FN_VAR.test(value)) {
// var() must be resolved before resolveRelativeColor()
if (format !== VAL_SPEC) {
throw new SyntaxError(`Unexpected token ${FN_VAR} found.`);
}
return value;
} else if (!REG_FN_REL.test(value)) {
return value;
}
value = value.toLowerCase().trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const cacheKey: string = createCacheKey(
{
namespace: NAMESPACE,
name: 'resolveRelativeColor',
value
},
options
);
const cachedResult = getCache(cacheKey);
if (cachedResult !== false) {
return cachedResult.item as string | null;
}
const originColor = extractOriginColor(value, options, resolver);
if (originColor === null) {
setCache(cacheKey, null);
return null;
}
value = originColor;
if (format === VAL_SPEC) {
if (value.startsWith('rgba(')) {
value = value.replace('rgba(', 'rgb(');
} else if (value.startsWith('hsla(')) {
value = value.replace('hsla(', 'hsl(');
}
return value;
}
const tokens = tokenize({ css: value });
const components = parseComponentValue(tokens) as ComponentValue;
const parsedComponents = colorParser(components);
if (!parsedComponents) {
setCache(cacheKey, null);
return null;
}
const {
alpha: alphaComponent,
channels: channelsComponent,
colorNotation,
syntaxFlags
} = parsedComponents;
let alpha: number | string;
if (Number.isNaN(Number(alphaComponent))) {
if (syntaxFlags instanceof Set && syntaxFlags.has(KEY_NONE)) {
alpha = NONE;
} else {
alpha = 0;
}
} else {
alpha = roundToPrecision(Number(alphaComponent), OCT);
}
let v1: number | string;
let v2: number | string;
let v3: number | string;
[v1, v2, v3] = channelsComponent;
let resolvedValue;
if (REG_CS_CIE.test(colorNotation)) {
const hasNone = syntaxFlags instanceof Set && syntaxFlags.has(KEY_NONE);
if (Number.isNaN(v1)) {
if (hasNone) {
v1 = NONE;
} else {
v1 = 0;
}
} else {
v1 = roundToPrecision(v1, HEX);
}
if (Number.isNaN(v2)) {
if (hasNone) {
v2 = NONE;
} else {
v2 = 0;
}
} else {
v2 = roundToPrecision(v2, HEX);
}
if (Number.isNaN(v3)) {
if (hasNone) {
v3 = NONE;
} else {
v3 = 0;
}
} else {
v3 = roundToPrecision(v3, HEX);
}
if (alpha === 1) {
resolvedValue = `${colorNotation}(${v1} ${v2} ${v3})`;
} else {
resolvedValue = `${colorNotation}(${v1} ${v2} ${v3} / ${alpha})`;
}
} else if (REG_CS_HSL.test(colorNotation)) {
if (Number.isNaN(v1)) {
v1 = 0;
}
if (Number.isNaN(v2)) {
v2 = 0;
}
if (Number.isNaN(v3)) {
v3 = 0;
}
let [r, g, b] = convertColorToRgb(
`${colorNotation}(${v1} ${v2} ${v3} / ${alpha})`
) as ColorChannels;
r = roundToPrecision(r / MAX_RGB, DEC);
g = roundToPrecision(g / MAX_RGB, DEC);
b = roundToPrecision(b / MAX_RGB, DEC);
if (alpha === 1) {
resolvedValue = `color(srgb ${r} ${g} ${b})`;
} else {
resolvedValue = `color(srgb ${r} ${g} ${b} / ${alpha})`;
}
} else {
const cs = colorNotation === 'rgb' ? 'srgb' : colorNotation;
const hasNone = syntaxFlags instanceof Set && syntaxFlags.has(KEY_NONE);
if (Number.isNaN(v1)) {
if (hasNone) {
v1 = NONE;
} else {
v1 = 0;
}
} else {
v1 = roundToPrecision(v1, DEC);
}
if (Number.isNaN(v2)) {
if (hasNone) {
v2 = NONE;
} else {
v2 = 0;
}
} else {
v2 = roundToPrecision(v2, DEC);
}
if (Number.isNaN(v3)) {
if (hasNone) {
v3 = NONE;
} else {
v3 = 0;
}
} else {
v3 = roundToPrecision(v3, DEC);
}
if (alpha === 1) {
resolvedValue = `color(${cs} ${v1} ${v2} ${v3})`;
} else {
resolvedValue = `color(${cs} ${v1} ${v2} ${v3} / ${alpha})`;
}
}
setCache(cacheKey, resolvedValue);
return resolvedValue;
}

View File

@ -0,0 +1,584 @@
/**
* resolve-color
*/
import { convertHexToRgb, convertRgbToHex } from '../converters/convert-hex';
import { transformXyzD50ToRgb, transformXyzToRgb } from '../matrix/transform';
import {
ComputedColorChannels,
Options,
SpecifiedColorChannels,
TriColorChannels
} from '../typedef';
import { createCacheKey, getCache, setCache } from '../utils/cache';
import { isString } from '../utils/common';
import { cssCalc, resolveVar } from '../utils/css-calc-var';
import {
parseAlpha,
resolveInvalidColorValue,
splitValue
} from '../utils/util';
import { resolveColorMix } from './color-mix';
import {
parseColorFunc,
parseHsl,
parseHwb,
parseLab,
parseLch,
parseOklab,
parseOklch,
parseRgb
} from './parse-color';
import { resolveRelativeColor } from './relative-color';
/* constants */
import {
FN_COLOR,
FN_MIX,
MAX_RGB,
SYN_COLOR_TYPE,
SYN_FN_CALC,
SYN_FN_COLOR,
SYN_FN_LIGHT_DARK,
SYN_FN_REL,
SYN_FN_VAR,
SYN_MIX,
VAL_COMP,
VAL_MIX,
VAL_SPEC
} from '../utils/constant';
import { NAMED_COLORS } from './named-color';
const NAMESPACE = 'resolve-color';
const RGB_TRANSPARENT = 'rgba(0, 0, 0, 0)';
/* regexp */
const REG_COLOR = new RegExp(`^(?:${SYN_COLOR_TYPE})$`);
const REG_COLOR_FUNC = new RegExp(`^color\\(\\s*(${SYN_FN_COLOR})\\s*\\)$`);
const REG_CURRENT = /^currentColor$/i;
const REG_FN_CALC = new RegExp(SYN_FN_CALC);
const REG_FN_COLOR =
/^(?:(?:ok)?l(?:ab|ch)|color(?:-mix)?|hsla?|hwb|rgba?|var)\(/;
const REG_FN_LIGHT_DARK = new RegExp(SYN_FN_LIGHT_DARK);
const REG_FN_REL = new RegExp(SYN_FN_REL);
const REG_FN_VAR = new RegExp(SYN_FN_VAR);
const REG_MIX = new RegExp(SYN_MIX);
const REG_SPEC = /^(?:specifi|comput)edValue$/;
/**
* resolve color value
* @param value - CSS color value
* @param opt - options
* @returns resolved color
* - [cs, v1, v2, v3, alpha], value, '(empty)', null
*/
export const resolveColorValue = (
value: string,
opt: Options = {}
): SpecifiedColorChannels | string | null => {
if (isString(value)) {
value = value.toLowerCase().trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { colorSpace = '', format = '', nullable = false } = opt;
const cacheKey: string = createCacheKey(
{
namespace: NAMESPACE,
name: 'resolveColorValue',
value
},
opt
);
const cachedResult = getCache(cacheKey);
if (cachedResult !== false) {
const { item } = cachedResult;
if (Array.isArray(item)) {
return [...item] as SpecifiedColorChannels;
}
return item as string | null;
}
if (!REG_COLOR.test(value)) {
const res = resolveInvalidColorValue(format, nullable);
if (res === null) {
setCache(cacheKey, null);
return null;
}
setCache(cacheKey, res);
if (isString(res)) {
return res as string;
}
return res as SpecifiedColorChannels;
}
let cs = '';
let r = 0;
let g = 0;
let b = 0;
let alpha = 0;
// complement currentcolor as a missing color
if (REG_CURRENT.test(value)) {
if (format === VAL_SPEC) {
setCache(cacheKey, value);
return value;
}
// named-color
} else if (/^[a-z]+$/.test(value)) {
if (Object.hasOwn(NAMED_COLORS, value)) {
if (format === VAL_SPEC) {
setCache(cacheKey, value);
return value;
}
[r, g, b] = NAMED_COLORS[
value as keyof typeof NAMED_COLORS
] as TriColorChannels;
alpha = 1;
} else {
switch (format) {
case VAL_SPEC: {
if (value === 'transparent') {
setCache(cacheKey, value);
return value;
}
const res = '';
setCache(cacheKey, res);
return res;
}
case VAL_MIX: {
if (value === 'transparent') {
const res: SpecifiedColorChannels = ['rgb', 0, 0, 0, 0];
setCache(cacheKey, res);
return [...res];
}
setCache(cacheKey, null);
return null;
}
case VAL_COMP:
default: {
if (nullable && value !== 'transparent') {
setCache(cacheKey, null);
return null;
}
const res: SpecifiedColorChannels = ['rgb', 0, 0, 0, 0];
setCache(cacheKey, res);
return [...res];
}
}
}
// hex-color
} else if (value[0] === '#') {
[r, g, b, alpha] = convertHexToRgb(value);
// hsl()
} else if (value.startsWith('hsl')) {
[, r, g, b, alpha] = parseHsl(value, opt) as ComputedColorChannels;
// hwb()
} else if (value.startsWith('hwb')) {
[, r, g, b, alpha] = parseHwb(value, opt) as ComputedColorChannels;
// lab(), lch()
} else if (/^l(?:ab|ch)/.test(value)) {
let x, y, z;
if (value.startsWith('lab')) {
[cs, x, y, z, alpha] = parseLab(value, opt) as ComputedColorChannels;
} else {
[cs, x, y, z, alpha] = parseLch(value, opt) as ComputedColorChannels;
}
if (REG_SPEC.test(format)) {
const res: SpecifiedColorChannels = [cs, x, y, z, alpha];
setCache(cacheKey, res);
return [...res];
}
[r, g, b] = transformXyzD50ToRgb([x, y, z]);
// oklab(), oklch()
} else if (/^okl(?:ab|ch)/.test(value)) {
let x, y, z;
if (value.startsWith('oklab')) {
[cs, x, y, z, alpha] = parseOklab(value, opt) as ComputedColorChannels;
} else {
[cs, x, y, z, alpha] = parseOklch(value, opt) as ComputedColorChannels;
}
if (REG_SPEC.test(format)) {
const res: SpecifiedColorChannels = [cs, x, y, z, alpha];
setCache(cacheKey, res);
return [...res];
}
[r, g, b] = transformXyzToRgb([x, y, z]);
// rgb()
} else {
[, r, g, b, alpha] = parseRgb(value, opt) as ComputedColorChannels;
}
if (format === VAL_MIX && colorSpace === 'srgb') {
const res: SpecifiedColorChannels = [
'srgb',
r / MAX_RGB,
g / MAX_RGB,
b / MAX_RGB,
alpha
];
setCache(cacheKey, res);
return [...res];
}
const res: SpecifiedColorChannels = [
'rgb',
Math.round(r),
Math.round(g),
Math.round(b),
alpha
];
setCache(cacheKey, res);
return [...res];
};
/**
* resolve color()
* @param value - color function value
* @param opt - options
* @returns resolved color - [cs, v1, v2, v3, alpha], '(empty)', null
*/
export const resolveColorFunc = (
value: string,
opt: Options = {}
): SpecifiedColorChannels | string | null => {
if (isString(value)) {
value = value.toLowerCase().trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
const { colorSpace = '', format = '', nullable = false } = opt;
const cacheKey: string = createCacheKey(
{
namespace: NAMESPACE,
name: 'resolveColorFunc',
value
},
opt
);
const cachedResult = getCache(cacheKey);
if (cachedResult !== false) {
const { item } = cachedResult;
if (Array.isArray(item)) {
return [...item] as SpecifiedColorChannels;
}
return item as string | null;
}
if (!REG_COLOR_FUNC.test(value)) {
const res = resolveInvalidColorValue(format, nullable);
if (res === null) {
setCache(cacheKey, null);
return null;
}
setCache(cacheKey, res);
if (isString(res)) {
return res as string;
}
return res as SpecifiedColorChannels;
}
const [cs, v1, v2, v3, v4] = parseColorFunc(
value,
opt
) as SpecifiedColorChannels;
if (REG_SPEC.test(format) || (format === VAL_MIX && cs === colorSpace)) {
const res: SpecifiedColorChannels = [cs, v1, v2, v3, v4];
setCache(cacheKey, res);
return [...res];
}
const x = parseFloat(`${v1}`);
const y = parseFloat(`${v2}`);
const z = parseFloat(`${v3}`);
const alpha = parseAlpha(`${v4}`);
const [r, g, b] = transformXyzToRgb([x, y, z], true);
const res: SpecifiedColorChannels = ['rgb', r, g, b, alpha];
setCache(cacheKey, res);
return [...res];
};
/**
* resolve color
* @param value - CSS color value
* @param opt - options
* @returns resolved color
*/
export const resolveColor = (
value: string,
opt: Options = {}
): string | null => {
if (!isString(value)) {
throw new TypeError(`${value} is not a string.`);
}
value = value.trim();
const {
colorScheme = 'normal',
currentColor = '',
format = VAL_COMP,
nullable = false
} = opt;
const cacheKey: string = createCacheKey(
{ namespace: NAMESPACE, name: 'resolve', value },
opt
);
const cachedResult = getCache(cacheKey);
if (cachedResult !== false) {
return cachedResult.item as string | null;
}
// 1. var() resolution
if (REG_FN_VAR.test(value)) {
if (format === VAL_SPEC) {
setCache(cacheKey, value);
return value;
}
const resolvedVar = resolveVar(value, opt);
if (resolvedVar === null) {
const res =
format === 'hex' || format === 'hexAlpha' || nullable
? null
: RGB_TRANSPARENT;
setCache(cacheKey, res);
return res;
}
value = resolvedVar;
}
if (opt.format !== format) {
opt.format = format;
}
value = value.toLowerCase();
// 2. light-dark() resolution
if (REG_FN_LIGHT_DARK.test(value) && value.endsWith(')')) {
const colorParts = value.replace(REG_FN_LIGHT_DARK, '').replace(/\)$/, '');
const [light = '', dark = ''] = splitValue(colorParts, { delimiter: ',' });
if (light && dark) {
if (format === VAL_SPEC) {
const lightColor = resolveColor(light, opt);
const darkColor = resolveColor(dark, opt);
const res =
lightColor && darkColor
? `light-dark(${lightColor}, ${darkColor})`
: '';
setCache(cacheKey, res);
return res;
}
const chosen = colorScheme === 'dark' ? dark : light;
const resolved = resolveColor(chosen, opt);
setCache(cacheKey, resolved);
return resolved;
}
// fallback for invalid light-dark
let invalidRes;
if (format === VAL_SPEC) {
invalidRes = '';
} else if (format === 'hex' || format === 'hexAlpha') {
invalidRes = null;
} else {
invalidRes = RGB_TRANSPARENT;
}
setCache(cacheKey, invalidRes);
return invalidRes;
}
// 3. Relative Color resolution
if (REG_FN_REL.test(value)) {
const resolvedRel = resolveRelativeColor(value, opt, resolveColor);
if (format === VAL_COMP) {
const res =
resolvedRel === null && !nullable ? RGB_TRANSPARENT : resolvedRel;
setCache(cacheKey, res);
return res;
}
if (format === VAL_SPEC) {
const res = resolvedRel === null ? '' : resolvedRel;
setCache(cacheKey, res);
return res;
}
value = resolvedRel === null ? '' : resolvedRel;
}
// 4. calc() resolution
if (REG_FN_CALC.test(value)) {
value = cssCalc(value, opt);
}
// 5. Keyword & Color-space resolution
let cs = '';
let r = NaN;
let g = NaN;
let b = NaN;
let alpha = NaN;
if (value === 'transparent') {
let res: string | null;
switch (format) {
case VAL_SPEC: {
res = value;
break;
}
case 'hex': {
res = null;
break;
}
case 'hexAlpha': {
res = '#00000000';
break;
}
default: {
res = RGB_TRANSPARENT;
}
}
setCache(cacheKey, res);
return res;
}
if (value === 'currentcolor') {
if (format === VAL_SPEC) {
setCache(cacheKey, value);
return value;
}
if (currentColor) {
let resolvedCurrent;
if (currentColor.startsWith(FN_MIX)) {
resolvedCurrent = resolveColorMix(currentColor, opt, resolveColor);
} else if (currentColor.startsWith(FN_COLOR)) {
resolvedCurrent = resolveColorFunc(currentColor, opt);
} else {
resolvedCurrent = resolveColorValue(currentColor, opt);
}
if (resolvedCurrent === null) {
setCache(cacheKey, null);
return null;
}
[cs, r, g, b, alpha] = resolvedCurrent as ComputedColorChannels;
} else {
// value is handled below if not VAL_COMP
const res = format === VAL_COMP ? RGB_TRANSPARENT : value;
if (format === VAL_COMP) {
setCache(cacheKey, res);
return res;
}
}
} else if (format === VAL_SPEC) {
let res = '';
if (value.startsWith(FN_MIX)) {
const mixRes = resolveColorMix(value, opt, resolveColor);
if (isString(mixRes) && mixRes) {
res = mixRes;
}
} else if (value.startsWith(FN_COLOR)) {
const funcRes = resolveColorFunc(value, opt);
if (Array.isArray(funcRes)) {
const [scs, rr, gg, bb, aa] = funcRes as SpecifiedColorChannels;
res =
aa === 1
? `color(${scs} ${rr} ${gg} ${bb})`
: `color(${scs} ${rr} ${gg} ${bb} / ${aa})`;
}
} else {
const rgb = resolveColorValue(value, opt);
if (Array.isArray(rgb)) {
const [scs, rr, gg, bb, aa] = rgb as SpecifiedColorChannels;
if (scs === 'rgb') {
res =
aa === 1
? `${scs}(${rr}, ${gg}, ${bb})`
: `${scs}a(${rr}, ${gg}, ${bb}, ${aa})`;
} else {
res =
aa === 1
? `${scs}(${rr} ${gg} ${bb})`
: `${scs}(${rr} ${gg} ${bb} / ${aa})`;
}
} else if (rgb) {
res = rgb;
}
}
setCache(cacheKey, res);
return res;
} else if (value.startsWith(FN_MIX)) {
if (currentColor) {
value = value.replace(/currentcolor/g, currentColor);
}
value = value.replace(/transparent/g, RGB_TRANSPARENT);
const resolvedMix = resolveColorMix(value, opt, resolveColor);
if (resolvedMix === null) {
setCache(cacheKey, null);
return null;
}
[cs, r, g, b, alpha] = resolvedMix as ComputedColorChannels;
} else if (value.startsWith(FN_COLOR)) {
const resolvedFunc = resolveColorFunc(value, opt);
if (resolvedFunc === null) {
setCache(cacheKey, null);
return null;
}
[cs, r, g, b, alpha] = resolvedFunc as ComputedColorChannels;
} else if (value) {
const resolvedVal = resolveColorValue(value, opt);
if (resolvedVal === null) {
setCache(cacheKey, null);
return null;
}
[cs, r, g, b, alpha] = resolvedVal as ComputedColorChannels;
}
// 6. Format Finalization
let finalRes: string | null = '';
switch (format) {
case 'hex':
case 'hexAlpha': {
if (
Number.isNaN(r) ||
Number.isNaN(g) ||
Number.isNaN(b) ||
Number.isNaN(alpha) ||
(format === 'hex' && alpha === 0)
) {
finalRes = null;
} else {
finalRes = convertRgbToHex([r, g, b, format === 'hex' ? 1 : alpha]);
}
break;
}
default: {
if (cs === 'rgb') {
finalRes =
alpha === 1
? `${cs}(${r}, ${g}, ${b})`
: `${cs}a(${r}, ${g}, ${b}, ${alpha})`;
} else if (['lab', 'lch', 'oklab', 'oklch'].includes(cs)) {
finalRes =
alpha === 1
? `${cs}(${r} ${g} ${b})`
: `${cs}(${r} ${g} ${b} / ${alpha})`;
} else {
finalRes =
alpha === 1
? `color(${cs} ${r} ${g} ${b})`
: `color(${cs} ${r} ${g} ${b} / ${alpha})`;
}
}
}
setCache(cacheKey, finalRes);
return finalRes;
};
/**
* is valid color
* @param value - CSS value
* @param opt - options
* @returns result
*/
export const isValidColor = (value: unknown, opt: Options = {}): boolean => {
if (!isString(value)) {
return false;
}
const color = value.toLowerCase().trim();
if (!color) {
return false;
}
if (/^[a-z]+$/.test(color)) {
return (
color === 'currentcolor' ||
color === 'transparent' ||
Object.hasOwn(NAMED_COLORS, color)
);
}
if (REG_COLOR.test(color) || REG_MIX.test(color)) {
return true;
}
if (REG_FN_COLOR.test(color)) {
const options = {
...opt,
nullable: true
};
return !!resolveColor(color, options);
}
return false;
};

View File

@ -0,0 +1,33 @@
/**
* resolve
*/
import { Options } from '../typedef';
import { isValidColor, resolveColor } from './resolve-color';
/**
* resolve CSS color
* @param value - CSS color value. system colors are not supported
* @param opt - options
* @returns resolved value
*/
export const resolve = (value: string, opt: Options = {}): string | null => {
const options = {
...opt
};
return resolveColor(value, options);
};
/**
* is color
* @param value - CSS value
* @param opt - options
* @returns result
*/
export const isColor = (value: unknown, opt: Options = {}): boolean => {
const options = {
...opt,
nullable: true
};
return !!isValidColor(value, options);
};

393
node_modules/@asamuzakjp/css-color/src/typedef.ts generated vendored Normal file
View File

@ -0,0 +1,393 @@
/**
* typedef
*/
import { CSSToken } from '@csstools/css-tokenizer';
/**
* Supported CSS gradient function types.
*/
export type GradientType =
| 'linear-gradient'
| 'repeating-linear-gradient'
| 'radial-gradient'
| 'repeating-radial-gradient'
| 'conic-gradient'
| 'repeating-conic-gradient';
/**
* Known CSS color spaces.
*/
type KnownColorSpace =
| 'srgb'
| 'srgb-linear'
| 'display-p3'
| 'a98-rgb'
| 'prophoto-rgb'
| 'rec2020'
| 'xyz'
| 'xyz-d50'
| 'xyz-d65';
/**
* Supported CSS color space string or custom space.
*/
export type ColorSpace = KnownColorSpace | (string & {});
/**
* Known CSS color output and input formats.
*/
type KnownColorFormat =
| 'hex'
| 'hexAlpha'
| 'rgb'
| 'hsl'
| 'hwb'
| 'lab'
| 'lch'
| 'oklab'
| 'oklch'
| 'computed'
| 'specified'
| 'mix';
/**
* Color format option or custom string.
*/
export type ColorFormat = KnownColorFormat | (string & {});
/**
* Hue interpolation methods for color spaces with hue.
*/
export type HueArc = 'shorter' | 'longer' | 'increasing' | 'decreasing';
/**
* Flags indicating missing or powerless channels [c1, c2, c3, alpha].
*/
export type ChannelNoneFlags = [
c1: boolean,
c2: boolean,
c3: boolean,
alpha: boolean
];
/**
* AST node representation for the calc() parser.
*/
export type CalcASTNode = string | CalcASTNode[];
/**
* Calculation token stream, including its terminal EOF token, and cursor.
*/
export interface CalculationState {
tokens: CSSToken[];
index: number;
}
/**
* Custom property resolver value or callback function.
*/
type CustomPropertyResolver = string | ((key: string) => string | undefined);
/**
* Dimension resolver value or callback function.
*/
type DimensionResolver = number | ((key: string) => number | undefined);
/**
* CSS dimension unit resolution map.
*/
interface DimensionMap {
[key: string]: DimensionResolver | undefined;
/** Custom dimension unit resolver callback. */
callback?: (key: string) => number | undefined;
/** Font size of the element in pixels. */
em?: number;
/** Root element font size in pixels. */
rem?: number;
/** Viewport height in pixels. */
vh?: number;
/** Viewport width in pixels. */
vw?: number;
}
/**
* Custom property lookup map or callback handler.
*/
interface CustomPropertyMap {
[key: string]: CustomPropertyResolver | undefined;
/** Custom property resolver callback function. */
callback?: (key: string) => string | undefined;
}
/**
* Parsing and resolution options.
*/
export interface Options {
/** Force alpha channel output. */
alpha?: boolean;
/** Preferred color scheme context. */
colorScheme?: string;
/** Target color space for output. */
colorSpace?: ColorSpace;
/** Value used for `currentColor` keyword. */
currentColor?: string;
/** Custom property resolvers. */
customProperty?: CustomPropertyMap;
/** Adapt XYZ coordinates to D50 illuminant. */
d50?: boolean;
/** Channel values delimiter string or list. */
delimiter?: string | readonly string[];
/** Dimension resolution settings. */
dimension?: DimensionMap;
/** Output color format. */
format?: ColorFormat;
/** Maximum length limit for parsed string. */
maxLength?: number;
/** Return null instead of throwing on invalid input. */
nullable?: boolean;
/** Retain comments during parsing. */
preserveComment?: boolean;
}
/**
* Three-element color channel tuple [x, y, z].
*/
export type TriColorChannels = [x: number, y: number, z: number];
/**
* Readonly three-element color channel tuple [x, y, z].
*/
export type ReadonlyTriColorChannels = readonly [
x: number,
y: number,
z: number
];
/**
* 3x3 color conversion matrix tuple.
*/
export type ReadonlyColorMatrix = readonly [
r1: ReadonlyTriColorChannels,
r2: ReadonlyTriColorChannels,
r3: ReadonlyTriColorChannels
];
/**
* Four-element color channel numeric tuple [x, y, z, alpha].
*/
export type ColorChannels = [x: number, y: number, z: number, alpha: number];
/**
* Four-element color channel string tuple [x, y, z, alpha].
*/
export type StringColorChannels = [
x: string,
y: string,
z: string,
alpha: string | undefined
];
/**
* Four-element color channel numeric/string tuple [x, y, z, alpha].
*/
export type NumStrColorChannels = [
x: number | string,
y: number | string,
z: number | string,
alpha: number | string
];
/**
* Color channel tuple with missing/powerless string tags.
*/
export type ColorChannelsWithPowerless = [
x: number | string,
y: number | string,
z: number | string,
alpha: number
];
/**
* Color space name and three channel strings with alpha.
*/
export type StringColorSpacedChannels = [
cs: string,
x: string,
y: string,
z: string,
alpha: string | undefined
];
/**
* Resolved computed color channel representation.
*/
export type ComputedColorChannels = [
cs: string,
x: number,
y: number,
z: number,
alpha: number
];
/**
* Resolved specified color channel representation.
*/
export type SpecifiedColorChannels = [
cs: string,
x: number | string,
y: number | string,
z: number | string,
alpha: number | string
];
/**
* RegExp match result tuple with 3 capture groups.
*/
export type MatchedRegExp3 = [
match: string,
gr1: string,
gr2: string,
gr3: string
];
/**
* RegExp match result tuple with 4 capture groups.
*/
export type MatchedRegExp4 = [
match: string,
gr1: string,
gr2: string,
gr3: string,
gr4: string
];
/**
* Standard matched RegExp tuple alias.
*/
export type MatchedRegExp = MatchedRegExp4;
/**
* Component validation configuration.
*/
export interface ValidateColorComponentsOptions {
/** Validate alpha channel presence. */
alpha?: boolean;
/** Minimum number of components. */
minLength?: number;
/** Maximum number of components. */
maxLength?: number;
/** Minimum allowed component value. */
minRange?: number;
/** Maximum allowed component value. */
maxRange?: number;
/** Whether to enforce component value range check. */
validateRange?: boolean;
}
/**
* Options for linear RGB conversion.
*/
export interface LinearRgbOptions {
/** Target color space for conversion. */
colorSpace?: ColorSpace;
/** Output color format. */
format?: ColorFormat;
}
/**
* Function type for converting color string to channel values.
*/
export type ColorConvertFn = (
value: string,
opt?: Options
) => ColorChannels | ColorChannelsWithPowerless | null;
/**
* Function type for resolving CSS color expressions.
*/
export type ColorResolverFn = (
value: string,
opt?: Options
) => SpecifiedColorChannels | string | null;
/**
* Parsed CSS gradient object structure.
*/
export interface Gradient {
/** Raw gradient CSS string value. */
value: string;
/** Type of gradient expression. */
type: GradientType;
/** Parsed gradient line parameter. */
gradientLine?: string;
/** List of color stops. */
colorStopList: ColorStopList;
}
/**
* Color stops validation result.
*/
export interface ValidateColorStops {
/** Extracted color stop strings. */
colorStops: string[];
/** Flag indicating stop list validity. */
valid: boolean;
}
/**
* Gradient line validation result.
*/
export interface ValidateGradientLine {
/** Extracted gradient line string. */
line: string;
/** Flag indicating line syntax validity. */
valid: boolean;
}
/**
* Tuple representing a minimum of two color stops.
*/
export type ColorStopList = [string, string, ...string[]];
/**
* Parsed color space parameter for color-mix().
*/
export interface ColorSpaceParseResult {
/** Color space name. */
colorSpace: ColorSpace;
/** Interpolation hue method. */
hueArc: HueArc | string;
}
/**
* Color and percentage pair for color-mix().
*/
export interface ColorAndPct {
/** Raw color string. */
color: string;
/** Raw percentage string. */
pct: string;
}
/**
* Normalized percentage values for color mixing.
*/
export interface NormalizedPercentages {
/** First color percentage weight (0 to 1). */
pA: number;
/** Second color percentage weight (0 to 1). */
pB: number;
/** Multiplier factor for un-normalized sums. */
m: number;
}
/**
* Interpolated channels and alpha output.
*/
export interface InterpolatedComponents {
/** Three-element color component values. */
comps: TriColorChannels;
/** Resulting alpha transparency. */
alpha: number;
}

121
node_modules/@asamuzakjp/css-color/src/utils/cache.ts generated vendored Normal file
View File

@ -0,0 +1,121 @@
/**
* cache
*/
import { LRUCache } from 'lru-cache';
import { Options } from '../typedef';
/* constants */
const CACHE_SIZE = 4096;
/**
* CacheItem
*/
export class CacheItem<T = unknown> {
/* private */
#item: T;
constructor(item: T) {
this.#item = item;
}
get item(): T {
return this.#item;
}
}
/*
* lru cache instance
*/
export const lruCache = new LRUCache<string, CacheItem<any>>({
max: CACHE_SIZE
});
/**
* set cache
* @param key - cache key
* @param value - value to cache
*/
export const setCache = <T>(key: string, value: T | CacheItem<T>): void => {
if (!key) {
return;
}
if (value instanceof CacheItem) {
lruCache.set(key, value);
} else {
lruCache.set(key, new CacheItem<T>(value));
}
};
/**
* get cache
* @param key - cache key
* @returns cached item or false otherwise
*/
export const getCache = <T = unknown>(key: string): CacheItem<T> | false => {
if (!key) {
return false;
}
const item = lruCache.get(key);
if (item !== undefined) {
return item as CacheItem<T>;
}
return false;
};
/**
* helper function to sort object keys alphabetically
* @param obj - Object
* @returns stringified JSON
*/
const stringifySorted = (obj: Record<string, unknown>): string => {
const keys = Object.keys(obj);
if (keys.length === 0) {
return '';
}
keys.sort();
let result = '';
for (const key of keys) {
result += `${key}:${JSON.stringify(obj[key])};`;
}
return result;
};
/**
* create cache key
* @param keyData - key data
* @param [opt] - options
* @returns cache key
*/
export const createCacheKey = (
keyData: Record<string, string>,
opt: Options = {}
): string => {
if (
!keyData ||
(opt.customProperty && typeof opt.customProperty.callback === 'function') ||
(opt.dimension && typeof opt.dimension.callback === 'function')
) {
return '';
}
const namespace = keyData.namespace || '';
const name = keyData.name || '';
const value = keyData.value || '';
if (!namespace && !name && !value) {
return '';
}
const baseKey = `${namespace}:${name}:${value}`;
const opts = [];
for (const [key, val] of Object.entries(opt)) {
if (key !== 'customProperty' && key !== 'dimension') {
opts.push(`${key}_${val}`);
}
}
const customPropStr = opt.customProperty
? stringifySorted(opt.customProperty as Record<string, unknown>)
: '';
const dimStr = opt.dimension
? stringifySorted(opt.dimension as Record<string, unknown>)
: '';
return `${baseKey}:${opts.sort().join('|')}:${customPropStr}:${dimStr}`;
};

31
node_modules/@asamuzakjp/css-color/src/utils/common.ts generated vendored Normal file
View File

@ -0,0 +1,31 @@
/**
* common
*/
/* numeric constants */
const TYPE_FROM = 8;
const TYPE_TO = -1;
/**
* get type
* @param o - object to check
* @returns type of object
*/
export const getType = (o: unknown): string =>
Object.prototype.toString.call(o).slice(TYPE_FROM, TYPE_TO);
/**
* is string
* @param o - object to check
* @returns result
*/
export const isString = (o: unknown): o is string =>
typeof o === 'string' || o instanceof String;
/**
* is string or number
* @param o - object to check
* @returns result
*/
export const isStringOrNumber = (o: unknown): o is string | number =>
isString(o) || typeof o === 'number';

View File

@ -0,0 +1,99 @@
/**
* constant
*/
/* values and units */
const _DIGIT = '(?:0|[1-9]\\d*)';
const _COMPARE = 'clamp|max|min';
const _EXPO = 'exp|hypot|log|pow|sqrt';
const _SIGN = 'abs|sign';
const _STEP = 'mod|rem|round';
const _TRIG = 'a?(?:cos|sin|tan)|atan2';
const _MATH = `${_COMPARE}|${_EXPO}|${_SIGN}|${_STEP}|${_TRIG}`;
const _CALC = `calc|${_MATH}`;
const _VAR = `var|${_CALC}`;
export const ANGLE = 'deg|g?rad|turn';
export const LENGTH =
'[cm]m|[dls]?v(?:[bhiw]|max|min)|in|p[ctx]|q|r?(?:[cl]h|cap|e[mx]|ic)';
export const NUM = `[+-]?(?:${_DIGIT}(?:\\.\\d*)?|\\.\\d+)(?:e-?${_DIGIT})?`;
export const NUM_POSITIVE = `\\+?(?:${_DIGIT}(?:\\.\\d*)?|\\.\\d+)(?:e-?${_DIGIT})?`;
export const NONE = 'none';
export const PCT = `${NUM}%`;
export const SYN_FN_CALC = `^(?:${_CALC})\\(|(?<=[*\\/\\s\\(])(?:${_CALC})\\(`;
export const SYN_FN_MATH_START = `^(?:${_MATH})\\($`;
export const SYN_FN_VAR = '^var\\(|(?<=[*\\/\\s\\(])var\\(';
export const SYN_FN_VAR_START = `^(?:${_VAR})\\(`;
/* colors */
const _ALPHA = `(?:\\s*\\/\\s*(?:${NUM}|${PCT}|${NONE}))?`;
const _ALPHA_LV3 = `(?:\\s*,\\s*(?:${NUM}|${PCT}))?`;
const _COLOR_FUNC = '(?:ok)?l(?:ab|ch)|color|hsla?|hwb|rgba?';
const _COLOR_KEY = '[a-z]+|#[\\da-f]{3}|#[\\da-f]{4}|#[\\da-f]{6}|#[\\da-f]{8}';
const _CS_HUE = '(?:ok)?lch|hsl|hwb';
const _CS_HUE_ARC = '(?:de|in)creasing|longer|shorter';
const _NUM_ANGLE = `${NUM}(?:${ANGLE})?`;
const _NUM_ANGLE_NONE = `(?:${NUM}(?:${ANGLE})?|${NONE})`;
const _NUM_PCT_NONE = `(?:${NUM}|${PCT}|${NONE})`;
export const CS_HUE = `(?:${_CS_HUE})(?:\\s(?:${_CS_HUE_ARC})\\shue)?`;
export const CS_HUE_CAPT = `(${_CS_HUE})(?:\\s(${_CS_HUE_ARC})\\shue)?`;
export const CS_LAB = '(?:ok)?lab';
export const CS_LCH = '(?:ok)?lch';
export const CS_SRGB = 'srgb(?:-linear)?';
export const CS_RGB = `(?:a98|prophoto)-rgb|display-p3|rec2020|${CS_SRGB}`;
export const CS_XYZ = 'xyz(?:-d(?:50|65))?';
export const CS_RECT = `${CS_LAB}|${CS_RGB}|${CS_XYZ}`;
export const CS_MIX = `${CS_HUE}|${CS_RECT}`;
export const FN_COLOR = 'color(';
export const FN_LIGHT_DARK = 'light-dark(';
export const FN_MIX = 'color-mix(';
export const FN_REL = `(?:${_COLOR_FUNC})\\(\\s*from\\s+`;
export const FN_REL_CAPT = `(${_COLOR_FUNC})\\(\\s*from\\s+`;
export const FN_VAR = 'var(';
export const SYN_FN_COLOR = `(?:${CS_RGB}|${CS_XYZ})(?:\\s+${_NUM_PCT_NONE}){3}${_ALPHA}`;
export const SYN_FN_LIGHT_DARK = '^light-dark\\(';
export const SYN_FN_REL = `^${FN_REL}|(?<=[\\s])${FN_REL}`;
export const SYN_HSL = `${_NUM_ANGLE_NONE}(?:\\s+${_NUM_PCT_NONE}){2}${_ALPHA}`;
export const SYN_HSL_LV3 = `${_NUM_ANGLE}(?:\\s*,\\s*${PCT}){2}${_ALPHA_LV3}`;
export const SYN_LCH = `(?:${_NUM_PCT_NONE}\\s+){2}${_NUM_ANGLE_NONE}${_ALPHA}`;
export const SYN_MOD = `${_NUM_PCT_NONE}(?:\\s+${_NUM_PCT_NONE}){2}${_ALPHA}`;
export const SYN_RGB_LV3 = `(?:${NUM}(?:\\s*,\\s*${NUM}){2}|${PCT}(?:\\s*,\\s*${PCT}){2})${_ALPHA_LV3}`;
export const SYN_COLOR_TYPE = `${_COLOR_KEY}|hsla?\\(\\s*${SYN_HSL_LV3}\\s*\\)|rgba?\\(\\s*${SYN_RGB_LV3}\\s*\\)|(?:hsla?|hwb)\\(\\s*${SYN_HSL}\\s*\\)|(?:(?:ok)?lab|rgba?)\\(\\s*${SYN_MOD}\\s*\\)|(?:ok)?lch\\(\\s*${SYN_LCH}\\s*\\)|color\\(\\s*${SYN_FN_COLOR}\\s*\\)`;
export const SYN_MIX_PART = `(?:${SYN_COLOR_TYPE})(?:\\s+${PCT})?`;
export const SYN_MIX = `color-mix\\(\\s*in\\s+(?:${CS_MIX})\\s*,\\s*${SYN_MIX_PART}\\s*,\\s*${SYN_MIX_PART}\\s*\\)`;
export const SYN_MIX_CAPT = `color-mix\\(\\s*in\\s+(${CS_MIX})\\s*,\\s*(${SYN_MIX_PART})\\s*,\\s*(${SYN_MIX_PART})\\s*\\)`;
/* formats */
/* formats */
export const VAL_COMP = 'computedValue' as const;
export const VAL_MIX = 'mixValue' as const;
export const VAL_SPEC = 'specifiedValue' as const;
export type SpecialValueFormat =
typeof VAL_COMP | typeof VAL_MIX | typeof VAL_SPEC;
/* numeric constants */
export const DEC = 10;
export const DEG = 360;
export const DEG_HALF = 180;
export const DOZ = 12;
export const DUO = 2;
export const HALF = 0.5;
export const HEX = 16;
export const LAB_A = 500;
export const LAB_B = 200;
export const LAB_EPSILON = 216 / 24389;
export const LAB_KAPPA = 24389 / 27;
export const LAB_L = 116;
export const LINEAR_COEF = 12.92;
export const LINEAR_OFFSET = 0.055;
export const MAX_LENGTH = 1024;
export const MAX_PCT = 100;
export const MAX_RGB = 255;
export const OCT = 8;
export const POW_CUBE = 3;
export const POW_LINEAR = 2.4;
export const POW_SQR = 2;
export const PPTH = 0.001;
export const QUAD = 4;
export const SEXA = 60;
export const TRIA = 3;

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,206 @@
/**
* length-percentage
*/
import {
CSSToken,
ParseError,
tokenize,
TokenType
} from '@csstools/css-tokenizer';
import { CalculationState } from '../typedef';
import { isString } from './common';
/* constants */
import { LENGTH } from './constant';
/* regexp */
const REG_LENGTH = new RegExp(`^(?:${LENGTH})$`, 'i');
const REG_CALC = /^(?:calc|min|max|clamp)\(/i;
const REG_CALC_KEYWORD = /^(?:e|pi|-?infinity|NaN)$/i;
/**
* Advance past whitespace and comments in a calculation.
* @param state - token stream and cursor
*/
export const skipCalculationWhitespace = (state: CalculationState): void => {
while (
state.tokens[state.index]![0] === TokenType.Whitespace ||
state.tokens[state.index]![0] === TokenType.Comment
) {
state.index++;
}
};
/**
* Check for actual whitespace, ignoring adjacent comments.
* @param tokens - token stream
* @param start - first token to check
* @param step - direction to scan
* @returns whether whitespace occurs before another non-comment token
*/
export const hasCalculationWhitespace = (
tokens: CSSToken[],
start: number,
step: 1 | -1
): boolean => {
for (let i = start; i >= 0 && i < tokens.length; i += step) {
if (tokens[i]![0] === TokenType.Whitespace) {
return true;
}
if (tokens[i]![0] !== TokenType.Comment) {
break;
}
}
return false;
};
/**
* Parse multiplication and division of calculation operands.
* Multiplication requires a number on one side, division a number divisor.
* This subset intentionally excludes CSS Values Level 4 typed arithmetic.
* @param state - token stream and cursor
* @returns calculation type or null on failure
*/
export const parseCalculationProduct = (
state: CalculationState
): number | null => {
let type = parseCalculationValue(state);
if (type === null) {
return null;
}
skipCalculationWhitespace(state);
while (
state.tokens[state.index]![0] === TokenType.Delim &&
(state.tokens[state.index]![1] === '*' ||
state.tokens[state.index]![1] === '/')
) {
const operator = state.tokens[state.index++]![1];
const right = parseCalculationValue(state);
if (
right === null ||
(operator === '*' ? type !== 0 && right !== 0 : right !== 0)
) {
return null;
}
type += right;
skipCalculationWhitespace(state);
}
return type;
};
/**
* Parse addition and subtraction, requiring matching operand types.
* @param state - token stream and cursor
* @returns calculation type or null on failure
*/
export const parseCalculationSum = (state: CalculationState): number | null => {
const type = parseCalculationProduct(state);
if (type === null) {
return null;
}
while (
state.tokens[state.index]![0] === TokenType.Delim &&
(state.tokens[state.index]![1] === '+' ||
state.tokens[state.index]![1] === '-')
) {
if (
!hasCalculationWhitespace(state.tokens, state.index - 1, -1) ||
!hasCalculationWhitespace(state.tokens, state.index + 1, 1)
) {
return null;
}
state.index++;
if (parseCalculationProduct(state) !== type) {
return null;
}
}
return type;
};
/**
* Parse a scalar, length, percentage, parenthesized sum or math function.
* Percentages receive the length percent hint in this context.
* @param state - token stream and cursor
* @returns calculation type or null on failure
*/
export function parseCalculationValue(state: CalculationState): number | null {
skipCalculationWhitespace(state);
if (state.tokens[state.index]![0] === TokenType.EOF) {
return null;
}
const token = state.tokens[state.index++]!;
switch (token[0]) {
case TokenType.Number: {
return 0;
}
case TokenType.Percentage: {
return 1;
}
case TokenType.Dimension: {
return REG_LENGTH.test(token[4].unit) ? 1 : null;
}
case TokenType.Ident: {
return REG_CALC_KEYWORD.test(token[4].value) ? 0 : null;
}
case TokenType.OpenParen:
case TokenType.Function: {
const name =
token[0] === TokenType.Function ? token[4].value.toLowerCase() : 'calc';
if (!['calc', 'min', 'max', 'clamp'].includes(name)) {
return null;
}
const type = parseCalculationSum(state);
if (type === null) {
return null;
}
let count = 1;
while (state.tokens[state.index]![0] === TokenType.Comma) {
state.index++;
if (parseCalculationSum(state) !== type) {
return null;
}
count++;
}
if (
state.tokens[state.index]![0] !== TokenType.CloseParen ||
(name === 'calc' && count !== 1) ||
(name === 'clamp' && count !== 3)
) {
return null;
}
state.index++;
return type;
}
default: {
return null;
}
}
}
/**
* Validate a calculation in a length-percentage context. Types are represented
* as 0 for numbers and 1 for lengths/percentages, with scalar products only.
* @param value - calculation
* @returns whether the calculation has type length-percentage
*/
export const isLengthPercentageCalculation = (value: unknown): boolean => {
if (!isString(value) || !REG_CALC.test(value)) {
return false;
}
const errors: ParseError[] = [];
const state: CalculationState = {
tokens: tokenize(
{ css: value },
{ onParseError: errors.push.bind(errors) }
),
index: 0
};
const type = parseCalculationValue(state);
skipCalculationWhitespace(state);
return (
errors.length === 0 &&
type === 1 &&
state.tokens[state.index]![0] === TokenType.EOF
);
};

581
node_modules/@asamuzakjp/css-color/src/utils/util.ts generated vendored Normal file
View File

@ -0,0 +1,581 @@
/**
* util
*/
import { TokenType, tokenize } from '@csstools/css-tokenizer';
import {
HueArc,
MatchedRegExp,
Options,
SpecifiedColorChannels
} from '../typedef';
import { createCacheKey, getCache, setCache } from './cache';
import { isString } from './common';
/* constants */
import {
ANGLE,
DEC,
DEG,
DEG_HALF,
DUO,
HEX,
MAX_LENGTH,
MAX_PCT,
MAX_RGB,
NONE,
NUM,
PPTH,
TRIA,
VAL_MIX,
VAL_SPEC
} from './constant';
const NAMESPACE = 'util';
const {
CloseParen: PAREN_CLOSE,
Comma: COMMA,
Comment: COMMENT,
Delim: DELIM,
EOF,
Function: FUNC,
OpenParen: PAREN_OPEN,
Whitespace: W_SPACE
} = TokenType;
/* regexp */
const REG_ANGLE_TO_DEG = new RegExp(`^(${NUM})(${ANGLE})?$`);
const REG_COMMA = /^,$/;
const REG_DASHED_IDENT = /--[\w-]+/g;
const REG_SLASH = /^\/$/;
const REG_WHITESPACE = /^\s+$/;
/* absolute font size to pixel ratio */
const absoluteFontSize = new Map([
['xx-small', 9 / 16],
['x-small', 5 / 8],
['small', 13 / 16],
['medium', 1],
['large', 9 / 8],
['x-large', 3 / 2],
['xx-large', 2],
['xxx-large', 3]
]);
/* relative font size to pixel ratio */
const relativeFontSize = new Map([
['smaller', 1 / 1.2],
['larger', 1.2]
]);
/* absolute length to pixel ratio */
const absoluteLength = new Map([
['cm', 96 / 2.54],
['mm', 96 / 25.4],
['q', 96 / 101.6],
['in', 96],
['pc', 16],
['pt', 96 / 72],
['px', 1]
]);
/* relative length to pixel ratio */
const relativeLength = new Map([
['rcap', 1],
['rch', 0.5],
['rem', 1],
['rex', 0.5],
['ric', 1],
['rlh', 1.2]
]);
/**
* get max length
* @param [opt] - options
* @returns max length
*/
export const getMaxLength = (opt: Options = {}): number => {
const { maxLength } = opt;
if (
Number.isInteger(maxLength) &&
(maxLength as number) > 0 &&
(maxLength as number) < MAX_LENGTH
) {
return maxLength as number;
}
return MAX_LENGTH;
};
/**
* split value
* NOTE: comments are stripped, it can be preserved if, in the options param,
* `delimiter` is either ',' or '/' and with `preserveComment` set to `true`
* @param value - CSS value
* @param [opt] - options
* @returns array of values
*/
export const splitValue = (value: string, opt: Options = {}): string[] => {
if (!isString(value)) {
throw new TypeError(`${value} is not a string.`);
}
const options = {
...opt
};
const strValue = value.trim();
const maxLength = getMaxLength(options);
if (!strValue || strValue.length > maxLength) {
return [];
}
const { delimiter = ' ', preserveComment = false } = options;
const cacheKey: string = createCacheKey(
{
namespace: NAMESPACE,
name: 'splitValue',
value: strValue
},
{ delimiter, preserveComment }
);
const cachedResult = getCache<string[]>(cacheKey);
if (cachedResult) {
return [...cachedResult.item];
}
let regDelimiter;
switch (delimiter) {
case ',': {
regDelimiter = REG_COMMA;
break;
}
case '/': {
regDelimiter = REG_SLASH;
break;
}
default: {
regDelimiter = REG_WHITESPACE;
}
}
const tokens = tokenize({ css: strValue });
let nest = 0;
let currentStr = '';
const res: string[] = [];
for (const [type, val] of tokens) {
switch (type) {
case COMMA:
case DELIM: {
if (nest === 0 && regDelimiter.test(val)) {
res.push(currentStr.trim());
currentStr = '';
} else {
currentStr += val;
}
break;
}
case COMMENT: {
if (preserveComment && (delimiter === ',' || delimiter === '/')) {
currentStr += val;
}
break;
}
case FUNC:
case PAREN_OPEN: {
currentStr += val;
nest++;
break;
}
case PAREN_CLOSE: {
currentStr += val;
nest--;
break;
}
case W_SPACE: {
if (regDelimiter.test(val)) {
if (nest === 0) {
if (currentStr) {
res.push(currentStr.trim());
currentStr = '';
}
} else {
currentStr += ' ';
}
} else if (!currentStr.endsWith(' ')) {
currentStr += ' ';
}
break;
}
default: {
if (type === EOF) {
res.push(currentStr.trim());
currentStr = '';
} else {
currentStr += val;
}
}
}
}
setCache(cacheKey, res);
return [...res];
};
/**
* extract dashed-ident tokens
* @param value - CSS value
* @returns array of dashed-ident tokens
*/
export const extractDashedIdent = (value: string): string[] => {
if (!isString(value)) {
throw new TypeError(`${value} is not a string.`);
}
const strValue = value.trim();
if (!strValue) {
return [];
}
const cacheKey: string = createCacheKey({
namespace: NAMESPACE,
name: 'extractDashedIdent',
value: strValue
});
const cachedResult = getCache<string[]>(cacheKey);
if (cachedResult) {
return [...cachedResult.item];
}
const matches = strValue.match(REG_DASHED_IDENT);
const res = matches ? [...new Set(matches)] : [];
setCache(cacheKey, res);
return [...res];
};
/**
* round to specified precision
* @param value - numeric value
* @param bit - minimum bits
* @returns rounded value
*/
export const roundToPrecision = (value: number, bit: number = 0): number => {
if (!Number.isFinite(value)) {
throw new TypeError(`${value} is not a finite number.`);
}
if (!Number.isFinite(bit)) {
throw new TypeError(`${bit} is not a finite number.`);
}
if (bit < 0 || bit > HEX) {
throw new RangeError(`${bit} is not between 0 and ${HEX}.`);
}
if (bit === 0) {
return Math.round(value);
}
const precision = bit === HEX ? 6 : bit < DEC ? 4 : 5;
return parseFloat(value.toPrecision(precision));
};
/**
* interpolate hue
* @param hueA - hue value
* @param hueB - hue value
* @param arc - shorter | longer | increasing | decreasing
* @returns result - [hueA, hueB]
*/
export const interpolateHue = (
hueA: number,
hueB: number,
arc: HueArc | string = 'shorter'
): [number, number] => {
if (!Number.isFinite(hueA)) {
throw new TypeError(`${hueA} is not a finite number.`);
}
if (!Number.isFinite(hueB)) {
throw new TypeError(`${hueB} is not a finite number.`);
}
let a = hueA;
let b = hueB;
switch (arc) {
case 'decreasing': {
if (b > a) {
a += DEG;
}
break;
}
case 'increasing': {
if (b < a) {
b += DEG;
}
break;
}
case 'longer': {
if (b > a && b < a + DEG_HALF) {
a += DEG;
} else if (b > a - DEG_HALF && b <= a) {
b += DEG;
}
break;
}
case 'shorter':
default: {
if (b > a + DEG_HALF) {
a += DEG;
} else if (b < a - DEG_HALF) {
b += DEG;
}
}
}
return [a, b];
};
/**
* resolve length in pixels
* @param value - value
* @param unit - unit
* @param [opt] - options
* @returns pixelated value
*/
export const resolveLengthInPixels = (
value: number | string,
unit: string | undefined,
opt: Options = {}
): number => {
const { dimension = {} } = opt;
const { callback, em, rem, vh, vw } = dimension;
if (isString(value)) {
const str = value.toLowerCase().trim();
const maxLength = getMaxLength(opt);
if (str.length > maxLength) {
return Number.NaN;
}
const ratio = absoluteFontSize.get(str);
if (ratio !== undefined && typeof rem === 'number') {
return ratio * rem;
}
const relRatio = relativeFontSize.get(str);
if (relRatio !== undefined && typeof em === 'number') {
return relRatio * em;
}
return Number.NaN;
}
if (Number.isFinite(value) && unit) {
const u = unit.toLowerCase();
if (Object.hasOwn(dimension, u)) {
const dimVal = dimension[u];
return typeof dimVal === 'number'
? (value as number) * dimVal
: Number.NaN;
}
if (typeof callback === 'function') {
const cbVal = callback(u);
return typeof cbVal === 'number' ? (value as number) * cbVal : Number.NaN;
}
const absRatio = absoluteLength.get(u);
if (absRatio !== undefined) {
return (value as number) * absRatio;
}
const relRatio = relativeLength.get(u);
if (relRatio !== undefined && typeof rem === 'number') {
return (value as number) * relRatio * rem;
}
const rUnitRatio = relativeLength.get(`r${u}`);
if (rUnitRatio !== undefined && typeof em === 'number') {
return (value as number) * rUnitRatio * em;
}
switch (u) {
case 'vb': {
return typeof vh === 'number' ? (value as number) * vh : Number.NaN;
}
case 'vi': {
return typeof vw === 'number' ? (value as number) * vw : Number.NaN;
}
case 'vmax': {
return typeof vh === 'number' && typeof vw === 'number'
? (value as number) * Math.max(vh, vw)
: Number.NaN;
}
case 'vmin': {
return typeof vh === 'number' && typeof vw === 'number'
? (value as number) * Math.min(vh, vw)
: Number.NaN;
}
default:
}
}
// unsupported or invalid value
return Number.NaN;
};
/**
* angle to deg
* @param angle - angle
* @returns deg: 0..360
*/
export const angleToDeg = (angle: string): number => {
if (isString(angle)) {
angle = angle.trim();
} else {
throw new TypeError(`${angle} is not a string.`);
}
const GRAD = DEG / 400;
const RAD = DEG / (Math.PI * DUO);
if (!REG_ANGLE_TO_DEG.test(angle)) {
throw new SyntaxError(`Invalid property value: ${angle}`);
}
const [, value, unit] = angle.match(REG_ANGLE_TO_DEG) as MatchedRegExp;
let deg;
switch (unit) {
case 'grad':
deg = parseFloat(value) * GRAD;
break;
case 'rad':
deg = parseFloat(value) * RAD;
break;
case 'turn':
deg = parseFloat(value) * DEG;
break;
default:
deg = parseFloat(value);
}
deg %= DEG;
if (deg < 0) {
deg += DEG;
} else if (Object.is(deg, -0)) {
deg = 0;
}
return deg;
};
/**
* number to hex string
* @param value - numeric value
* @returns hex string
*/
export const numberToHexString = (value: number): string => {
if (!Number.isFinite(value)) {
throw new TypeError(`${value} is not a number.`);
} else {
value = Math.round(value);
if (value < 0 || value > MAX_RGB) {
throw new RangeError(`${value} is not between 0 and ${MAX_RGB}.`);
}
}
let hex = value.toString(HEX);
if (hex.length === 1) {
hex = `0${hex}`;
}
return hex;
};
/**
* parse alpha
* @param [alpha] - alpha value
* @returns alpha: 0..1
*/
export const parseAlpha = (alpha: string = ''): number => {
if (isString(alpha)) {
alpha = alpha.trim();
if (!alpha) {
alpha = '1';
} else if (alpha === NONE) {
alpha = '0';
} else {
let a;
if (alpha.endsWith('%')) {
a = parseFloat(alpha) / MAX_PCT;
} else {
a = parseFloat(alpha);
}
if (!Number.isFinite(a)) {
throw new TypeError(`${a} is not a finite number.`);
}
if (a < PPTH) {
alpha = '0';
} else if (a > 1) {
alpha = '1';
} else {
alpha = a.toFixed(TRIA);
}
}
} else {
alpha = '1';
}
return parseFloat(alpha);
};
/**
* parse hex alpha
* @param value - alpha value in hex string
* @returns alpha: 0..1
*/
export const parseHexAlpha = (value: string): number => {
if (isString(value)) {
if (value === '') {
throw new SyntaxError('Invalid property value: (empty string)');
}
value = value.trim();
} else {
throw new TypeError(`${value} is not a string.`);
}
let alpha = parseInt(value, HEX);
if (alpha <= 0) {
return 0;
}
if (alpha >= MAX_RGB) {
return 1;
}
const alphaMap = new Map();
for (let i = 1; i < MAX_PCT; i++) {
alphaMap.set(Math.round((i * MAX_RGB) / MAX_PCT), i);
}
if (alphaMap.has(alpha)) {
alpha = alphaMap.get(alpha) / MAX_PCT;
} else {
alpha = Math.round(alpha / MAX_RGB / PPTH) * PPTH;
}
return parseFloat(alpha.toFixed(TRIA));
};
/**
* cache invalid color value
* @param cacheKey - cache key
* @param format - format
* @param nullable - is nullable
* @returns cached value
*/
export const cacheInvalidColorValue = (
cacheKey: string,
format: string,
nullable: boolean = false
): SpecifiedColorChannels | string | null => {
if (format === VAL_SPEC) {
const res = '';
setCache(cacheKey, res);
return res;
}
if (nullable) {
setCache(cacheKey, null);
return null;
}
const res: SpecifiedColorChannels = ['rgb', 0, 0, 0, 0];
setCache(cacheKey, res);
return res;
};
/**
* resolve invalid color value
* @param format - output format
* @param nullable - is nullable
* @returns resolved value
*/
export const resolveInvalidColorValue = (
format: string,
nullable: boolean = false
): SpecifiedColorChannels | string | null => {
switch (format) {
case 'hsl':
case 'hwb':
case VAL_MIX: {
return null;
}
case VAL_SPEC: {
return '';
}
default: {
if (nullable) {
return null;
}
return ['rgb', 0, 0, 0, 0] as SpecifiedColorChannels;
}
}
};

21
node_modules/@asamuzakjp/dom-selector/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 asamuzaK (Kazz)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

268
node_modules/@asamuzakjp/dom-selector/README.md generated vendored Normal file
View File

@ -0,0 +1,268 @@
# DOM Selector
[![build](https://github.com/asamuzaK/domSelector/actions/workflows/node.js.yml/badge.svg)](https://github.com/asamuzaK/domSelector/actions/workflows/node.js.yml)
[![CodeQL](https://github.com/asamuzaK/domSelector/actions/workflows/github-code-scanning/codeql/badge.svg)](https://github.com/asamuzaK/domSelector/actions/workflows/github-code-scanning/codeql)
[![npm (scoped)](https://img.shields.io/npm/v/@asamuzakjp/dom-selector)](https://www.npmjs.com/package/@asamuzakjp/dom-selector)
A CSS selector engine built for strict specification compliance.
## Features
* **Strict Specification Compliance**: Strictly adheres to modern web standards. It accurately parses, evaluates, and extracts elements across complex combinations of pseudo-classes and HTML attributes. Features comprehensive support for CSS Selectors Level 4 (e.g., `:is()`, `:not()`, `:where()`, `:has()`) and Shadow DOM pseudo-classes (`:host`, `:host-context`).
* **Utility Functions**: Provides utility methods alongside standard querying, such as `check()` for AST evaluation and `extractSubjects()` for extracting subject keys from selectors.
* **jsdom's Default Engine**: Adopted as the CSS selector engine for [jsdom](https://github.com/jsdom/jsdom).
## Install
``` console
npm i @asamuzakjp/dom-selector
```
## Usage
``` javascript
import { DOMSelector } from '@asamuzakjp/dom-selector';
import { JSDOM } from 'jsdom';
const { window } = new JSDOM();
// Destructuring methods (all methods are bound to the instance)
const {
check, closest, extractSubjects, matches, querySelector, querySelectorAll, supports
} = new DOMSelector(window);
```
## API
### `new DOMSelector(window, document?, opt?)`
Creates an instance of the DOMSelector.
* `window` **{Window}** The window object.
* `document` **{Document}?** The document object. Defaults to `window.document`.
* `opt` **{object}?** Options:
* `opt.cacheSize` **{number}?** Maximum number of items to store in the internal LRU cache. Defaults to `4096`.
* `opt.idlUtils` **{object}?** The internal IDL wrapper used for jsdom.
* `opt.maxLength` **{number}?** The maximum length of the selector allowed. Defaults to `2048`.
---
### `matches(selector, node, opt?)`
Equivalent to [Element.matches()](https://developer.mozilla.org/docs/Web/API/Element/matches).
* `selector` **{string}** CSS selector.
* `node` **{Element}** Element node.
* `opt` **{object}?** Options:
* `opt.noexcept` **{boolean}?** `true` to suppress exceptions (e.g., `DOMException` for invalid selectors) and return `false` instead.
* `opt.warn` **{boolean}?** `true` to output warnings to the console when encountering unsupported or deprecated features.
* **Returns** **{boolean}** `true` if matched, `false` otherwise.
### `closest(selector, node, opt?)`
Equivalent to [Element.closest()](https://developer.mozilla.org/docs/Web/API/Element/closest).
* `selector` **{string}** CSS selector.
* `node` **{Element}** Element node.
* `opt` **{object}?** Options:
* `opt.noexcept` **{boolean}?** `true` to suppress exceptions and return `null` instead.
* `opt.warn` **{boolean}?** `true` to output warnings to the console when encountering unsupported or deprecated features.
* **Returns** **{Element | null}** The matched ancestor node or `null`.
### `querySelector(selector, node, opt?)`
Equivalent to [Document.querySelector()](https://developer.mozilla.org/docs/Web/API/Document/querySelector), [DocumentFragment.querySelector()](https://developer.mozilla.org/docs/Web/API/DocumentFragment/querySelector) and [Element.querySelector()](https://developer.mozilla.org/docs/Web/API/Element/querySelector).
* `selector` **{string}** CSS selector.
* `node` **{Document | DocumentFragment | Element}** Node to find within.
* `opt` **{object}?** Options:
* `opt.noexcept` **{boolean}?** `true` to suppress exceptions and return `null` instead.
* `opt.warn` **{boolean}?** `true` to output warnings to the console when encountering unsupported or deprecated features.
* **Returns** **{Element | null}** The matched node or `null`.
### `querySelectorAll(selector, node, opt?)`
Equivalent to [Document.querySelectorAll()](https://developer.mozilla.org/docs/Web/API/Document/querySelectorAll), [DocumentFragment.querySelectorAll()](https://developer.mozilla.org/docs/Web/API/DocumentFragment/querySelectorAll) and [Element.querySelectorAll()](https://developer.mozilla.org/docs/Web/API/Element/querySelectorAll).
**NOTE**: Returns a standard `Array<Element>`, not a `NodeList`.
* `selector` **{string}** CSS selector.
* `node` **{Document | DocumentFragment | Element}** Node to find within.
* `opt` **{object}?** Options:
* `opt.noexcept` **{boolean}?** `true` to suppress exceptions and return an empty array `[]` instead.
* `opt.warn` **{boolean}?** `true` to output warnings to the console when encountering unsupported or deprecated features.
* **Returns** **{Array<Element>}** Array of matched elements.
### `check(selector, node, opt?)`
Checks if an element matches a CSS selector and returns additional abstract syntax tree (AST) information.
**NOTE**: Any pseudo-elements in the selector are excluded from the matching evaluation.
* `selector` **{string}** CSS selector.
* `node` **{Element}** Element node.
* `opt` **{object}?** Options:
* `opt.requireAst` **{boolean}?** Indicates whether to always try to parse and return the AST.
* `opt.noexcept` **{boolean}?** `true` to suppress exceptions and store the error in the `error` property of the result instead of throwing.
* `opt.warn` **{boolean}?** `true` to output warnings to the console when encountering unsupported or deprecated features.
* **Returns** **{CheckResult}** An object containing the following properties:
* `match` **{boolean}** `true` if the element matches the selector, `false` otherwise.
* `pseudoElement` **{string | null}** The pseudo-element extracted from the selector, if any.
* `ast` **{object | null}** The parsed AST object.
* `error` **{DOMException | Error | null}** The error object, if any.
### `extractSubjects(selector, caseSensitive?)`
Parses a selector and extracts the rightmost subject keys (Id, Class, Tag).
* `selector` **{string}** CSS selector.
* `caseSensitive` **{boolean}?** `true` if the tag key should be case sensitive. Defaults to `false`.
* **Returns** **{Array<SelectorSubject>}** An array of extracted subject keys. Each object contains:
* `id` **{string | null}** The ID.
* `className` **{string | null}** The class name.
* `tag` **{string | null}** The tag name.
### `supports(selector)`
Checks if the given CSS selector is supported by this engine.
See the table below for the full list of supported selectors.
* `selector` **{string}** CSS selector.
* **Returns** **{boolean}** `true` if the selector is supported, `false` otherwise.
### `clear(clearAll?)`
Clears the internal caches to free up memory.
* `clearAll` **{boolean}?** Whether to clear all caches. If false, only cached matching results are cleared. Defaults to `false`.
* **Returns** **{void}**
## Supported CSS selectors
| Pattern | Supported | Note |
| :--- | :---: | :--- |
| `*` | ✓ | |
| `E` | ✓ | |
| <code>ns\|E</code> | ✓ | |
| <code>*\|E</code> | ✓ | |
| <code>\|E</code> | ✓ | |
| `E F` | ✓ | |
| `E > F` | ✓ | |
| `E + F` | ✓ | |
| `E ~ F` | ✓ | |
| <code>F \|\| E</code> | Unsupported | |
| `E.warning` | ✓ | |
| `E#myid` | ✓ | |
| `E[foo]` | ✓ | |
| `E[foo="bar"]` | ✓ | |
| `E[foo="bar" i]` | ✓ | |
| `E[foo="bar" s]` | ✓ | |
| `E[foo~="bar"]` | ✓ | |
| `E[foo^="bar"]` | ✓ | |
| `E[foo$="bar"]` | ✓ | |
| `E[foo*="bar"]` | ✓ | |
| <code>E[foo\|="en"]</code> | ✓ | |
| `E:is(s1, s2, …)` | ✓ | |
| `E:not(s1, s2, …)` | ✓ | |
| `E:where(s1, s2, …)` | ✓ | |
| `E:has(rs1, rs2, …)` | ✓ | |
| `E:defined` | Partially supported | Matching with MathML is not yet supported. |
| `E:dir(ltr)` | ✓ | |
| `E:lang(en)` | ✓ | |
| `E:any-link` | ✓ | |
| `E:link` | ✓ | |
| `E:visited` | ✓ | Returns `false` or `null` to prevent fingerprinting. |
| `E:local-link` | ✓ | |
| `E:target` | ✓ | |
| `E:target-within` | | Removed from spec. |
| `E:scope` | ✓ | |
| `E:hover` | ✓ | |
| `E:active` | ✓ | |
| `E:focus` | ✓ | |
| `E:focus-visible` | ✓ | |
| `E:focus-within` | ✓ | |
| `E:current` | Unsupported | |
| `E:current(s)` | Unsupported | |
| `E:past` | Unsupported | |
| `E:future` | Unsupported | |
| `E:open` | Partially supported | Matching with `<select>`, e.g. `select:open`, or `<input type="color">` are not supported. |
| `E:popover-open` | Unsupported | |
| `E:enabled`<br>`E:disabled` | ✓ | |
| `E:read-write`<br>`E:read-only` | ✓ | |
| `E:placeholder-shown` | ✓ | |
| `E:default` | ✓ | |
| `E:checked` | ✓ | |
| `E:indeterminate` | ✓ | |
| `E:blank` | Unsupported | |
| `E:valid`<br>`E:invalid` | ✓ | |
| `E:in-range`<br>`E:out-of-range` | ✓ | |
| `E:required`<br>`E:optional` | ✓ | |
| `E:user-valid`<br>`E:user-invalid` | Unsupported | |
| `E:root` | ✓ | |
| `E:empty` | ✓ | |
| `E:nth-child(n [of S]?)` | ✓ | |
| `E:nth-last-child(n [of S]?)` | ✓ | |
| `E:first-child` | ✓ | |
| `E:last-child` | ✓ | |
| `E:only-child` | ✓ | |
| `E:nth-of-type(n)` | ✓ | |
| `E:nth-last-of-type(n)` | ✓ | |
| `E:first-of-type` | ✓ | |
| `E:last-of-type` | ✓ | |
| `E:only-of-type` | ✓ | |
| `E:nth-col(n)` | Unsupported | |
| `E:nth-last-col(n)` | Unsupported | |
| `CE:state(v)` | ✓ | \*1 |
| `:host` | ✓ | |
| `:host(s)` | ✓ | |
| `:host(:state(v))` | ✓ | \*1 |
| `:host:has(rs1, rs2, ...)` | ✓ | |
| `:host(s):has(rs1, rs2, ...)` | ✓ | |
| `:host-context(s)` | ✓ | |
| `:host-context(s):has(rs1, rs2, ...)` | ✓ | |
| `&` | ✓ | Only supports outermost `&`, i.e. equivalent to `:scope` |
\*1: `ElementInternals.states`, i.e. `CustomStateSet`, is not implemented in jsdom, so you need to apply a patch in the custom element constructor.
``` javascript
class LabeledCheckbox extends window.HTMLElement {
#internals;
constructor() {
super();
this.#internals = this.attachInternals();
// patch CustomStateSet
if (!this.#internals.states) {
this.#internals.states = new Set();
}
this.addEventListener('click', this._onClick.bind(this));
}
get checked() {
return this.#internals.states.has('checked');
}
set checked(flag) {
if (flag) {
this.#internals.states.add('checked');
} else {
this.#internals.states.delete('checked');
}
}
_onClick(event) {
this.checked = !this.checked;
}
}
```
## Performance
See [benchmark](https://github.com/asamuzaK/domSelector/actions/workflows/benchmark.yml) for the latest results.
## Acknowledgments
The following resources have been of great help in the development of the DOM Selector.
* [CSSTree](https://github.com/csstree/csstree)
* [selery](https://github.com/danburzo/selery)
* [jsdom](https://github.com/jsdom/jsdom)
* [nwsapi](https://github.com/dperini/nwsapi)
---
Copyright (c) 2023 [asamuzaK (Kazz)](https://github.com/asamuzaK/)

80
node_modules/@asamuzakjp/dom-selector/package.json generated vendored Normal file
View File

@ -0,0 +1,80 @@
{
"name": "@asamuzakjp/dom-selector",
"description": "A CSS selector engine.",
"author": "asamuzaK",
"license": "MIT",
"homepage": "https://github.com/asamuzaK/domSelector#readme",
"bugs": {
"url": "https://github.com/asamuzaK/domSelector/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/asamuzaK/domSelector.git"
},
"files": [
"src",
"types"
],
"type": "module",
"types": "./types/index.d.ts",
"exports": {
".": {
"types": "./types/index.d.ts",
"default": "./src/index.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"bidi-js": "^1.1.0",
"css-tree": "^3.2.1",
"is-potential-custom-element-name": "^1.0.1",
"lru-cache": "^11.5.3"
},
"devDependencies": {
"@types/css-tree": "^3.2.0",
"@types/node": "^26.6.4",
"c8": "^12.0.0",
"chai": "^6.3.0",
"commander": "^15.0.0",
"eslint": "^10.12.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-jsdoc": "^65.0.2",
"eslint-plugin-prettier": "^5.5.6",
"eslint-plugin-regexp": "^3.3.1",
"eslint-plugin-unicorn": "^76.0.0",
"globals": "^17.13.0",
"jsdom": "^30.1.1",
"mitata": "^1.0.34",
"mocha": "^12.0.3",
"neostandard": "^0.14.0-next.1",
"prettier": "^3.9.9",
"sinon": "^22.1.0",
"tinybench": "^6.2.0",
"typescript": "^7.0.2",
"wpt-runner": "^7.0.0"
},
"overrides": {
"jsdom": "$jsdom"
},
"scripts": {
"bench": "node --expose-gc benchmark/bench.js",
"bench:cache": "node --expose-gc benchmark/bench-cache.js",
"bench:nwsapi": "node --expose-gc benchmark/bench-nwsapi.js",
"bench:ps-form": "node --expose-gc benchmark/bench-default.js && node --expose-gc benchmark/bench-indeterminate.js && node --expose-gc benchmark/bench-valid-invalid.js",
"bench:ps-has": "node --expose-gc benchmark/bench-has.js",
"bench:ps-nth": "node --expose-gc benchmark/bench-nth-child.js && node --expose-gc benchmark/bench-nth-of-type.js",
"bench:ps-traverse": "node --expose-gc benchmark/bench-dir.js && node --expose-gc benchmark/bench-lang.js",
"bench:tl": "node --expose-gc benchmark/bench-testing-library.js",
"bench:universal": "node --expose-gc benchmark/bench-universal.js",
"build": "npm run tsc && npm run lint && npm test",
"lint": "eslint --fix .",
"test": "c8 --reporter=text mocha --exit test/**/*.test.js",
"test:wpt": "node test/wpt/wpt-runner.js",
"tsc": "node scripts/index clean --dir=types -i && npx tsc",
"update:wpt": "git submodule update --init --recursive --remote"
},
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
"version": "9.2.4"
}

590
node_modules/@asamuzakjp/dom-selector/src/index.js generated vendored Normal file
View File

@ -0,0 +1,590 @@
/*!
* DOM Selector - A CSS selector engine.
* @license MIT
* @copyright asamuzaK (Kazz)
* @see {@link https://github.com/asamuzaK/domSelector/blob/main/LICENSE}
*/
/* import */
import { LRUCache } from 'lru-cache';
import { clone as cssTreeClone } from 'css-tree/utils';
import { Finder } from './js/finder.js';
import { Nwsapi } from './js/nwsapi.js';
import { extractSubjectsAst, parseSelector } from './js/parser.js';
import {
extractSubjectsRegExp,
filterSelector,
isSupportedAST
} from './js/selector.js';
import {
collectAllDescendants,
findByExactIdAttribute,
findBySimpleAttribute,
getType,
stringifyValue
} from './js/utility.js';
/* constants */
import {
DOCUMENT_NODE,
ELEMENT_NODE,
MIME_HTML,
NS_HTML,
TARGET_ALL,
TARGET_FIRST,
TARGET_LINEAL,
TARGET_SELF
} from './js/constant.js';
const CACHE_SIZE = 4096;
const MAX_LENGTH = 2048;
const DEFAULT_SUBJECT = Object.freeze({ id: null, className: null, tag: null });
/* regexp */
const REG_SELECTOR = /[[\]():\\"'`]/;
const REG_UNIVERSAL = /^\s*(?:\*\|)?\*\s*$/;
/* types */
/**
* @typedef {object} CheckResult
* @property {boolean} match - The match result.
* @property {string|null} pseudoElement - The pseudo-element, if any.
* @property {import('css-tree').CssNode|null} ast - The AST object.
* @property {DOMException|Error|null} error - The error object, or null.
*/
/**
* @typedef {object} SelectorSubject
* @property {string|null} id - The ID.
* @property {string|null} className - The class name.
* @property {string|null} tag - The tag name.
*/
/**
* @typedef {object} UserOptions
* @property {boolean} [noexcept] - True to suppress exceptions.
* @property {boolean} [warn] - True to enable console warnings.
*/
/**
* @typedef {object} FindOptions
* @property {string} [dir] - The traversal direction.
* @property {boolean} [check] - Indicates if running in internal check mode.
* @property {boolean} [forgive] - True to ignore unknown or invalid selectors.
* @property {boolean} [noexcept] - True to suppress exceptions.
* @property {boolean} [warn] - True to enable console warnings.
* @property {boolean} [isShadowRoot] - Indicates if the node is a ShadowRoot.
* @property {object} [globalObject] - The Window object.
*/
/* DOMSelector */
export class DOMSelector {
/* private fields */
#cache;
#cacheSize;
#document;
#finder;
#idlUtils;
#maxLength;
#nwsapi;
#window;
/**
* Creates an instance of DOMSelector.
* @param {Window} window - The Window object.
* @param {Document} document - The Document object.
* @param {object} [opt] - Options.
* @param {number} [opt.cacheSize] - The maximum size of the LRU cache.
* @param {object} [opt.idlUtils] - The internal IDL wrapper used for jsdom.
* @param {number} [opt.maxLength] - The maximum length of the selector.
*/
constructor(window, document, opt = {}) {
const { cacheSize, idlUtils, maxLength } = opt;
this.#idlUtils = idlUtils;
this.#window = window;
this.#document = document ? this.#wrapNode(document) : window.document;
this.#maxLength =
Number.isInteger(maxLength) && maxLength > 0 ? maxLength : MAX_LENGTH;
this.#cacheSize =
Number.isInteger(cacheSize) && cacheSize > 0 ? cacheSize : CACHE_SIZE;
this.#cache = new LRUCache({
max: this.#cacheSize
});
this.#finder = new Finder(this.#window);
this.#nwsapi = new Nwsapi(this.#window, this.#document, this.#cacheSize);
}
/**
* Clears the internal caches.
* @param {boolean} [clearAll] - True to clear all caches. If false, only
* cached matching results are cleared.
* @returns {void}
*/
clear(clearAll = false) {
if (clearAll) {
this.#cache.clear();
}
this.#finder.clearResults(true);
this.#nwsapi.clear(clearAll);
}
/**
* Parses a selector and extracts the rightmost subject keys (Id, Class, Tag).
* @param {string} selector - The CSS selector to parse.
* @param {boolean} [caseSensitive] - True if key should be case sensitive.
* @returns {Array<SelectorSubject>} The list of selector subjects.
*/
extractSubjects(selector, caseSensitive = false) {
if (!selector || typeof selector !== 'string') {
return [DEFAULT_SUBJECT];
}
const { error, selector: validatedSelector } =
this.#validateSelector(selector);
if (error) {
return [DEFAULT_SUBJECT];
}
selector = validatedSelector;
const cacheKey = `extract_${selector}_${caseSensitive}`;
let subjects = this.#cache.get(cacheKey);
if (subjects !== undefined) {
return [...subjects];
}
subjects = [];
if (!REG_SELECTOR.test(selector)) {
subjects = extractSubjectsRegExp(selector, caseSensitive);
} else {
try {
const ast = parseSelector(selector);
subjects = extractSubjectsAst(ast);
} catch {
// fall through
}
}
if (!subjects.length) {
subjects.push(DEFAULT_SUBJECT);
}
this.#cache.set(cacheKey, subjects);
return [...subjects];
}
/**
* Checks if the given CSS selector is supported by this engine.
* @param {string} selector - The CSS selector to check.
* @returns {boolean} True if the selector is supported, false otherwise.
*/
supports(selector) {
if (typeof selector !== 'string') {
return false;
}
const { error, selector: validatedSelector } =
this.#validateSelector(selector);
if (error) {
return false;
}
selector = validatedSelector;
const cacheKey = `supports_${selector}`;
let isSupported = this.#cache.get(cacheKey);
if (isSupported !== undefined) {
return isSupported;
}
if (filterSelector(selector, TARGET_SELF)) {
isSupported = true;
} else {
try {
const ast = parseSelector(selector);
isSupported = isSupportedAST(ast);
} catch {
isSupported = false;
}
}
this.#cache.set(cacheKey, isSupported);
return isSupported;
}
/**
* Checks if an element matches a CSS selector.
* @param {string} selector - The CSS selector to check against.
* @param {Element} node - The element node to check.
* @param {object} [opt] - Optional parameters.
* @param {boolean} [opt.requireAst] - Indicates always try to parse AST.
* @returns {CheckResult} An object containing the check result.
*/
check(selector, node, opt = {}) {
const { error, selector: validatedSelector } =
this.#validateSelector(selector);
if (error) {
return {
error,
ast: null,
match: false,
pseudoElement: null
};
}
selector = validatedSelector;
node = this.#wrapNode(node);
const nodeError = this.#validateNodeType(node, true);
if (nodeError) {
let ast = null;
if (opt.requireAst) {
const astCacheKey = `check_ast_${selector}`;
ast = this.#cache.get(astCacheKey);
if (ast === undefined) {
ast = parseSelector(selector);
this.#cache.set(astCacheKey, ast);
}
}
return {
ast: this.#cloneAST(ast),
error: nodeError,
match: false,
pseudoElement: null
};
}
if (REG_UNIVERSAL.test(selector)) {
const astCacheKey = `check_ast_${selector.trim()}`;
let ast = this.#cache.get(astCacheKey);
if (ast === undefined) {
ast = parseSelector(selector);
this.#cache.set(astCacheKey, ast);
}
return {
ast: this.#cloneAST(ast),
error: null,
match: true,
pseudoElement: null
};
}
const nwsapiRes = this.#tryNwsapi(
selector,
node,
TARGET_SELF,
n => this.#nwsapi.match(selector, n),
true
);
if (nwsapiRes.success) {
let ast = null;
if (nwsapiRes.result || opt.requireAst) {
const astCacheKey = `check_ast_${selector}`;
ast = this.#cache.get(astCacheKey);
if (ast === undefined) {
ast = parseSelector(selector);
this.#cache.set(astCacheKey, ast);
}
}
return {
ast: this.#cloneAST(ast),
error: null,
match: nwsapiRes.result,
pseudoElement: null
};
}
const options = {
check: true,
noexcept: true,
warn: false,
globalObject: this.#window
};
const checkResult = this.#finder
.setup(selector, node, options)
.find(TARGET_SELF);
return {
...checkResult,
ast: this.#cloneAST(checkResult.ast)
};
}
/**
* Returns true if the element matches the selector.
* @param {string} selector - The CSS selector to match against.
* @param {Element} node - The element node to test.
* @param {UserOptions} [opt] - User options.
* @returns {boolean} True if the element matches, false otherwise.
*/
matches(selector, node, opt = {}) {
const options = {
...opt,
check: false,
globalObject: this.#window
};
const { error, selector: validatedSelector } =
this.#validateSelector(selector);
if (error) {
this.#finder.onError(error, options);
return false;
}
selector = validatedSelector;
node = this.#wrapNode(node);
const nodeError = this.#validateNodeType(node, true);
if (nodeError) {
this.#finder.onError(nodeError, options);
return false;
}
if (REG_UNIVERSAL.test(selector)) {
return true;
}
const nwsapiRes = this.#tryNwsapi(selector, node, TARGET_SELF, n =>
this.#nwsapi.match(selector, n)
);
if (nwsapiRes.success) {
return nwsapiRes.result;
}
const nodes = this.#findNodes(selector, node, options, TARGET_SELF);
return !!(nodes && nodes.size > 0);
}
/**
* Traverses up the DOM tree to find the first node that matches the selector.
* @param {string} selector - The CSS selector to match against.
* @param {Element} node - The element from which to start traversing.
* @param {UserOptions} [opt] - User options.
* @returns {Element|null} The first matching ancestor element, or `null`.
*/
closest(selector, node, opt = {}) {
const options = {
...opt,
check: false,
globalObject: this.#window
};
const { error, selector: validatedSelector } =
this.#validateSelector(selector);
if (error) {
this.#finder.onError(error, options);
return null;
}
selector = validatedSelector;
node = this.#wrapNode(node);
const nodeError = this.#validateNodeType(node, true);
if (nodeError) {
return this.#finder.onError(nodeError, options);
}
if (REG_UNIVERSAL.test(selector)) {
return node;
}
const nwsapiRes = this.#tryNwsapi(selector, node, TARGET_LINEAL, n =>
this.#nwsapi.closest(selector, n)
);
if (nwsapiRes.success) {
return nwsapiRes.result;
}
const nodes = this.#findNodes(selector, node, options, TARGET_LINEAL);
if (nodes && nodes.size) {
let refNode = node;
while (refNode) {
if (nodes.has(refNode)) {
return refNode;
}
refNode = refNode.parentNode;
}
}
return null;
}
/**
* Returns the first element within the subtree that matches the selector.
* @param {string} selector - The CSS selector to match.
* @param {Document|DocumentFragment|Element} node - The node to find within.
* @param {UserOptions} [opt] - User options.
* @returns {Element|null} The first matching element, or `null`.
*/
querySelector(selector, node, opt = {}) {
const options = {
...opt,
check: false,
globalObject: this.#window
};
const { error, selector: validatedSelector } =
this.#validateSelector(selector);
if (error) {
this.#finder.onError(error, options);
return null;
}
selector = validatedSelector;
node = this.#wrapNode(node);
const nodeError = this.#validateNodeType(node);
if (nodeError) {
this.#finder.onError(nodeError, options);
return null;
}
if (REG_UNIVERSAL.test(selector)) {
return node.firstElementChild;
}
const fastNode = findByExactIdAttribute(selector, node);
if (fastNode === null || fastNode?.nodeType === ELEMENT_NODE) {
return fastNode;
}
const nodes = this.#findNodes(selector, node, options, TARGET_FIRST);
if (nodes && nodes.size) {
return nodes.values().next().value;
}
return null;
}
/**
* Returns an array of elements within the subtree that match the selector.
* Note: This method returns an Array, not a NodeList.
* @param {string} selector - The CSS selector to match.
* @param {Document|DocumentFragment|Element} node - The node to find within.
* @param {UserOptions} [opt] - User options.
* @returns {Array<Element>} An array of elements, or an empty array.
*/
querySelectorAll(selector, node, opt = {}) {
const options = {
...opt,
check: false,
globalObject: this.#window
};
const { error, selector: validatedSelector } =
this.#validateSelector(selector);
if (error) {
this.#finder.onError(error, options);
return [];
}
selector = validatedSelector;
node = this.#wrapNode(node);
const nodeError = this.#validateNodeType(node);
if (nodeError) {
this.#finder.onError(nodeError, options);
return [];
}
if (REG_UNIVERSAL.test(selector)) {
const document =
node.nodeType === DOCUMENT_NODE ? node : node.ownerDocument;
return collectAllDescendants(node, document);
}
const fastNodes = findBySimpleAttribute(selector, node);
if (Array.isArray(fastNodes)) {
return fastNodes;
}
const nodes = this.#findNodes(selector, node, options, TARGET_ALL);
if (nodes && nodes.size) {
return [...nodes];
}
return [];
}
/**
* Generates a cloned selector AST.
* @private
* @param {import('css-tree').CssNode|null} ast - The selector AST.
* @returns {import('css-tree').CssNode|null} Cloned selector AST.
*/
#cloneAST(ast) {
if (!ast) {
return null;
}
return cssTreeClone(ast);
}
/**
* Wraps the node for IDL internal implementation if idlUtils is present.
* @private
* @param {Document|DocumentFragment|Element} node - The raw node.
* @returns {object} The wrapped or raw node.
*/
#wrapNode(node) {
return this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node;
}
/**
* Validates a selector.
* @private
* @param {string} selector - The selector to check.
* @returns {{ selector:string|null, error:DOMException|RangeError|null}} The validation result.
*/
#validateSelector(selector) {
try {
selector = stringifyValue(selector, this.#window);
if (selector.length > this.#maxLength) {
return {
selector: null,
error: new this.#window.RangeError(
`Selector exceeds maximum allowed length of ${this.#maxLength}.`
)
};
}
return {
selector,
error: null
};
} catch (e) {
return {
selector: null,
error: e
};
}
}
/**
* Validates a node.
* @private
* @param {Document|DocumentFragment|Element} node - The node to check.
* @param {boolean} [element] - `true` if the node must be an Element.
* @returns {TypeError|null} A TypeError if invalid, otherwise null.
*/
#validateNodeType(node, element = false) {
if (!node?.nodeType) {
return new this.#window.TypeError(`Unexpected type ${getType(node)}`);
}
if (element && node.nodeType !== ELEMENT_NODE) {
return new this.#window.TypeError(`Unexpected node ${node.nodeName}`);
}
return null;
}
/**
* Executes Nwsapi matching logic with caching and error wrapping.
* @private
* @param {string} selector - The CSS selector to match against.
* @param {Element} node - The target node to check.
* @param {number} targetType - The target type indicating the scope.
* @param {(node: Element) => Array<Element>|Element|boolean|null} callback - The specific nwsapi function.
* @param {boolean} [isCheck] - True if called from the check method.
* @returns {{success: boolean, result: Array<Element>|Element|boolean|null}} An object indicating whether the execution succeeded and its result.
*/
#tryNwsapi(selector, node, targetType, callback, isCheck = false) {
const document = node.ownerDocument;
if (
node.isConnected &&
node.namespaceURI === NS_HTML &&
document === this.#document &&
document.contentType === MIME_HTML &&
document.documentElement
) {
const cacheKey = `${isCheck ? 'check' : targetType}_${selector}`;
let filterMatches = this.#cache.get(cacheKey);
if (filterMatches === undefined) {
filterMatches = filterSelector(selector, targetType);
this.#cache.set(cacheKey, filterMatches);
}
if (filterMatches) {
try {
const result = callback(node);
return { result, success: true };
} catch {
// fall through
}
}
}
return { result: null, success: false };
}
/**
* Encapsulates Finder traversal logic and error handling.
* @private
* @param {string} selector - The CSS selector to match against.
* @param {Document|DocumentFragment|Element} node - The node from which to start searching.
* @param {FindOptions} [opt] - The finder options.
* @param {number} targetType - The target type indicating the scope.
* @returns {Set<Element>|null} The search results from Finder, or null.
*/
#findNodes(selector, node, opt, targetType) {
try {
const res = this.#finder.setup(selector, node, opt).find(targetType);
if (res instanceof Set) {
return res;
}
} catch (e) {
this.#finder.onError(e, opt);
}
return null;
}
}

View File

@ -0,0 +1,307 @@
/**
* constant.js
*/
/* string */
export const ATRULE = 'Atrule';
export const ATTR_SELECTOR = 'AttributeSelector';
export const CLASS_SELECTOR = 'ClassSelector';
export const COMBINATOR = 'Combinator';
export const DIR_NEXT = 'next';
export const DIR_PREV = 'prev';
export const IDENT = 'Identifier';
export const ID_SELECTOR = 'IdSelector';
export const NEST_SELECTOR = 'NestingSelector';
export const NOT_SUPPORTED_ERR = 'NotSupportedError';
export const NTH = 'Nth';
export const OPERATOR = 'Operator';
export const PS_CLASS_SELECTOR = 'PseudoClassSelector';
export const PS_ELEMENT_SELECTOR = 'PseudoElementSelector';
export const RULE = 'Rule';
export const SCOPE = 'Scope';
export const SELECTOR = 'Selector';
export const SELECTOR_LIST = 'SelectorList';
export const STRING = 'String';
export const SYNTAX_ERR = 'SyntaxError';
export const TARGET_ALL = 'all';
export const TARGET_FIRST = 'first';
export const TARGET_LINEAL = 'lineal';
export const TARGET_SELF = 'self';
export const TYPE_SELECTOR = 'TypeSelector';
/* numeric */
export const BIT_01 = 1;
export const BIT_02 = 2;
export const BIT_04 = 4;
export const BIT_08 = 8;
export const BIT_16 = 0x10;
export const BIT_32 = 0x20;
export const BIT_FFFF = 0xffff;
export const DUO = 2;
export const HEX = 16;
export const TYPE_FROM = 8;
export const TYPE_TO = -1;
/* Node */
export const ELEMENT_NODE = 1;
export const TEXT_NODE = 3;
export const DOCUMENT_NODE = 9;
export const DOCUMENT_FRAGMENT_NODE = 11;
export const DOCUMENT_POSITION_PRECEDING = 2;
export const DOCUMENT_POSITION_CONTAINS = 8;
export const DOCUMENT_POSITION_CONTAINED_BY = 0x10;
/* NodeFilter */
export const FILTER_ACCEPT = 1;
export const FILTER_REJECT = 2;
export const FILTER_SKIP = 3;
export const SHOW_ALL = 0xffffffff;
export const SHOW_CONTAINER = 0x501;
export const SHOW_DOCUMENT = 0x100;
export const SHOW_DOCUMENT_FRAGMENT = 0x400;
export const SHOW_ELEMENT = 1;
/* selectors */
export const ALPHA_NUM = '[A-Z\\d]+';
export const CHILD_IDX = '(?:first|last|only)-(?:child|of-type)';
export const DIGIT = '(?:0|[1-9]\\d*)';
export const LANG_ALPHA_NUM = '[A-Z\\d]{1,8}';
export const LANG_SKIP_ALPHA_NUM = '[A-Z\\d]{2,8}';
export const LANG_PART = `(?:-${LANG_ALPHA_NUM})*`;
export const LANG_PART_SKIP = `(?:-${LANG_SKIP_ALPHA_NUM})*`;
export const PSEUDO_CLASS = `(?:any-)?link|${CHILD_IDX}|checked|empty|indeterminate|read-(?:only|write)|target`;
export const ANB = `[+-]?(?:${DIGIT}n?|n)|(?:[+-]?${DIGIT})?n\\s*[+-]\\s*${DIGIT}`;
// combinators
export const COMBO = '\\s?[\\s>~+]\\s?';
export const DESCEND = '\\s?[\\s>]\\s?';
export const SIBLING = '\\s?[+~]\\s?';
// LOGIC_IS: :is()
export const LOGIC_IS = `:is\\(\\s*[^)]+\\s*\\)`;
// N_TH: excludes An+B with selector list, e.g. :nth-child(2n+1 of .foo)
export const N_TH = `nth-(?:last-)?(?:child|of-type)\\(\\s*(?:even|odd|${ANB})\\s*\\)`;
// ATTR_TYPE: excludes [foo|=bar]
export const ATTR_TYPE = '\\[[^|\\]]+\\]';
// SUB_TYPE: attr, id, class, pseudo-class
export const SUB_TYPE = `${ATTR_TYPE}|[#.:][\\w-]+`;
export const SUB_TYPE_WO_PSEUDO = `${ATTR_TYPE}|[#.][\\w-]+`;
// TAG_TYPE: *, tag
export const TAG_TYPE_WO_UNIVERSAL = '[A-Za-z][\\w-]*';
export const TAG_TYPE = `\\*|${TAG_TYPE_WO_UNIVERSAL}`;
export const TAG_TYPE_I = '\\*|[A-Z][\\w-]*';
export const COMPOUND = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE})+)`;
export const COMPOUND_L = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE}|${LOGIC_IS})+)`;
export const COMPOUND_I = `(?:${TAG_TYPE_I}|(?:${TAG_TYPE_I})?(?:${SUB_TYPE})+)`;
export const COMPOUND_WO_PSEUDO = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE_WO_PSEUDO})+)`;
export const COMPLEX = `${COMPOUND}(?:${COMBO}${COMPOUND})*`;
export const COMPLEX_L = `${COMPOUND_L}(?:${COMBO}${COMPOUND_L})*`;
export const HAS_COMPOUND = `has\\([\\s>]?\\s*${COMPOUND_WO_PSEUDO}\\s*\\)`;
export const LOGIC_COMPOUND = `(?:is|not)\\(\\s*${COMPOUND_L}(?:\\s*,\\s*${COMPOUND_L})*\\s*\\)`;
export const LOGIC_COMPLEX = `(?:is|not)\\(\\s*${COMPLEX_L}(?:\\s*,\\s*${COMPLEX_L})*\\s*\\)`;
/* forms and input types */
/** @type {Array<string>} */
export const FORM_PARTS = Object.freeze([
'button',
'input',
'select',
'textarea'
]);
/** @type {Array<string>} */
export const INPUT_BUTTON = Object.freeze(['button', 'reset', 'submit']);
/** @type {Array<string>} */
export const INPUT_CHECK = Object.freeze(['checkbox', 'radio']);
/** @type {Array<string>} */
export const INPUT_DATE = Object.freeze([
'date',
'datetime-local',
'month',
'time',
'week'
]);
/** @type {Array<string>} */
export const INPUT_TEXT = Object.freeze([
'email',
'password',
'search',
'tel',
'text',
'url'
]);
/** @type {Array<string>} */
export const INPUT_EDIT = Object.freeze([
...INPUT_DATE,
...INPUT_TEXT,
'number'
]);
/** @type {Array<string>} */
export const INPUT_LTR = Object.freeze([
...INPUT_CHECK,
'color',
'date',
'image',
'number',
'range',
'time'
]);
/* Attribute names that must treat values as ASCII case-insensitive */
/** @type {Array<string>} */
export const ATTR_VALUE_I = Object.freeze([
'accept',
'accept-charset',
'align',
'alink',
'axis',
'bgcolor',
'charset',
'checked',
'clear',
'codetype',
'color',
'compact',
'declare',
'defer',
'dir',
'direction',
'disabled',
'enctype',
'face',
'frame',
'hreflang',
'http-equiv',
'lang',
'language',
'link',
'media',
'method',
'multiple',
'nohref',
'noresize',
'noshade',
'nowrap',
'readonly',
'rel',
'rev',
'rules',
'scope',
'scrolling',
'selected',
'shape',
'target',
'text',
'type',
'valign',
'valuetype',
'vlink'
]);
/* logical combination pseudo-classes */
/** @type {Set<string>} */
export const KEYS_LOGICAL = new Set(['has', 'is', 'not', 'where']);
/* lists of supported / unsupported pseudo-classes and pseudo-elements */
/** @type {Set<string>} */
export const KEYS_PS_CLASS_SUPPORTED = new Set([
'active',
'any-link',
'checked',
'closed',
'default',
'defined',
'dir',
'disabled',
'empty',
'enabled',
'first-child',
'first-of-type',
'focus',
'focus-visible',
'focus-within',
'has',
'host',
'host-context',
'hover',
'in-range',
'indeterminate',
'invalid',
'is',
'lang',
'last-child',
'last-of-type',
'link',
'local-link',
'not',
'nth-child',
'nth-last-child',
'nth-last-of-type',
'nth-of-type',
'only-child',
'only-of-type',
'open',
'optional',
'out-of-range',
'placeholder-shown',
'read-only',
'read-write',
'required',
'root',
'scope',
'state',
'target',
'target-within',
'valid',
'visited',
'where'
]);
/** @type {Set<string>} */
export const KEYS_PS_CLASS_UNSUPPORTED = new Set([
'autofill',
'blank',
'buffering',
'contains',
'current',
'fullscreen',
'future',
'has-slotted',
'heading',
'modal',
'muted',
'nth-col',
'nth-last-col',
'past',
'paused',
'picture-in-picture',
'playing',
'popover-open',
'seeking',
'stalled',
'user-invalid',
'user-valid',
'volume-locked',
'-webkit-autofill'
]);
/** @type {Set<string>} */
export const KEYS_PS_ELEMENT_UNSUPPORTED = new Set([
'after',
'backdrop',
'before',
'cue',
'cue-region',
'file-selector-button',
'first-letter',
'first-line',
'marker',
'part',
'placeholder',
'selection',
'slotted',
'target-text'
]);
/* mime type and namespace */
/** @type {string} */
export const MIME_HTML = 'text/html';
/** @type {string} */
export const NS_HTML = 'http://www.w3.org/1999/xhtml';

View File

@ -0,0 +1,429 @@
/**
* evaluator.js
*/
/* import */
import { EventHandler } from './event.js';
import {
matchAttributeSelector,
matchPseudoElementSelector,
matchTypeSelector
} from './matcher.js';
import { generateCSS, parseSelector, unescapeSelector } from './parser.js';
import { PseudoClassEvaluator } from './pseudo-class.js';
import { ShadowDOMEvaluator } from './shadow.js';
import { DOMTraverser } from './traverser.js';
import { resolveContent } from './utility.js';
/* constants */
import {
ATTR_SELECTOR,
CLASS_SELECTOR,
DOCUMENT_FRAGMENT_NODE,
ELEMENT_NODE,
FORM_PARTS,
ID_SELECTOR,
NEST_SELECTOR,
NOT_SUPPORTED_ERR,
PS_CLASS_SELECTOR,
TYPE_SELECTOR
} from './constant.js';
const KEYS_FORM = new Set([...FORM_PARTS, 'fieldset', 'form']);
const KEYS_UNCACHE = new Set(['any-link', 'defined', 'dir', 'link', 'scope']);
/**
* Evaluator
* Determines if DOM elements match provided CSS selectors.
*/
export class Evaluator {
/* private fields */
#domTraverser;
#eventHandler;
#filterLeavesCache;
#invalidate;
#invalidateResults;
#nestingAST;
#pseudoClassEvaluator;
#results;
#shadowEvaluator;
#unescapedCache;
/**
* @param {Window} window - The window object.
*/
constructor(window) {
this.window = window;
this.documentCache = new WeakMap();
this.#domTraverser = new DOMTraverser(this);
this.#eventHandler = new EventHandler(window);
this.#pseudoClassEvaluator = new PseudoClassEvaluator(this);
this.#shadowEvaluator = new ShadowDOMEvaluator(this);
this.#unescapedCache = new WeakMap();
this.clearResults(true);
}
/**
* Gets the event handler.
* @returns {EventHandler} The EventHandler instance.
*/
get eventHandler() {
return this.#eventHandler;
}
/**
* Gets the invalidate flag.
* @returns {boolean} True if the selector should be invalidated, false otherwise.
*/
get invalidate() {
return this.#invalidate;
}
/**
* Sets the invalidate flag.
* @param {boolean} value - A flag to set.
*/
set invalidate(value) {
this.#invalidate = !!value;
}
/**
* Gets the verifyShadowHost flag from ShadowDOMEvaluator.
* @returns {boolean} True if shadow host is verified, false otherwise.
*/
get verifyShadowHost() {
return this.#shadowEvaluator.verifyShadowHost;
}
/**
* Sets up the evaluator.
* @param {string} selector - The CSS selector.
* @param {Document|DocumentFragment|Element} node - Document, DocumentFragment, or Element.
* @param {import('../index.js').FindOptions} [opt] - Options.
* @returns {Evaluator} The Evaluator instance.
*/
setup(selector, node, opt = {}) {
const { check, noexcept, warn } = opt;
this.check = !!check;
this.noexcept = !!noexcept;
this.warn = !!warn;
[this.document, this.root, this.shadow] = resolveContent(node);
this.node = node;
this.pseudoElements = [];
this.#invalidate = false;
this.#domTraverser.reset();
this.#shadowEvaluator.reset();
this.#pseudoClassEvaluator.reset();
this.clearResults();
return this;
}
/**
* Handles errors.
* @param {Error} e - The error object.
* @param {import('../index.js').FindOptions} [opt] - Options.
* @throws {Error} Throws an error.
* @returns {void}
*/
onError(e, opt = {}) {
const noexcept = opt.noexcept ?? this.noexcept;
if (noexcept) {
return;
}
const isDOMException =
e instanceof DOMException || e instanceof this.window.DOMException;
if (isDOMException) {
if (e.name === NOT_SUPPORTED_ERR) {
if (this.warn) {
console.warn(e.message);
}
return;
}
throw new this.window.DOMException(e.message, e.name);
}
const ErrorCtor = this.window[e.name];
if (typeof ErrorCtor === 'function') {
throw new ErrorCtor(e.message, { cause: e });
}
throw e;
}
/**
* Destroys the evaluator instance and removes external event listeners.
*/
destroy() {
this.clearResults(true);
if (this.#eventHandler) {
this.#eventHandler.destroy();
}
}
/**
* Clear cached results.
* @param {boolean} all - Clear all results.
* @returns {void}
*/
clearResults(all = false) {
this.#invalidate = false;
this.#invalidateResults = null;
this.#pseudoClassEvaluator.clearResults(all);
if (all) {
this.#filterLeavesCache = null;
this.#nestingAST = null;
this.#results = new WeakMap();
}
}
/**
* Matches a selector.
* @param {import('css-tree').CssNode} ast - The AST.
* @param {Document|DocumentFragment|Element} node - The Document, DocumentFragment, or Element node.
* @param {import('../index.js').FindOptions} opt - Options.
* @returns {boolean} True if matches, otherwise false.
*/
matchSelector(ast, node, opt) {
if (node.nodeType === ELEMENT_NODE) {
return this.#matchSelectorForElement(ast, node, opt);
}
if (
this.shadow &&
node.nodeType === DOCUMENT_FRAGMENT_NODE &&
ast.type === PS_CLASS_SELECTOR
) {
return this.#shadowEvaluator.matchSelectorForShadowRoot(ast, node, opt);
}
return false;
}
/**
* Matches leaves against a node with cache check.
* @param {Array<import('css-tree').CssNode>} leaves - The AST leaves to match.
* @param {Element} node - The Element node.
* @param {import('../index.js').FindOptions} [opt] - Options.
* @returns {boolean} True if matched, otherwise false.
*/
matchLeaves(leaves, node, opt) {
let isFormParts;
if (leaves.length === 1) {
const [leaf] = leaves;
const isUncacheable =
leaf.type === ATTR_SELECTOR ||
leaf.type === ID_SELECTOR ||
(leaf.type === PS_CLASS_SELECTOR && KEYS_UNCACHE.has(leaf.name));
if (!isUncacheable) {
isFormParts =
node.nodeType === ELEMENT_NODE && KEYS_FORM.has(node.localName);
}
if (isUncacheable || isFormParts) {
return this.matchSelector(
leaf,
node,
opt ?? {
warn: this.warn,
globalObject: this.window
}
);
}
}
let results;
if (this.invalidate) {
if (!this.#invalidateResults) {
this.#invalidateResults = new WeakMap();
}
results = this.#invalidateResults;
} else {
results = this.#results;
}
let result = results.get(leaves);
if (result) {
const nodeResult = result.get(node);
if (nodeResult !== undefined) {
return nodeResult;
}
}
isFormParts ??=
node.nodeType === ELEMENT_NODE && KEYS_FORM.has(node.localName);
let cacheable = !isFormParts;
let bool;
const l = leaves.length;
for (let i = 0; i < l; i++) {
const leaf = leaves[i];
switch (leaf.type) {
case ATTR_SELECTOR:
case ID_SELECTOR: {
cacheable = false;
break;
}
case PS_CLASS_SELECTOR: {
if (KEYS_UNCACHE.has(leaf.name)) {
cacheable = false;
}
break;
}
default: {
// No action needed for other types.
}
}
bool = this.matchSelector(
leaf,
node,
opt ?? {
warn: this.warn,
globalObject: this.window
}
);
if (!bool) {
break;
}
}
if (cacheable) {
if (!result) {
result = new WeakMap();
}
result.set(node, bool);
results.set(leaves, result);
}
return bool;
}
/**
* Returns a cached slice of the leaves array (excluding the first item).
* @param {Array<import('css-tree').CssNode>} leaves - The original AST leaves array.
* @returns {Array<object>} The filtered leaves.
*/
getFilterLeaves(leaves) {
if (!this.#filterLeavesCache) {
this.#filterLeavesCache = new WeakMap();
}
let filterLeaves = this.#filterLeavesCache.get(leaves);
if (filterLeaves) {
return filterLeaves;
}
filterLeaves = leaves.slice(1);
this.#filterLeavesCache.set(leaves, filterLeaves);
return filterLeaves;
}
/**
* Gets the unescaped name of an AST node from the cache.
* @param {import('css-tree').CssNode} ast - The AST node.
* @returns {string} The unescaped name.
*/
getUnescapedName(ast) {
let name = this.#unescapedCache.get(ast);
if (name === undefined) {
name = unescapeSelector(ast.name);
this.#unescapedCache.set(ast, name);
}
return name;
}
/**
* Evaluates shadow host pseudo-classes.
* @param {import('css-tree').CssNode} ast - The AST.
* @param {DocumentFragment} node - The DocumentFragment node.
* @returns {boolean} True if matches, otherwise false.
*/
evaluateShadowHost(ast, node) {
return this.#shadowEvaluator.evaluateShadowHost(ast, node);
}
/**
* Matches pseudo-class selector.
* @see https://html.spec.whatwg.org/_pseudo-classes
* @param {import('css-tree').CssNode} ast - The AST.
* @param {Element} node - The Element node.
* @param {import('../index.js').FindOptions} opt - Options.
* @returns {boolean} True if matches, otherwise false.
*/
matchPseudoClassSelector(ast, node, opt) {
return this.#pseudoClassEvaluator.matchPseudoClassSelector(ast, node, opt);
}
/**
* Creates a TreeWalker.
* @param {Document|DocumentFragment|Element} node - The Document, DocumentFragment, or Element node.
* @param {object} opt - Options.
* @returns {TreeWalker} The TreeWalker object.
*/
createTreeWalker(node, opt) {
return this.#domTraverser.createTreeWalker(node, opt);
}
/**
* Yields combinator matches (Lazy evaluation, O(1) memory).
* @param {import('./processor.js').ProcessedBranch} twig - The twig object.
* @param {Element} node - The Element node.
* @param {import('../index.js').FindOptions} opt - Options.
* @yields {Element} The matched node.
*/
*yieldCombinatorMatches(twig, node, opt) {
yield* this.#domTraverser.yieldCombinatorMatches(twig, node, opt);
}
/**
* Finds descendant nodes and yields matches.
* @param {Array<import('css-tree').CssNode>} leaves - The AST leaves.
* @param {DocumentFragment|Element} baseNode - The base Element node or Element.shadowRoot.
* @param {import('../index.js').FindOptions} opt - Options.
* @yields {Element} The matched node.
*/
*yieldFindDescendantNodes(leaves, baseNode, opt) {
yield* this.#domTraverser.yieldFindDescendantNodes(leaves, baseNode, opt);
}
/**
* Matches a selector for element nodes.
* @private
* @param {import('css-tree').CssNode} ast - The AST.
* @param {Element} node - The Element node.
* @param {import('../index.js').FindOptions} opt - Options.
* @returns {boolean} True if matches, otherwise false.
*/
#matchSelectorForElement(ast, node, opt) {
const { type: astType } = ast;
switch (astType) {
case ATTR_SELECTOR: {
return matchAttributeSelector(ast, node, opt);
}
case ID_SELECTOR: {
return node.id === this.getUnescapedName(ast);
}
case CLASS_SELECTOR: {
const astName = this.getUnescapedName(ast);
return node.classList.contains(astName);
}
case NEST_SELECTOR: {
if (!this.#nestingAST) {
this.#nestingAST = parseSelector(':scope', 'selector');
}
return this.matchPseudoClassSelector(
this.#nestingAST.children.head.data,
node,
opt
);
}
case PS_CLASS_SELECTOR: {
return this.matchPseudoClassSelector(ast, node, opt);
}
case TYPE_SELECTOR: {
return matchTypeSelector(ast, node, opt);
}
// PS_ELEMENT_SELECTOR is handled by default.
default: {
try {
if (this.check) {
const css = generateCSS(ast);
this.pseudoElements.push(css);
return true;
} else {
const astName = this.getUnescapedName(ast);
matchPseudoElementSelector(astName, astType, opt);
}
} catch (e) {
this.onError(e);
}
}
}
return false;
}
}

146
node_modules/@asamuzakjp/dom-selector/src/js/event.js generated vendored Normal file
View File

@ -0,0 +1,146 @@
/**
* event.js
*/
/* constants */
const KEYS_MODIFIER = new Set([
'Alt',
'AltGraph',
'CapsLock',
'Control',
'Fn',
'FnLock',
'Hyper',
'Meta',
'NumLock',
'ScrollLock',
'Shift',
'Super',
'Symbol',
'SymbolLock'
]);
/**
* EventHandler
* Tracks window events to record recent user interactions.
*/
export class EventHandler {
/* private fields */
#window;
#event;
#eventHandlers;
#focusEvent;
#lastFocusVisible;
/**
* @param {Window} window - The window object.
*/
constructor(window) {
this.#window = window;
this.#event = null;
this.#focusEvent = null;
this.#lastFocusVisible = null;
this.#eventHandlers = [
{
keys: ['focus', 'focusin'],
handler: this.handleFocusEvent.bind(this)
},
{
keys: ['keydown', 'keyup'],
handler: this.handleKeyboardEvent.bind(this)
},
{
keys: ['mouseover', 'mousedown', 'mouseup', 'click', 'mouseout'],
handler: this.handleMouseEvent.bind(this)
}
];
this.registerEventListeners();
}
/**
* Gets the most recent non-modifier keyboard or mouse event.
* @returns {Event|null} The current event object.
*/
get currentEvent() {
return this.#event;
}
/**
* Gets the most recent focus event.
* @returns {Event|null} The current focus event object.
*/
get currentFocus() {
return this.#focusEvent;
}
/**
* Gets the node that last had visible focus.
* @returns {Element|null} The last focused node.
*/
get lastFocusVisible() {
return this.#lastFocusVisible;
}
/**
* Sets the node that last had visible focus.
* @param {Element} node - The node to set as the last visible focus.
*/
set lastFocusVisible(node) {
this.#lastFocusVisible = node;
}
/**
* Handles focus events and updates the current focus state.
* @param {Event} evt - The focus event.
*/
handleFocusEvent(evt) {
this.#focusEvent = evt;
}
/**
* Handles keyboard events and updates the current event state.
* @param {KeyboardEvent} evt - The keyboard event.
*/
handleKeyboardEvent(evt) {
const { key } = evt;
if (!KEYS_MODIFIER.has(key)) {
this.#event = evt;
}
}
/**
* Handles mouse events and updates the current event state.
* @param {MouseEvent} evt - The mouse event.
*/
handleMouseEvent(evt) {
this.#event = evt;
}
/**
* Registers all predefined event listeners on the window object.
*/
registerEventListeners() {
for (const { keys, handler } of this.#eventHandlers) {
for (const key of keys) {
this.#window.addEventListener(key, handler, {
capture: true,
passive: true
});
}
}
}
/**
* Removes all registered event listeners and resets all internal states.
*/
destroy() {
for (const { keys, handler } of this.#eventHandlers) {
for (const key of keys) {
this.#window.removeEventListener(key, handler, { capture: true });
}
}
this.#event = null;
this.#focusEvent = null;
this.#lastFocusVisible = null;
}
}

1061
node_modules/@asamuzakjp/dom-selector/src/js/finder.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

122
node_modules/@asamuzakjp/dom-selector/src/js/mapper.js generated vendored Normal file
View File

@ -0,0 +1,122 @@
/**
* mapper.js
*/
import { SelectorProcessor } from './processor.js';
import { parseSelector, walkAST } from './parser.js';
import { createHasValidator } from './selector.js';
/**
* @typedef {object} MapperResult
* @property {Array<import('./processor.js').ProcessedASTNode>} ast - Fresh AST nodes.
* @property {boolean} invalidate - Invalidation flag for dynamic evaluation.
* @property {Array<Array<Element>>} nodes - Array of matched element arrays per branch.
* @property {import('css-tree').CssNode} selectorAST - The selector AST.
*/
/**
* Mapper
* Maps CSS selectors to parsed ASTs and sets up node arrays.
*/
export class Mapper {
#context;
#processor;
/**
* @param {import('./finder.js').Finder} context - The Finder instance.
*/
constructor(context) {
this.#context = context;
this.#processor = new SelectorProcessor(context);
}
/**
* Gets the corresponding AST, nodes array, invalidate flag, and selector AST.
* @param {string} selector - The CSS selector string.
* @returns {MapperResult} The MapperResult object.
*/
correspond(selector) {
const ctx = this.#context;
let ast = null;
let invalidate = false;
let selectorAST = null;
// Check cache.
if (ctx.documentCache.has(ctx.document)) {
const cachedItem = ctx.documentCache.get(ctx.document);
if (cachedItem && cachedItem.has(selector)) {
const item = cachedItem.get(selector);
ast = item.ast;
invalidate = item.invalidate;
selectorAST = item.selectorAST;
}
}
if (ast) {
return this.#prepareResult(ast, invalidate, selectorAST);
}
// Parse selector and build metadata.
selectorAST = parseSelector(selector);
const { branches, info } = walkAST(
selectorAST,
true,
createHasValidator(ctx.window)
);
const {
hasHasPseudoFunc,
hasNestingSelector,
hasNthChildOfSelector,
hasSiblingCombinator,
hasStatePseudoClass,
hasUnsupportedPseudoClass
} = info;
// Determine invalidation flags.
invalidate =
hasHasPseudoFunc ||
hasNestingSelector ||
hasNthChildOfSelector ||
hasSiblingCombinator ||
hasStatePseudoClass ||
hasUnsupportedPseudoClass;
// Process branches.
const processed = this.#processor.process(branches, selector);
ast = processed.ast;
const descendant = processed.descendant;
// Store in cache.
let cachedItem;
if (ctx.documentCache.has(ctx.document)) {
cachedItem = ctx.documentCache.get(ctx.document);
} else {
cachedItem = new Map();
ctx.documentCache.set(ctx.document, cachedItem);
}
cachedItem.set(selector, {
ast,
descendant,
invalidate,
selectorAST
});
return this.#prepareResult(ast, invalidate, selectorAST);
}
/**
* Prepares fresh AST nodes and initialized matching nodes array.
* @private
* @param {Array<import('./processor.js').ProcessedASTNode>} ast - The cached or parsed AST.
* @param {boolean} invalidate - Invalidation flag for dynamic evaluation.
* @param {import('css-tree').CssNode} selectorAST - The parsed CSS selector AST.
* @returns {MapperResult} The MapperResult object.
*/
#prepareResult(ast, invalidate, selectorAST) {
const l = ast.length;
const freshAst = new Array(l);
const nodes = new Array(l);
for (let i = 0; i < l; i++) {
freshAst[i] = {
branch: ast[i].branch,
dir: null,
filtered: false,
find: false
};
nodes[i] = [];
}
return { ast: freshAst, invalidate, nodes, selectorAST };
}
}

807
node_modules/@asamuzakjp/dom-selector/src/js/matcher.js generated vendored Normal file
View File

@ -0,0 +1,807 @@
/**
* matcher.js
*/
/* import */
import { generateCSS, parseAstName, unescapeSelector } from './parser.js';
import {
generateException,
getDirectionality,
getLanguageAttribute,
getType,
isContentEditable,
isHTMLElement,
isNamespaceDeclared
} from './utility.js';
/* constants */
import {
ATTR_VALUE_I,
INPUT_EDIT,
LANG_ALPHA_NUM,
LANG_PART,
LANG_PART_SKIP,
NOT_SUPPORTED_ERR,
PS_ELEMENT_SELECTOR,
STRING,
SYNTAX_ERR
} from './constant.js';
const KEYS_ATTR_VALUE_I = new Set(ATTR_VALUE_I);
const KEYS_INPUT_EDIT = new Set(INPUT_EDIT);
/* regexp */
const REG_LANG_VALID = new RegExp(
`^(?:\\*-)?${LANG_ALPHA_NUM}${LANG_PART}$`,
'i'
);
const REG_ATTR_EQUALITY = /^[a-z][a-z\d_-]*$/;
/* cache */
const astMetaCache = new WeakMap();
const htmlAttrMetaCache = new WeakMap();
/**
* Validates a pseudo-element selector.
* @param {string} astName - The name of the pseudo-element from the AST.
* @param {string} astType - The type of the selector from the AST.
* @param {import('../index.js').FindOptions} [opt] - Options.
* @throws {DOMException} If the selector is invalid or unsupported.
* @returns {void}
*/
export const matchPseudoElementSelector = (
astName,
astType,
{ forgive, globalObject, warn } = {}
) => {
if (astType !== PS_ELEMENT_SELECTOR) {
// Ensure the AST node is a pseudo-element selector.
throw new TypeError(`Unexpected ast type ${getType(astType)}`);
}
switch (astName) {
case 'after':
case 'backdrop':
case 'before':
case 'cue':
case 'cue-region':
case 'first-letter':
case 'first-line':
case 'file-selector-button':
case 'marker':
case 'placeholder':
case 'selection':
case 'target-text': {
// Warn if the pseudo-element is known but unsupported.
if (warn) {
throw generateException(
`Unsupported pseudo-element ::${astName}`,
NOT_SUPPORTED_ERR,
globalObject
);
}
break;
}
case 'part':
case 'slotted': {
// Warn if the functional pseudo-element is known but unsupported.
if (warn) {
throw generateException(
`Unsupported pseudo-element ::${astName}()`,
NOT_SUPPORTED_ERR,
globalObject
);
}
break;
}
default: {
// Handle vendor-prefixed unknown pseudo-elements.
if (astName.startsWith('-webkit-')) {
if (warn) {
throw generateException(
`Unsupported pseudo-element ::${astName}`,
NOT_SUPPORTED_ERR,
globalObject
);
}
} else if (!forgive) {
// Throw an error for unknown pseudo-elements if not forgiven.
throw generateException(
`Unknown pseudo-element ::${astName}`,
SYNTAX_ERR,
globalObject
);
}
}
}
};
/**
* Matches the :dir() pseudo-class against an element's directionality.
* @param {import('css-tree').CssNode} ast - The AST object for the pseudo-class.
* @param {Element} node - The element node to match against.
* @param {WeakMap} [dirCache] - Cache for directionality.
* @throws {TypeError} If the AST does not contain a valid direction value.
* @returns {boolean} - True if matches, otherwise false.
*/
export const matchDirectionPseudoClass = (
ast,
node,
dirCache = new WeakMap()
) => {
const { name } = ast;
if (!name) {
const type = name === '' ? '(empty String)' : getType(name);
throw new TypeError(`Unexpected ast type ${type}`);
}
const dir = getDirectionality(node, dirCache);
return name === dir;
};
/**
* Matches the :lang() pseudo-class against an element's language attribute.
* @param {import('css-tree').CssNode} ast - The AST object for the pseudo-class child.
* @param {Element} node - The element node to match against.
* @param {WeakMap} [langCache] - Cache for language attributes.
* @throws {TypeError} If the AST does not contain a valid language value.
* @returns {boolean} - True if matches, otherwise false.
*/
export const matchLanguagePseudoClass = (
ast,
node,
langCache = new WeakMap()
) => {
const elementLang = getLanguageAttribute(node, langCache);
if (elementLang === null) {
return false;
}
let meta = astMetaCache.get(ast);
if (meta === undefined) {
meta = {};
astMetaCache.set(ast, meta);
}
if (meta.langRegex !== undefined) {
if (meta.langPattern === '*') {
return elementLang !== '';
}
if (meta.langRegex === null) {
return false;
}
return meta.langRegex.test(elementLang);
}
const { name, type, value } = ast;
const langPattern =
type === STRING && value !== undefined ? value : unescapeSelector(name);
meta.langPattern = langPattern;
if (typeof langPattern !== 'string') {
meta.langRegex = null;
return false;
}
if (langPattern === '*') {
meta.langRegex = null;
return elementLang !== '';
}
if (!REG_LANG_VALID.test(langPattern)) {
meta.langRegex = null;
return false;
}
const parts = langPattern.split('-');
const regexStr = parts
.map((part, index) => {
const core = part === '*' ? LANG_ALPHA_NUM : part;
const skip = index === parts.length - 1 ? LANG_PART : LANG_PART_SKIP;
return (index === 0 ? core : `-${core}`) + skip;
})
.join('');
const matcherRegex = new RegExp(`^${regexStr}$`, 'i');
meta.langRegex = matcherRegex;
return matcherRegex.test(elementLang);
};
/**
* Matches the :checked pseudo-class.
* @param {Element} node - The Element node.
* @returns {boolean} True if matches, otherwise false.
*/
export const matchCheckedPseudoClass = node => {
const { localName } = node;
if (localName === 'option') {
return node.selected;
}
if (localName === 'input') {
const attrType = node.getAttribute('type');
if (node.checked) {
return attrType === 'checkbox' || attrType === 'radio';
}
}
return false;
};
/**
* Matches the :any-link and :link pseudo-classes.
* @param {Element} node - The Element node.
* @returns {boolean} True if matches, otherwise false.
*/
export const matchLinkPseudoClass = node => {
const { localName } = node;
if (localName === 'a' || localName === 'area') {
return node.hasAttribute('href');
}
return false;
};
/**
* Matches the :open pseudo-class.
* @param {Element} node - The Element node.
* @returns {boolean} True if matches, otherwise false.
*/
export const matchOpenPseudoClass = node => {
const { localName } = node;
if (localName === 'details' || localName === 'dialog') {
return node.hasAttribute('open');
}
return false;
};
/**
* Matches the :placeholder-shown pseudo-class.
* @param {Element} node - The Element node.
* @param {Set<string>} keys - A set of input type keys.
* @returns {boolean} True if matches, otherwise false.
*/
export const matchPlaceholderShownPseudoClass = (node, keys) => {
let placeholder;
if (node.placeholder) {
placeholder = node.placeholder;
} else if (node.hasAttribute('placeholder')) {
placeholder = node.getAttribute('placeholder');
}
if (typeof placeholder === 'string' && !/[\r\n]/.test(placeholder)) {
let targetNode;
const { localName } = node;
if (localName === 'textarea') {
targetNode = node;
} else if (localName === 'input') {
if (node.hasAttribute('type')) {
if (keys.has(node.getAttribute('type'))) {
targetNode = node;
}
} else {
targetNode = node;
}
}
if (targetNode) {
return node.value === '';
}
}
return false;
};
/**
* Matches the :in-range and :out-of-range pseudo-classes.
* @param {string} astName - The name of the pseudo-class.
* @param {Element} node - The Element node.
* @param {Set<string>} keys - A set of input type keys.
* @returns {boolean} True if matches, otherwise false.
*/
export const matchRangePseudoClass = (astName, node, keys) => {
const { localName } = node;
const attrType = node.getAttribute('type');
if (
localName === 'input' &&
!(node.readOnly || node.hasAttribute('readonly')) &&
!(node.disabled || node.hasAttribute('disabled')) &&
keys.has(attrType)
) {
const flowed = node.validity.rangeUnderflow || node.validity.rangeOverflow;
if (astName === 'out-of-range') {
return flowed;
}
if (flowed) {
return false;
}
return (
node.hasAttribute('min') ||
node.hasAttribute('max') ||
attrType === 'range'
);
}
return false;
};
/**
* Match the :read-only and :read-write pseudo-classes
* @param {string} astName - pseudo-class name
* @param {Element} node - Element node
* @returns {boolean} - True if matches, otherwise false.
*/
export const matchReadOnlyPseudoClass = (astName, node) => {
const { localName } = node;
let isReadOnly = false;
switch (localName) {
case 'textarea':
case 'input': {
const isEditableInput = !node.type || KEYS_INPUT_EDIT.has(node.type);
if (localName === 'textarea' || isEditableInput) {
isReadOnly =
node.readOnly ||
node.hasAttribute('readonly') ||
node.disabled ||
node.hasAttribute('disabled');
} else {
// Non-editable input types are always read-only
isReadOnly = true;
}
break;
}
default: {
isReadOnly = !isContentEditable(node);
}
}
if (astName === 'read-only') {
return isReadOnly;
}
return !isReadOnly;
};
/**
* Matches the :required and :optional pseudo-classes.
* @param {string} astName - The name of the pseudo-class.
* @param {Element} node - The Element node.
* @param {Set<string>} keys - A set of input type keys.
* @returns {boolean} True if matches, otherwise false.
*/
export const matchRequiredPseudoClass = (astName, node, keys) => {
const { localName } = node;
let required = false;
if (localName === 'select' || localName === 'textarea') {
if (node.required || node.hasAttribute('required')) {
required = true;
}
} else if (localName === 'input') {
if (node.hasAttribute('type')) {
const attrType = node.getAttribute('type');
if (keys.has(attrType)) {
if (node.required || node.hasAttribute('required')) {
required = true;
}
}
} else if (node.required || node.hasAttribute('required')) {
required = true;
}
} else {
return false;
}
if (astName === 'optional') {
return !required;
}
return required;
};
/**
* Matches an attribute selector against an element.
* @param {import('css-tree').CssNode} ast - The AST for the attribute selector.
* @param {Element} node - The element node to match against.
* @param {import('../index.js').FindOptions} [opt] - Options.
* @returns {boolean} - True if the attribute selector matches, otherwise false.
*/
export const matchAttributeSelector = (
ast,
node,
{ check, forgive, globalObject } = {}
) => {
const {
flags: astFlags,
matcher: astMatcher,
name: astName,
value: astValue
} = ast;
if (typeof astFlags === 'string' && !/^[is]$/i.test(astFlags) && !forgive) {
const css = generateCSS(ast);
throw generateException(
`Invalid selector ${css}`,
SYNTAX_ERR,
globalObject
);
}
const astRawName = astName?.name;
const isHTML = isHTMLElement(node);
const metaCache = isHTML ? htmlAttrMetaCache : astMetaCache;
let meta = metaCache.get(ast);
if (meta === undefined) {
meta = {
attrValues: new Set(),
equalityName: null
};
if (
astMatcher === '=' &&
!astFlags &&
astValue?.type === STRING &&
typeof astRawName === 'string' &&
astRawName !== 'lang' &&
!KEYS_ATTR_VALUE_I.has(astRawName) &&
REG_ATTR_EQUALITY.test(astRawName)
) {
meta.equalityName = astRawName;
}
metaCache.set(ast, meta);
}
// Parsing and flag validation still run before this matching shortcut.
if (isHTML && meta.equalityName !== null) {
const attrName = meta.equalityName;
if (node.getAttribute(attrName) === astValue.value) {
return true;
}
// Prefixed or duplicate names can hide another matching attribute.
let occurrences = 0;
let needsFallback = false;
for (const attributeName of node.getAttributeNames()) {
if (attributeName === attrName) {
occurrences++;
}
if (attributeName.includes(':') || occurrences > 1) {
needsFallback = true;
break;
}
}
if (!needsFallback) {
return false;
}
}
if (astMatcher === null && !astFlags && typeof astRawName === 'string') {
if (meta.astName === undefined) {
const rawName = unescapeSelector(astRawName);
meta.astName = rawName;
meta.hasPipe = rawName.indexOf('|') > -1;
}
if (!meta.hasPipe) {
if (
meta.astName === 'lang' &&
node.hasAttributeNS('http://www.w3.org/XML/1998/namespace', 'lang')
) {
return false;
}
if (node.hasAttribute(meta.astName)) {
return true;
}
const attrs = node.attributes;
if (!attrs || attrs.length === 0) {
return false;
}
const checkName = isHTML ? meta.astName.toLowerCase() : meta.astName;
for (const itemAttr of attrs) {
let itemName = itemAttr.name;
if (isHTML) {
itemName = itemName.toLowerCase();
}
const colonIdx = itemName.indexOf(':');
if (colonIdx > -1) {
const itemLocalName = itemName
.substring(colonIdx + 1)
.replace(/^:/, '');
if (checkName === itemLocalName) {
return true;
}
} else if (checkName === itemName) {
return true;
}
}
return false;
}
}
const { attributes } = node;
if (!attributes || !attributes.length) {
return false;
}
if (meta.caseInsensitive === undefined) {
let caseInsensitive = false;
if (typeof astFlags === 'string') {
caseInsensitive = /^i$/i.test(astFlags);
} else if (isHTML) {
caseInsensitive = KEYS_ATTR_VALUE_I.has(astRawName);
}
meta.caseInsensitive = caseInsensitive;
let astAttrName = unescapeSelector(astRawName);
if (isHTML) {
if (typeof astFlags === 'string') {
if (/^i$/i.test(astFlags)) {
astAttrName = astAttrName.toLowerCase();
}
} else {
astAttrName = astAttrName.toLowerCase();
}
} else if (caseInsensitive) {
astAttrName = astAttrName.toLowerCase();
}
meta.astAttrName = astAttrName;
meta.hasPipeInName = astAttrName.indexOf('|') > -1;
if (meta.hasPipeInName) {
const { prefix, localName } = parseAstName(astAttrName);
meta.astPrefix = prefix;
meta.astLocalName = localName;
}
const { name: astIdentValue, value: astStringValue } = astValue ?? {};
let attrValue;
if (astIdentValue) {
attrValue = unescapeSelector(astIdentValue);
} else if (astStringValue !== undefined) {
attrValue = astStringValue;
}
if (caseInsensitive && typeof attrValue === 'string') {
attrValue = attrValue.toLowerCase();
}
meta.cachedAttrValue = attrValue;
if (astMatcher === '~=' && attrValue && typeof attrValue === 'string') {
meta.tildeTarget = /\s/.test(attrValue) ? null : ` ${attrValue} `;
}
}
const caseInsensitive = meta.caseInsensitive;
const astAttrName = meta.astAttrName;
const attrValue = meta.cachedAttrValue;
const attrValues = meta.attrValues;
if (attrValues.size) {
attrValues.clear();
}
if (meta.hasPipeInName) {
const astPrefix = meta.astPrefix;
const astLocalName = meta.astLocalName;
for (const item of attributes) {
let itemName = item.name;
let itemValue = item.value;
if (caseInsensitive) {
itemName = itemName.toLowerCase();
itemValue = itemValue.toLowerCase();
}
const colonIdx = itemName.indexOf(':');
switch (astPrefix) {
case '': {
if (astLocalName === itemName) {
attrValues.add(itemValue);
}
break;
}
case '*': {
if (colonIdx > -1) {
const itemLocalName = itemName
.substring(colonIdx + 1)
.replace(/^:/, '');
if (itemLocalName === astLocalName) {
attrValues.add(itemValue);
}
} else if (astLocalName === itemName) {
attrValues.add(itemValue);
}
break;
}
default: {
if (!check) {
if (forgive) {
return false;
}
const css = generateCSS(ast);
throw generateException(
`Invalid selector ${css}`,
SYNTAX_ERR,
globalObject
);
}
if (colonIdx > -1) {
const itemPrefix = itemName.substring(0, colonIdx);
const itemLocalName = itemName
.substring(colonIdx + 1)
.replace(/^:/, '');
if (itemPrefix === 'xml' && itemLocalName === 'lang') {
continue;
}
if (astPrefix === itemPrefix && astLocalName === itemLocalName) {
if (isNamespaceDeclared(astPrefix, node)) {
attrValues.add(itemValue);
}
}
}
}
}
}
} else {
for (const item of attributes) {
const origName = item.name;
if (
item.namespaceURI === 'http://www.w3.org/XML/1998/namespace' &&
item.localName === 'lang'
) {
continue;
}
const colonIdx = origName.indexOf(':');
if (colonIdx > -1) {
const itemPrefix = origName.substring(0, colonIdx);
const itemLocalName = origName
.substring(colonIdx + 1)
.replace(/^:/, '');
if (itemPrefix === 'xml' && itemLocalName === 'lang') {
continue;
}
}
let isMatch = false;
if (origName === astAttrName) {
isMatch = true;
} else if (caseInsensitive && origName.toLowerCase() === astAttrName) {
isMatch = true;
}
if (isMatch) {
attrValues.add(caseInsensitive ? item.value.toLowerCase() : item.value);
} else if (colonIdx > -1) {
const itemLocalName = origName
.substring(colonIdx + 1)
.replace(/^:/, '');
let isLocalMatch = false;
if (itemLocalName === astAttrName) {
isLocalMatch = true;
} else if (
caseInsensitive &&
itemLocalName.toLowerCase() === astAttrName
) {
isLocalMatch = true;
}
if (isLocalMatch) {
attrValues.add(
caseInsensitive ? item.value.toLowerCase() : item.value
);
}
}
}
}
if (!attrValues.size) {
return false;
}
switch (astMatcher) {
case '=': {
return typeof attrValue === 'string' && attrValues.has(attrValue);
}
case '~=': {
if (meta.tildeTarget === null || !attrValue) {
return false;
}
const target = meta.tildeTarget;
for (const value of attrValues) {
if (` ${value.replace(/[\t\r\n\f]/g, ' ')} `.includes(target)) {
return true;
}
}
return false;
}
case '|=': {
if (!attrValue || typeof attrValue !== 'string') {
return false;
}
const prefix = `${attrValue}-`;
for (const value of attrValues) {
if (value === attrValue || value.startsWith(prefix)) {
return true;
}
}
return false;
}
case '^=': {
if (!attrValue || typeof attrValue !== 'string') {
return false;
}
for (const value of attrValues) {
if (value.startsWith(attrValue)) {
return true;
}
}
return false;
}
case '$=': {
if (!attrValue || typeof attrValue !== 'string') {
return false;
}
for (const value of attrValues) {
if (value.endsWith(attrValue)) {
return true;
}
}
return false;
}
case '*=': {
if (!attrValue || typeof attrValue !== 'string') {
return false;
}
for (const value of attrValues) {
if (value.includes(attrValue)) {
return true;
}
}
return false;
}
case null:
default: {
return true;
}
}
};
/**
* Matches a type selector against an element.
* @param {import('css-tree').CssNode} ast - The AST for the type selector.
* @param {Element} node - The element node to match against.
* @param {import('../index.js').FindOptions} [opt] - Options.
* @returns {boolean} - True if the type selector matches, otherwise false.
*/
export const matchTypeSelector = (
ast,
node,
{ check, forgive, globalObject } = {}
) => {
const { localName, namespaceURI, prefix } = node;
let meta = astMetaCache.get(ast);
if (meta === undefined) {
meta = {};
astMetaCache.set(ast, meta);
}
if (meta.astName === undefined) {
const astName = unescapeSelector(ast.name);
const { prefix: parsedPrefix, localName: parsedLocalName } = parseAstName(
astName,
node
);
meta.astName = astName;
meta.astPrefix = parsedPrefix;
meta.astPrefixLowerCased = parsedPrefix.toLowerCase();
meta.astLocalName = parsedLocalName;
meta.astLocalNameLowerCased = parsedLocalName.toLowerCase();
meta.hasPipe = astName.includes('|');
}
const isHTML = isHTMLElement(node);
if (isHTML && localName === meta.astLocalName && !meta.hasPipe) {
return true;
}
let nodePrefix;
let nodeLocalName;
const colonIdx = localName.indexOf(':');
if (colonIdx > -1) {
nodePrefix = localName.substring(0, colonIdx);
nodeLocalName = localName.substring(colonIdx + 1);
} else {
nodePrefix = prefix || '';
nodeLocalName = localName;
}
const astPrefix = isHTML ? meta.astPrefixLowerCased : meta.astPrefix;
const astLocalName = isHTML ? meta.astLocalNameLowerCased : meta.astLocalName;
const isUniversal = astLocalName === '*';
switch (astPrefix) {
case '': {
return (
!nodePrefix &&
!namespaceURI &&
(isUniversal || astLocalName === nodeLocalName)
);
}
case '*': {
return isUniversal || astLocalName === nodeLocalName;
}
default: {
if (!check) {
if (forgive) {
return false;
}
const css = generateCSS(ast);
throw generateException(
`Invalid selector ${css}`,
SYNTAX_ERR,
globalObject
);
}
const astNS = node.lookupNamespaceURI(astPrefix);
const nodeNS = node.lookupNamespaceURI(nodePrefix);
if (astNS === nodeNS && astPrefix === nodePrefix) {
return isUniversal || astLocalName === nodeLocalName;
} else if (!forgive && !astNS) {
throw generateException(
`Undeclared namespace ${astPrefix}`,
SYNTAX_ERR,
globalObject
);
}
return false;
}
}
};

1354
node_modules/@asamuzakjp/dom-selector/src/js/nwsapi.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

511
node_modules/@asamuzakjp/dom-selector/src/js/parser.js generated vendored Normal file
View File

@ -0,0 +1,511 @@
/**
* parser.js
*/
/* import */
import cssTreeParse from 'css-tree/selector-parser';
import cssTreeWalk from 'css-tree/walker';
import cssTreeConvertor from 'css-tree/convertor';
import { clone as cssTreeClone } from 'css-tree/utils';
import cssTreeGenerate from 'css-tree/generator';
import { stringifyValue } from './utility.js';
/* constants */
import {
ATTR_SELECTOR,
BIT_01,
BIT_02,
BIT_04,
BIT_08,
BIT_16,
BIT_32,
BIT_FFFF,
CLASS_SELECTOR,
COMBINATOR,
DUO,
HEX,
ID_SELECTOR,
KEYS_LOGICAL,
KEYS_PS_CLASS_SUPPORTED,
NEST_SELECTOR,
NTH,
PS_CLASS_SELECTOR,
PS_ELEMENT_SELECTOR,
SELECTOR,
SYNTAX_ERR,
TYPE_SELECTOR
} from './constant.js';
const AST_SORT_ORDER = new Map([
[PS_ELEMENT_SELECTOR, BIT_01],
[ID_SELECTOR, BIT_02],
[CLASS_SELECTOR, BIT_04],
[TYPE_SELECTOR, BIT_08],
[ATTR_SELECTOR, BIT_16],
[PS_CLASS_SELECTOR, BIT_32]
]);
const KEYS_PS_NTH = new Set([
'first-child',
'first-of-type',
'last-child',
'last-of-type',
'only-child',
'only-of-type'
]);
const KEYS_PS_CLASS_STATE = new Set([
'checked',
'closed',
'disabled',
'empty',
'enabled',
'in-range',
'indeterminate',
'invalid',
'open',
'out-of-range',
'placeholder-shown',
'read-only',
'read-write',
'valid',
...KEYS_PS_NTH
]);
const KEYS_SHADOW_HOST = new Set(['host', 'host-context']);
const U_FFFD = '\uFFFD';
/* regexp */
const REG_EMPTY_PS_FUNC =
/(?<=:(?:dir|has|host(?:-context)?|is|lang|not|nth-(?:last-)?(?:child|of-type)|where))\(\s+\)/g;
const REG_SHADOW_PS_ELEMENT = /^part|slotted$/;
/**
* Unescapes a CSS selector string.
* @param {string} [selector] - The CSS selector to unescape.
* @returns {string} The unescaped selector string.
*/
export const unescapeSelector = (selector = '') => {
if (typeof selector === 'string' && selector.indexOf('\\', 0) >= 0) {
const arr = selector.split('\\');
const selectorItems = [arr[0]];
const l = arr.length;
for (let i = 1; i < l; i++) {
const item = arr[i];
if (item === '' && i === l - 1) {
selectorItems.push(U_FFFD);
} else if (item === '') {
// Empty segment at non-last position means \\ (escaped backslash)
selectorItems.push('\\');
// skip the next segment which is the remainder after \\
i++;
if (i < l) {
selectorItems.push(arr[i]);
}
} else {
const hexExists = /^([\da-f]{1,6}\s?)/i.exec(item);
if (hexExists) {
const [, hex] = hexExists;
let str;
try {
const low = parseInt('D800', HEX);
const high = parseInt('DFFF', HEX);
const deci = parseInt(hex, HEX);
if (deci === 0 || (deci >= low && deci <= high)) {
str = U_FFFD;
} else {
str = String.fromCodePoint(deci);
}
} catch (e) {
str = U_FFFD;
}
let postStr = '';
if (item.length > hex.length) {
postStr = item.substring(hex.length);
}
selectorItems.push(`${str}${postStr}`);
} else if (/^[\n\r\f]/.test(item)) {
// whitespace
selectorItems.push(`\\${item}`);
} else {
selectorItems.push(item);
}
}
}
return selectorItems.join('');
}
return selector;
};
/**
* Preprocesses a selector string according to the specification.
* @see https://drafts.csswg.org/css-syntax-3/#input-preprocessing
* @param {string} value - The value to preprocess.
* @returns {string} The preprocessed selector string.
*/
export const preprocess = value => {
let selector = stringifyValue(value);
let index = 0;
while (index >= 0) {
// @see https://drafts.csswg.org/selectors/#id-selectors
index = selector.indexOf('#', index);
if (index < 0) {
break;
}
const preHash = selector.substring(0, index + 1);
let postHash = selector.substring(index + 1);
const codePoint = postHash.codePointAt(0);
if (codePoint > BIT_FFFF) {
const str = `\\${codePoint.toString(HEX)} `;
if (postHash.length === DUO) {
postHash = str;
} else {
postHash = `${str}${postHash.substring(DUO)}`;
}
}
selector = `${preHash}${postHash}`;
index++;
}
selector = selector
.replace(/\f|\r\n?/g, '\n')
.replace(/[\0\uD800-\uDFFF]|\\$/g, U_FFFD);
if (selector === '&') {
return '';
}
return selector;
};
/**
* Creates an Abstract Syntax Tree (AST) from a CSS selector string.
* @param {string} sel - The CSS selector string.
* @param {string} [context] - Parse what part of CSS.
* @returns {import('css-tree').CssNode} The parsed AST object.
*/
export const parseSelector = (sel, context = 'selectorList') => {
const selector = preprocess(sel);
// invalid selectors
if (/^$|^\s*>|,\s*$/.test(selector)) {
throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR);
}
try {
return cssTreeParse(selector, { context });
} catch (e) {
const { message } = e;
if (
/^(?:"\]"|Attribute selector [()\s,=~^$*|]+) is expected$/.test(
message
) &&
!selector.endsWith(']')
) {
const index = selector.lastIndexOf('[');
const selPart = selector.substring(index);
if (selPart.includes('"')) {
const quotes = selPart.match(/"/g).length;
if (quotes % 2) {
return parseSelector(`${selector}"]`);
}
return parseSelector(`${selector}]`);
}
return parseSelector(`${selector}]`);
} else if (message === '")" is expected') {
// workaround for https://github.com/csstree/csstree/issues/283
if (REG_EMPTY_PS_FUNC.test(selector)) {
return parseSelector(`${selector.replaceAll(REG_EMPTY_PS_FUNC, '()')}`);
} else if (!selector.endsWith(')')) {
return parseSelector(`${selector})`);
} else {
throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR);
}
} else {
throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR);
}
}
};
/**
* Walks the provided AST to collect selector branches and gather information
* about its contents.
* @param {import('css-tree').CssNode} [ast] - The AST to traverse.
* @param {boolean} [toObject] - True if converts ast to object.
* @param {(node: import('css-tree').CssNode) => void} [callback] - Optional callback for each node.
* @returns {{branches: Array<Array<import('css-tree').CssNode>>, info: object}} An object containing the selector branches and info.
*/
export const walkAST = (ast = {}, toObject = false, callback = null) => {
const branches = new Set();
const info = {
hasForgivenPseudoFunc: false,
hasHasPseudoFunc: false,
hasLogicalPseudoFunc: false,
hasNestedSelector: false,
hasNestingSelector: false,
hasNotPseudoFunc: false,
hasNthChildOfSelector: false,
hasSiblingCombinator: false,
hasStatePseudoClass: false,
hasUnsupportedPseudoClass: false
};
const opt = {
enter(node) {
if (typeof callback === 'function') {
callback(node);
}
switch (node.type) {
case CLASS_SELECTOR: {
if (/^-?\d/.test(node.name)) {
throw new DOMException(
`Invalid selector .${node.name}`,
SYNTAX_ERR
);
}
break;
}
case COMBINATOR: {
if (/^[+~]$/.test(node.name)) {
info.hasSiblingCombinator = true;
}
break;
}
case ID_SELECTOR: {
if (/^-?\d/.test(node.name)) {
throw new DOMException(
`Invalid selector #${node.name}`,
SYNTAX_ERR
);
}
break;
}
case PS_CLASS_SELECTOR: {
const name = node.name.toLowerCase();
if (KEYS_LOGICAL.has(name)) {
info.hasNestedSelector = true;
info.hasLogicalPseudoFunc = true;
if (name === 'has') {
info.hasHasPseudoFunc = true;
} else if (name === 'not') {
info.hasNotPseudoFunc = true;
} else {
info.hasForgivenPseudoFunc = true;
}
} else if (KEYS_PS_CLASS_STATE.has(name)) {
info.hasStatePseudoClass = true;
} else if (
KEYS_SHADOW_HOST.has(name) &&
Array.isArray(node.children) &&
node.children.length
) {
info.hasNestedSelector = true;
} else if (!KEYS_PS_CLASS_SUPPORTED.has(name)) {
info.hasUnsupportedPseudoClass = true;
}
break;
}
case PS_ELEMENT_SELECTOR: {
if (REG_SHADOW_PS_ELEMENT.test(node.name)) {
info.hasNestedSelector = true;
}
break;
}
case NEST_SELECTOR: {
info.hasNestingSelector = true;
break;
}
case NTH: {
if (node.selector) {
info.hasNestedSelector = true;
info.hasNthChildOfSelector = true;
}
break;
}
case SELECTOR: {
branches.add(node.children);
break;
}
default:
}
}
};
const clonedAst = cssTreeClone(ast);
cssTreeWalk(
toObject ? cssTreeConvertor.toPlainObject(clonedAst) : clonedAst,
opt
);
if (info.hasNestedSelector === true) {
cssTreeWalk.findAll(clonedAst, (node, item, list) => {
if (list) {
if (node.type === PS_CLASS_SELECTOR && KEYS_LOGICAL.has(node.name)) {
const itemList = list.filter(i => {
const { name, type } = i;
return type === PS_CLASS_SELECTOR && KEYS_LOGICAL.has(name);
});
for (const { children } of itemList) {
// SelectorList
for (const { children: grandChildren } of children) {
// Selector
for (const { children: greatGrandChildren } of grandChildren) {
if (branches.has(greatGrandChildren)) {
branches.delete(greatGrandChildren);
}
}
}
}
} else if (
node.type === PS_CLASS_SELECTOR &&
KEYS_SHADOW_HOST.has(node.name) &&
Array.isArray(node.children) &&
node.children.length
) {
const itemList = list.filter(i => {
const { children, name, type } = i;
return (
type === PS_CLASS_SELECTOR &&
KEYS_SHADOW_HOST.has(name) &&
Array.isArray(children) &&
children.length
);
});
for (const { children } of itemList) {
// Selector
for (const { children: grandChildren } of children) {
if (branches.has(grandChildren)) {
branches.delete(grandChildren);
}
}
}
} else if (
node.type === PS_ELEMENT_SELECTOR &&
REG_SHADOW_PS_ELEMENT.test(node.name)
) {
const itemList = list.filter(i => {
const { name, type } = i;
return (
type === PS_ELEMENT_SELECTOR && REG_SHADOW_PS_ELEMENT.test(name)
);
});
for (const { children } of itemList) {
// Selector
for (const { children: grandChildren } of children) {
if (branches.has(grandChildren)) {
branches.delete(grandChildren);
}
}
}
} else if (node.type === NTH && node.selector) {
const itemList = list.filter(i => {
const { selector, type } = i;
return type === NTH && selector;
});
for (const { selector } of itemList) {
const { children } = selector;
// Selector
for (const { children: grandChildren } of children) {
if (branches.has(grandChildren)) {
branches.delete(grandChildren);
}
}
}
}
}
});
}
return {
info,
branches: [...branches]
};
};
/**
* Comparison function for sorting AST nodes based on specificity.
* @param {import('css-tree').CssNode} a - The first AST node.
* @param {import('css-tree').CssNode} b - The second AST node.
* @returns {number} -1, 0 or 1, depending on the sort order.
*/
export const compareASTNodes = (a, b) => {
const bitA = AST_SORT_ORDER.get(a.type);
const bitB = AST_SORT_ORDER.get(b.type);
if (bitA === bitB) {
return 0;
} else if (bitA > bitB) {
return 1;
} else {
return -1;
}
};
/**
* Sorts a collection of AST nodes based on CSS specificity rules.
* @param {Array<import('css-tree').CssNode>} asts - A collection of AST nodes to sort.
* @returns {Array<import('css-tree').CssNode>} A new array containing the sorted AST nodes.
*/
export const sortAST = asts => {
const arr = [...asts];
if (arr.length > 1) {
arr.sort(compareASTNodes);
}
return arr;
};
/**
* Parses a type selector's name, which may include a namespace prefix.
* @param {string} selector - The type selector name (e.g., 'ns|E' or 'E').
* @returns {{prefix: string, localName: string}} An object with `prefix` and
* `localName` properties.
*/
export const parseAstName = selector => {
let prefix;
let localName;
if (selector && typeof selector === 'string') {
if (selector.indexOf('|') > -1) {
[prefix, localName] = selector.split('|');
} else {
prefix = '*';
localName = selector;
}
} else {
throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR);
}
return {
prefix,
localName
};
};
/**
* Extracts the rightmost subject keys (id, class, tag) from a CSS selector AST.
* @param {import('css-tree').CssNode} ast - The AST representation of the CSS selector.
* @returns {Array<{id: string|null, className: string|null, tag: string|null}>} The list of extracted keys for each selector group.
*/
export const extractSubjectsAst = ast => {
const subjects = [];
if (ast?.type === 'SelectorList') {
for (const selectorNode of ast.children) {
let idKey = null;
let classKey = null;
let tagKey = null;
let current = selectorNode.children.tail;
while (current) {
const node = current.data;
if (node.type === COMBINATOR) {
break;
}
if (node.type === ID_SELECTOR && idKey === null) {
idKey = unescapeSelector(node.name);
} else if (node.type === CLASS_SELECTOR && classKey === null) {
classKey = unescapeSelector(node.name);
} else if (node.type === TYPE_SELECTOR && tagKey === null) {
const { localName } = parseAstName(unescapeSelector(node.name));
if (localName !== '*') {
tagKey = localName.toLowerCase();
}
}
if (idKey !== null && classKey !== null && tagKey !== null) {
break;
}
current = current.prev;
}
subjects.push({ id: idKey, className: classKey, tag: tagKey });
}
}
return subjects;
};
/* Re-exported from css-tree. */
/** @type {typeof import('css-tree').find} */
export const findAST = cssTreeWalk.find;
/** @type {typeof import('css-tree').generate} */
export const generateCSS = cssTreeGenerate;

View File

@ -0,0 +1,100 @@
/**
* processor.js
*/
/* import */
import { sortAST, unescapeSelector } from './parser.js';
import { isInvalidCombinator } from './selector.js';
import { generateException } from './utility.js';
/* constants */
import { COMBINATOR, SYNTAX_ERR } from './constant.js';
/**
* @typedef {object} ProcessedBranch
* @property {import('css-tree').CssNode|null} combo - The combinator AST node.
* @property {Array<import('css-tree').CssNode>} leaves - An array of AST leaf nodes.
*/
/**
* @typedef {object} ProcessedASTNode
* @property {Array<ProcessedBranch>} branch - The processed selector branch.
* @property {string|null} dir - The traversal direction.
* @property {boolean} filtered - Indicates if the node is filtered.
* @property {boolean} find - Indicates if the match is found.
*/
/**
* SelectorProcessor
* Processes raw selector branches into an internal AST format.
*/
export class SelectorProcessor {
#context;
/**
* @param {import('./finder.js').Finder} context - The Finder instance.
*/
constructor(context) {
this.#context = context;
}
/**
* Processes selector branches into the internal AST.
* @param {Array<Array<import('css-tree').CssNode>>} branches - The raw selector branches.
* @param {string} selector - The original CSS selector string.
* @returns {{ast: Array<ProcessedASTNode>, descendant: boolean, invalidate?: boolean}} An object containing the ast, a descendant flag, and an optional invalidate flag.
*/
process(branches, selector) {
let descendant = false;
const ast = [];
for (const items of branches) {
const branch = [];
let prevType = null;
const itemsLen = items.length;
if (itemsLen) {
const leaves = new Set();
for (let j = 0; j < itemsLen; j++) {
const item = items[j];
const isLast = j === itemsLen - 1;
// Validate combinator syntax.
if (isInvalidCombinator(item.type, prevType, isLast)) {
const msg = `Invalid selector ${selector}`;
this.#context.onError(
generateException(msg, SYNTAX_ERR, this.#context.window)
);
return { ast: [], descendant: false, invalidate: false };
}
if (item.type === COMBINATOR) {
// Flag if the branch contains descendant or child combinators.
if (item.name === ' ' || item.name === '>') {
descendant = true;
}
branch.push({ combo: item, leaves: sortAST(leaves) });
leaves.clear();
} else {
// Unescape selector names and detect namespaces.
if (item.name && typeof item.name === 'string') {
const unescapedName = unescapeSelector(item.name);
if (unescapedName !== item.name) {
item.name = unescapedName;
}
if (/[|:]/.test(unescapedName)) {
item.namespace = true;
}
}
leaves.add(item);
}
prevType = item.type;
// Handle the trailing items after the loop finishes.
if (isLast) {
branch.push({ combo: null, leaves: sortAST(leaves) });
leaves.clear();
}
}
}
// Initialize the structure required for node collection.
ast.push({ branch, dir: null, filtered: false, find: false });
}
return { ast, descendant };
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,330 @@
/**
* selector.js
*/
/* import */
import cssTreeWalk from 'css-tree/walker';
import cssTreeGenerate from 'css-tree/generator';
import { generateException } from './utility.js';
/* constants */
import {
COMBINATOR,
COMBO,
COMPOUND_I,
HAS_COMPOUND,
KEYS_LOGICAL,
KEYS_PS_CLASS_SUPPORTED,
LOGIC_COMPLEX,
LOGIC_COMPOUND,
N_TH,
PSEUDO_CLASS,
PS_CLASS_SELECTOR,
PS_ELEMENT_SELECTOR,
SELECTOR,
SYNTAX_ERR,
TARGET_ALL,
TARGET_FIRST
} from './constant.js';
/* regexp */
const REG_EXCLUDE_BASIC =
/[|\\]|::|[^\u0021-\u007F\s]|\[\s*[\w$*=^|~-]+(?:(?:"[\w$*=^|~\s'-]+"|'[\w$*=^|~\s"-]+')?(?:\s+[\w$*=^|~-]+)+|"[^"\]]{1,255}|'[^'\]]{1,255})\s*\]|:(?:is|where)\(\s*\)|\[\s*data-/;
const REG_HAS = /has\(/i;
const REG_IS_NOT = /(?:is|not)\(/i;
const REG_COMPLEX = new RegExp(`${COMPOUND_I}${COMBO}${COMPOUND_I}`, 'i');
const REG_LOGIC_COMPLEX = new RegExp(
`:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPLEX})`,
'i'
);
const REG_LOGIC_COMPOUND = new RegExp(
`:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPOUND})`,
'i'
);
const REG_LOGIC_HAS_COMPOUND = new RegExp(
`:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPOUND}|${HAS_COMPOUND})`
);
const REG_END_WITH_HAS = new RegExp(`:${HAS_COMPOUND}$`);
const REG_WO_LOGICAL = new RegExp(`:(?!${PSEUDO_CLASS}|${N_TH})`, 'i');
const REG_COMBO = new RegExp(COMBO);
const REG_ID = /#(\D[^#.*]+)/g;
const REG_CLASS = /\.(\D[^#.*]+)/g;
const REG_TAG = /^([^#.]+)/;
const REG_INVALID_SYNTAX =
/[+~>]\s*[+~>]|^\s*[+~>]|[+~>]\s*$|^\s*,|,\s*,|,\s*$/;
const REG_UPPERCASE_TAG =
/(?:^|[\s>+~,])[a-z\d-]*[A-Z][a-zA-Z\d-]*(?=[#.:[\s>+~,]|$)/;
/**
* Find a nested :has() pseudo-class.
* @param {object} leaf - The AST leaf to check.
* @returns {object|null} The leaf if it's :has, otherwise null.
*/
export const findNestedHas = leaf => leaf.name === 'has';
/**
* Find a logical pseudo-class that contains a nested :has().
* @param {object} leaf - The AST leaf to check.
* @returns {object|null} The leaf if it matches, otherwise null.
*/
export const findLogicalWithNestedHas = leaf => {
if (KEYS_LOGICAL.has(leaf.name) && cssTreeWalk.find(leaf, findNestedHas)) {
return leaf;
}
return null;
};
/**
* Validates nesting restrictions within :has() arguments.
* @param {Array<object>} astChildren - The AST nodes representing the :has() arguments.
* @returns {boolean} False if there's an invalid nesting constraint violation.
*/
export const validateHasNesting = astChildren => {
const l = astChildren.length;
for (let i = 0; i < l; i++) {
const item = cssTreeWalk.find(astChildren[i], findLogicalWithNestedHas);
if (item) {
// If nested :has() is wrapped inside :is() or :where(), it is forgiven.
if (item.name !== 'is' && item.name !== 'where') {
return false;
}
}
}
return true;
};
/**
* Creates a callback function to validate :has() nesting during AST walk.
* @param {object} globalObj - The global window object.
* @returns {(node: object) => void} The callback function for walkAST.
*/
export const createHasValidator = globalObj => node => {
if (
node.type === PS_CLASS_SELECTOR &&
node.name.toLowerCase() === 'has' &&
!validateHasNesting(Array.from(node.children || []))
) {
const css = cssTreeGenerate(node);
throw generateException(
`Disallowed nested :has() pseudo-class: ${css}`,
SYNTAX_ERR,
globalObj
);
}
};
/**
* Check if a combinator node is invalid (leading, trailing, or consecutive).
* @param {string} type - The current node type.
* @param {string|null} prevType - The previous node type.
* @param {boolean} isLast - Whether the current node is the last in the list.
* @returns {boolean} True if the combinator is invalid.
*/
export const isInvalidCombinator = (type, prevType, isLast) =>
type === COMBINATOR &&
(prevType === null || prevType === COMBINATOR || isLast);
/**
* Checks if a given AST is supported by the DOMSelector engine.
* @param {import('css-tree').CssNode} ast - The AST to validate.
* @returns {boolean} True if the selector is fully supported.
*/
export const isSupportedAST = ast => {
let isSupported = true;
const walk = (
node,
context = { insideHas: false, insideForgiving: false }
) => {
if (!isSupported || !node) {
return;
}
const nextContext = { ...context };
if (node.type === PS_ELEMENT_SELECTOR) {
isSupported = false;
return;
} else if (node.type === PS_CLASS_SELECTOR) {
let name = node.name;
if (name && typeof name === 'string') {
name = name.toLowerCase();
}
if (!KEYS_PS_CLASS_SUPPORTED.has(name)) {
isSupported = false;
return;
}
if (name === 'has') {
if (context.insideHas && !context.insideForgiving) {
isSupported = false;
return;
}
nextContext.insideHas = true;
} else if (name === 'is' || name === 'where') {
nextContext.insideForgiving = true;
}
}
if (node.children) {
let prevType = null;
if (node.children.head !== undefined) {
let current = node.children.head;
while (current) {
if (!current.data) {
current = current.next;
continue;
}
const childType = current.data.type;
if (
node.type === SELECTOR &&
isInvalidCombinator(childType, prevType, !current.next)
) {
if (!(prevType === null && context.insideHas)) {
isSupported = false;
return;
}
}
prevType = childType;
walk(current.data, nextContext);
if (!isSupported) {
return;
}
current = current.next;
}
} else if (Array.isArray(node.children)) {
const l = node.children.length;
for (let i = 0; i < l; i++) {
const child = node.children[i];
if (!child) {
continue;
}
const childType = child.type;
if (
node.type === SELECTOR &&
isInvalidCombinator(childType, prevType, i === l - 1)
) {
if (!(prevType === null && context.insideHas)) {
isSupported = false;
return;
}
}
prevType = childType;
walk(child, nextContext);
if (!isSupported) {
return;
}
}
}
}
if (node.selector) {
walk(node.selector, nextContext);
}
};
walk(ast);
return isSupported;
};
/**
* Extracts the rightmost subject keys (id, class, tag) from a selector.
* @param {string} selector - The CSS selector string to parse.
* @param {boolean} caseSensitive - True if the tag should be case-sensitive.
* @returns {Array<{id: string|null, className: string|null, tag: string|null}>} The list of extracted keys for each selector group.
*/
export const extractSubjectsRegExp = (selector, caseSensitive) => {
const subjects = [];
const groups = selector.split(',');
for (const item of groups) {
const group = item.trim();
if (!group) {
continue;
}
const compounds = group.split(REG_COMBO);
const rightmost = compounds.at(-1);
let idKey = null;
let classKey = null;
let tagKey = null;
if (rightmost) {
const idMatch = rightmost.match(REG_ID);
if (idMatch) {
idKey = idMatch.at(-1).slice(1);
}
const classMatch = rightmost.match(REG_CLASS);
if (classMatch) {
classKey = classMatch.at(-1).slice(1);
}
const tagMatch = rightmost.match(REG_TAG);
if (tagMatch) {
const tag = tagMatch[1];
if (tag !== '*') {
tagKey = caseSensitive ? tag : tag.toLowerCase();
}
}
}
subjects.push({ id: idKey, className: classKey, tag: tagKey });
}
return subjects;
};
/**
* Filter a selector for use with nwsapi.
* @param {string} selector - The selector string.
* @param {string} target - The target type.
* @returns {boolean} - True if the selector is valid for nwsapi.
*/
export const filterSelector = (selector, target) => {
// Basic validation and fast-fail for null/undefined/non-string values.
// Rejects stringified nullish values as well.
if (
!selector ||
typeof selector !== 'string' ||
selector === 'null' ||
selector === 'undefined'
) {
return false;
}
// Exclude querySelectorAll and querySelector
if (target === TARGET_ALL || target === TARGET_FIRST) {
return false;
}
// Validate syntax.
if (REG_INVALID_SYNTAX.test(selector)) {
return false;
}
// Exclude various complex or unsupported selectors early.
// i.e. non-ASCII, escaped selectors, namespaced selectors, pseudo-elements.
if (
selector.includes('/') ||
selector.includes('&') ||
REG_EXCLUDE_BASIC.test(selector) ||
REG_UPPERCASE_TAG.test(selector)
) {
return false;
}
// Validate attribute selector integrity.
if (selector.includes('[')) {
const index = selector.lastIndexOf('[');
if (selector.indexOf(']', index) === -1) {
return false;
}
}
// Logic for pseudo-classes.
if (selector.includes(':')) {
// Determine if the selector has complex logical structures.
const isComplex = REG_COMPLEX.test(selector);
// Handle :has() specifically.
if (REG_HAS.test(selector)) {
if (!isComplex || REG_LOGIC_HAS_COMPOUND.test(selector)) {
return false;
}
return REG_END_WITH_HAS.test(selector);
}
// Handle :is() and :not().
if (REG_IS_NOT.test(selector)) {
if (isComplex) {
return !REG_LOGIC_COMPLEX.test(selector);
}
return !REG_LOGIC_COMPOUND.test(selector);
}
// Default check for other pseudo-classes against known list.
if (REG_WO_LOGICAL.test(selector)) {
return false;
}
}
return true;
};

179
node_modules/@asamuzakjp/dom-selector/src/js/shadow.js generated vendored Normal file
View File

@ -0,0 +1,179 @@
/**
* shadow.js
*/
import { generateCSS, walkAST } from './parser.js';
import { generateException } from './utility.js';
import { COMBINATOR, KEYS_LOGICAL, SYNTAX_ERR } from './constant.js';
/**
* ShadowDOMEvaluator
* Handles the evaluation of Shadow DOM specific selectors.
*/
export class ShadowDOMEvaluator {
/* private fields */
#evaluator;
#verifyShadowHost;
/**
* @param {import('./evaluator.js').Evaluator} evaluator - The Evaluator instance.
*/
constructor(evaluator) {
this.#evaluator = evaluator;
this.#verifyShadowHost = false;
}
/**
* Gets the verifyShadowHost state.
* @returns {boolean} True if verified, otherwise false.
*/
get verifyShadowHost() {
return this.#verifyShadowHost;
}
/**
* Resets the evaluation state.
* @returns {void}
*/
reset() {
this.#verifyShadowHost = false;
}
/**
* Matches a selector for a shadow root.
* @param {import('css-tree').CssNode} ast - The AST.
* @param {DocumentFragment} node - The DocumentFragment node.
* @param {object} [opt] - Options.
* @returns {boolean} True if matches, otherwise false.
*/
matchSelectorForShadowRoot(ast, node, opt = {}) {
const { name: astName } = ast;
if (KEYS_LOGICAL.has(astName)) {
opt.isShadowRoot = true;
return this.#evaluator.matchPseudoClassSelector(ast, node, opt);
}
if (astName === 'host' || astName === 'host-context') {
const matches = this.evaluateShadowHost(ast, node, opt);
if (matches) {
this.#verifyShadowHost = true;
return true;
}
}
return false;
}
/**
* Evaluates shadow host pseudo-classes.
* @param {import('css-tree').CssNode} ast - The AST.
* @param {DocumentFragment} node - The DocumentFragment node.
* @returns {boolean} True if matches, otherwise false.
*/
evaluateShadowHost(ast, node) {
const { children: astChildren, name: astName } = ast;
// Handle simple pseudo-class (no arguments).
if (!Array.isArray(astChildren)) {
if (astName === 'host') {
return true;
}
const msg = `Invalid selector :${astName}`;
this.#evaluator.onError(
generateException(msg, SYNTAX_ERR, this.#evaluator.window)
);
return false;
}
// Handle functional pseudo-class like :host(...).
if (astName !== 'host' && astName !== 'host-context') {
const msg = `Invalid selector :${astName}()`;
this.#evaluator.onError(
generateException(msg, SYNTAX_ERR, this.#evaluator.window)
);
return false;
}
if (astChildren.length === 0) {
const css = generateCSS(ast);
const msg = `Invalid selector ${css}`;
this.#evaluator.onError(
generateException(msg, SYNTAX_ERR, this.#evaluator.window)
);
return false;
}
const { host } = node;
for (const child of astChildren) {
const { branches } = walkAST(child);
for (const branch of branches) {
if (astName === 'host' && this.#evaluateHostPseudo(branch, host, ast)) {
return true;
} else if (
astName === 'host-context' &&
this.#evaluateHostContextPseudo(branch, host, ast)
) {
return true;
}
}
}
return false;
}
/**
* Evaluates the :host() pseudo-class.
* @private
* @param {Array<object>} leaves - The AST leaves.
* @param {Element} host - The host element.
* @param {import('css-tree').CssNode} ast - The original AST for error reporting.
* @returns {boolean} True if matches, otherwise false.
*/
#evaluateHostPseudo(leaves, host, ast) {
const l = leaves.length;
for (let i = 0; i < l; i++) {
const leaf = leaves[i];
if (leaf.type === COMBINATOR) {
const css = generateCSS(ast);
const msg = `Invalid selector ${css}`;
this.#evaluator.onError(
generateException(msg, SYNTAX_ERR, this.#evaluator.window)
);
return false;
}
if (!this.#evaluator.matchSelector(leaf, host)) {
return false;
}
}
return true;
}
/**
* Evaluates the :host-context() pseudo-class.
* @private
* @param {Array<object>} leaves - The AST leaves.
* @param {Element} host - The host element.
* @param {import('css-tree').CssNode} ast - The original AST for error reporting.
* @returns {boolean} True if matched, otherwise false.
*/
#evaluateHostContextPseudo(leaves, host, ast) {
let parent = host;
while (parent) {
let bool;
const l = leaves.length;
for (let i = 0; i < l; i++) {
const leaf = leaves[i];
if (leaf.type === COMBINATOR) {
const css = generateCSS(ast);
const msg = `Invalid selector ${css}`;
this.#evaluator.onError(
generateException(msg, SYNTAX_ERR, this.#evaluator.window)
);
return false;
}
bool = this.#evaluator.matchSelector(leaf, parent);
if (!bool) {
break;
}
}
if (bool) {
return true;
}
parent = parent.parentNode || parent.host;
}
return false;
}
}

View File

@ -0,0 +1,256 @@
/**
* traverser.js
*/
/* import */
import { matchPseudoElementSelector } from './matcher.js';
import {
canUseFastClassSearch,
canUseFastIdSearch,
canUseFastTagSearch,
traverseNode
} from './utility.js';
/* constants */
import {
DIR_NEXT,
ID_SELECTOR,
CLASS_SELECTOR,
TYPE_SELECTOR,
PS_ELEMENT_SELECTOR,
SHOW_CONTAINER
} from './constant.js';
/**
* DOMTraverser
* Handles DOM tree traversal and combinator matches.
*/
export class DOMTraverser {
#evaluator;
#walkers;
/**
* @param {import('./evaluator.js').Evaluator} evaluator - The Evaluator instance.
*/
constructor(evaluator) {
this.#evaluator = evaluator;
}
/**
* Resets the traversal state.
* @returns {void}
*/
reset() {
this.#walkers = null;
}
/**
* Creates a TreeWalker.
* @param {Document|DocumentFragment|Element} node - The Document, DocumentFragment, or Element node.
* @param {object} [opt] - Options.
* @param {boolean} [opt.force] - Force creation of a new TreeWalker.
* @param {number} [opt.whatToShow] - The NodeFilter whatToShow value.
* @returns {TreeWalker} The TreeWalker object.
*/
createTreeWalker(node, opt = {}) {
const { force = false, whatToShow = SHOW_CONTAINER } = opt;
if (force) {
return this.#evaluator.document.createTreeWalker(node, whatToShow);
}
if (!this.#walkers) {
this.#walkers = new WeakMap();
}
let walker = this.#walkers.get(node);
if (walker) {
return walker;
}
walker = this.#evaluator.document.createTreeWalker(node, whatToShow);
this.#walkers.set(node, walker);
return walker;
}
/**
* Yields combinator matches.
* @param {import('./processor.js').ProcessedBranch} twig - The twig object.
* @param {Element} node - The Element node.
* @param {import('../index.js').FindOptions} [opt] - Options.
* @yields {Element} The matched node.
*/
*yieldCombinatorMatches(twig, node, opt = {}) {
const {
combo: { name: comboName },
leaves
} = twig;
const { dir } = opt;
switch (comboName) {
case '+': {
const refNode =
dir === DIR_NEXT
? node.nextElementSibling
: node.previousElementSibling;
if (refNode && this.#evaluator.matchLeaves(leaves, refNode, opt)) {
yield refNode;
}
break;
}
case '~': {
let refNode =
dir === DIR_NEXT
? node.nextElementSibling
: node.previousElementSibling;
while (refNode) {
if (this.#evaluator.matchLeaves(leaves, refNode, opt)) {
yield refNode;
}
refNode =
dir === DIR_NEXT
? refNode.nextElementSibling
: refNode.previousElementSibling;
}
break;
}
case '>': {
if (dir === DIR_NEXT) {
let refNode = node.firstElementChild;
while (refNode) {
if (this.#evaluator.matchLeaves(leaves, refNode, opt)) {
yield refNode;
}
refNode = refNode.nextElementSibling;
}
} else {
const { parentNode } = node;
if (
parentNode &&
this.#evaluator.matchLeaves(leaves, parentNode, opt)
) {
yield parentNode;
}
}
break;
}
case ' ':
default: {
if (dir === DIR_NEXT) {
for (const refNode of this.yieldFindDescendantNodes(
leaves,
node,
opt
)) {
yield refNode;
}
} else {
const ancestors = [];
let refNode = node.parentNode;
while (refNode) {
if (this.#evaluator.matchLeaves(leaves, refNode, opt)) {
ancestors.push(refNode);
}
refNode = refNode.parentNode;
}
if (ancestors.length) {
for (let i = ancestors.length - 1; i >= 0; i--) {
yield ancestors[i];
}
}
}
}
}
}
/**
* Finds descendant nodes and yields matches.
* @param {Array<object>} leaves - The AST leaves.
* @param {DocumentFragment|Element} baseNode - The base Element node or Element.shadowRoot.
* @param {import('../index.js').FindOptions} opt - Options.
* @yields {Element} The matched node.
*/
*yieldFindDescendantNodes(leaves, baseNode, opt) {
const [leaf] = leaves;
const { type: leafType } = leaf;
const leafName = this.#evaluator.getUnescapedName(leaf);
const filterLeaves = this.#evaluator.getFilterLeaves(leaves);
const isSimple = filterLeaves.length === 0;
switch (leafType) {
case ID_SELECTOR: {
if (canUseFastIdSearch(baseNode, this.#evaluator.root)) {
const foundNode = this.#evaluator.root.getElementById(leafName);
if (
foundNode &&
foundNode !== baseNode &&
baseNode.contains(foundNode)
) {
if (
isSimple ||
this.#evaluator.matchLeaves(filterLeaves, foundNode, opt)
) {
yield foundNode;
return;
}
}
break;
}
break;
}
case CLASS_SELECTOR: {
if (canUseFastClassSearch(baseNode)) {
const collection = baseNode.getElementsByClassName(leafName);
for (let i = 0, len = collection.length; i < len; i++) {
const item = collection[i];
if (
isSimple ||
this.#evaluator.matchLeaves(filterLeaves, item, opt)
) {
yield item;
}
}
return;
}
break;
}
case TYPE_SELECTOR: {
if (canUseFastTagSearch(baseNode, leafName)) {
const collection = baseNode.getElementsByTagName(leafName);
for (let i = 0, len = collection.length; i < len; i++) {
const item = collection[i];
if (
isSimple ||
this.#evaluator.matchLeaves(filterLeaves, item, opt)
) {
yield item;
}
}
return;
}
break;
}
case PS_ELEMENT_SELECTOR: {
matchPseudoElementSelector(leafName, leafType, opt);
return;
}
default: {
// no-op
}
}
yield* this.yieldTraverseAllDescendants(baseNode, leaves, opt);
}
/**
* Traverses all descendant nodes and yields matches.
* @param {DocumentFragment|Element} baseNode - The base Element node or Element.shadowRoot.
* @param {Array<object>} leaves - The AST leaves.
* @param {import('../index.js').FindOptions} opt - Options.
* @yields {Element} The matched node.
*/
*yieldTraverseAllDescendants(baseNode, leaves, opt) {
const walker = this.createTreeWalker(baseNode);
traverseNode(baseNode, walker);
let currentNode = walker.firstChild();
while (currentNode) {
if (this.#evaluator.matchLeaves(leaves, currentNode, opt)) {
yield currentNode;
}
currentNode = walker.nextNode();
}
}
}

1132
node_modules/@asamuzakjp/dom-selector/src/js/utility.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

54
node_modules/@asamuzakjp/dom-selector/types/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,54 @@
/*!
* DOM Selector - A CSS selector engine.
* @license MIT
* @copyright asamuzaK (Kazz)
* @see {@link https://github.com/asamuzaK/domSelector/blob/main/LICENSE}
*/
export type CheckResult = {
match: boolean;
pseudoElement: string | null;
ast: import('css-tree').CssNode | null;
error: DOMException | Error | null;
};
export type SelectorSubject = {
id: string | null;
className: string | null;
tag: string | null;
};
export type UserOptions = {
noexcept?: boolean;
warn?: boolean;
};
export type FindOptions = {
dir?: string;
check?: boolean;
forgive?: boolean;
noexcept?: boolean;
warn?: boolean;
isShadowRoot?: boolean;
globalObject?: object;
};
export declare class DOMSelector {
#private;
constructor(window: Window, document: Document, opt?: {
cacheSize?: number;
idlUtils?: object;
maxLength?: number;
});
clear(clearAll?: boolean): void;
extractSubjects(selector: string, caseSensitive?: boolean): Array<SelectorSubject>;
supports(selector: string): boolean;
check(selector: string, node: Element, opt?: {
requireAst?: boolean;
}): CheckResult;
matches(selector: string, node: Element, opt?: UserOptions): boolean;
closest(selector: string, node: Element, opt?: UserOptions): Element | null;
querySelector(selector: string, node: Document | DocumentFragment | Element, opt?: UserOptions): Element | null;
querySelectorAll(selector: string, node: Document | DocumentFragment | Element, opt?: UserOptions): Array<Element>;
private #cloneAST;
private #wrapNode;
private #validateSelector;
private #validateNodeType;
private #tryNwsapi;
private #findNodes;
}

View File

@ -0,0 +1,94 @@
export declare const ATRULE = "Atrule";
export declare const ATTR_SELECTOR = "AttributeSelector";
export declare const CLASS_SELECTOR = "ClassSelector";
export declare const COMBINATOR = "Combinator";
export declare const DIR_NEXT = "next";
export declare const DIR_PREV = "prev";
export declare const IDENT = "Identifier";
export declare const ID_SELECTOR = "IdSelector";
export declare const NEST_SELECTOR = "NestingSelector";
export declare const NOT_SUPPORTED_ERR = "NotSupportedError";
export declare const NTH = "Nth";
export declare const OPERATOR = "Operator";
export declare const PS_CLASS_SELECTOR = "PseudoClassSelector";
export declare const PS_ELEMENT_SELECTOR = "PseudoElementSelector";
export declare const RULE = "Rule";
export declare const SCOPE = "Scope";
export declare const SELECTOR = "Selector";
export declare const SELECTOR_LIST = "SelectorList";
export declare const STRING = "String";
export declare const SYNTAX_ERR = "SyntaxError";
export declare const TARGET_ALL = "all";
export declare const TARGET_FIRST = "first";
export declare const TARGET_LINEAL = "lineal";
export declare const TARGET_SELF = "self";
export declare const TYPE_SELECTOR = "TypeSelector";
export declare const BIT_01 = 1;
export declare const BIT_02 = 2;
export declare const BIT_04 = 4;
export declare const BIT_08 = 8;
export declare const BIT_16 = 16;
export declare const BIT_32 = 32;
export declare const BIT_FFFF = 65535;
export declare const DUO = 2;
export declare const HEX = 16;
export declare const TYPE_FROM = 8;
export declare const TYPE_TO = -1;
export declare const ELEMENT_NODE = 1;
export declare const TEXT_NODE = 3;
export declare const DOCUMENT_NODE = 9;
export declare const DOCUMENT_FRAGMENT_NODE = 11;
export declare const DOCUMENT_POSITION_PRECEDING = 2;
export declare const DOCUMENT_POSITION_CONTAINS = 8;
export declare const DOCUMENT_POSITION_CONTAINED_BY = 16;
export declare const FILTER_ACCEPT = 1;
export declare const FILTER_REJECT = 2;
export declare const FILTER_SKIP = 3;
export declare const SHOW_ALL = 4294967295;
export declare const SHOW_CONTAINER = 1281;
export declare const SHOW_DOCUMENT = 256;
export declare const SHOW_DOCUMENT_FRAGMENT = 1024;
export declare const SHOW_ELEMENT = 1;
export declare const ALPHA_NUM = "[A-Z\\d]+";
export declare const CHILD_IDX = "(?:first|last|only)-(?:child|of-type)";
export declare const DIGIT = "(?:0|[1-9]\\d*)";
export declare const LANG_ALPHA_NUM = "[A-Z\\d]{1,8}";
export declare const LANG_SKIP_ALPHA_NUM = "[A-Z\\d]{2,8}";
export declare const LANG_PART = "(?:-[A-Z\\d]{1,8})*";
export declare const LANG_PART_SKIP = "(?:-[A-Z\\d]{2,8})*";
export declare const PSEUDO_CLASS = "(?:any-)?link|(?:first|last|only)-(?:child|of-type)|checked|empty|indeterminate|read-(?:only|write)|target";
export declare const ANB = "[+-]?(?:(?:0|[1-9]\\d*)n?|n)|(?:[+-]?(?:0|[1-9]\\d*))?n\\s*[+-]\\s*(?:0|[1-9]\\d*)";
export declare const COMBO = "\\s?[\\s>~+]\\s?";
export declare const DESCEND = "\\s?[\\s>]\\s?";
export declare const SIBLING = "\\s?[+~]\\s?";
export declare const LOGIC_IS = ":is\\(\\s*[^)]+\\s*\\)";
export declare const N_TH = "nth-(?:last-)?(?:child|of-type)\\(\\s*(?:even|odd|[+-]?(?:(?:0|[1-9]\\d*)n?|n)|(?:[+-]?(?:0|[1-9]\\d*))?n\\s*[+-]\\s*(?:0|[1-9]\\d*))\\s*\\)";
export declare const ATTR_TYPE = "\\[[^|\\]]+\\]";
export declare const SUB_TYPE = "\\[[^|\\]]+\\]|[#.:][\\w-]+";
export declare const SUB_TYPE_WO_PSEUDO = "\\[[^|\\]]+\\]|[#.][\\w-]+";
export declare const TAG_TYPE_WO_UNIVERSAL = "[A-Za-z][\\w-]*";
export declare const TAG_TYPE = "\\*|[A-Za-z][\\w-]*";
export declare const TAG_TYPE_I = "\\*|[A-Z][\\w-]*";
export declare const COMPOUND = "(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+)+)";
export declare const COMPOUND_L = "(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+)";
export declare const COMPOUND_I = "(?:\\*|[A-Z][\\w-]*|(?:\\*|[A-Z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+)+)";
export declare const COMPOUND_WO_PSEUDO = "(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.][\\w-]+)+)";
export declare const COMPLEX = "(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+)+)(?:\\s?[\\s>~+]\\s?(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+)+))*";
export declare const COMPLEX_L = "(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+)(?:\\s?[\\s>~+]\\s?(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+))*";
export declare const HAS_COMPOUND = "has\\([\\s>]?\\s*(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.][\\w-]+)+)\\s*\\)";
export declare const LOGIC_COMPOUND = "(?:is|not)\\(\\s*(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+)(?:\\s*,\\s*(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+))*\\s*\\)";
export declare const LOGIC_COMPLEX = "(?:is|not)\\(\\s*(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+)(?:\\s?[\\s>~+]\\s?(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+))*(?:\\s*,\\s*(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+)(?:\\s?[\\s>~+]\\s?(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+))*)*\\s*\\)";
export declare const FORM_PARTS: Array<string>;
export declare const INPUT_BUTTON: Array<string>;
export declare const INPUT_CHECK: Array<string>;
export declare const INPUT_DATE: Array<string>;
export declare const INPUT_TEXT: Array<string>;
export declare const INPUT_EDIT: Array<string>;
export declare const INPUT_LTR: Array<string>;
export declare const ATTR_VALUE_I: Array<string>;
export declare const KEYS_LOGICAL: Set<string>;
export declare const KEYS_PS_CLASS_SUPPORTED: Set<string>;
export declare const KEYS_PS_CLASS_UNSUPPORTED: Set<string>;
export declare const KEYS_PS_ELEMENT_UNSUPPORTED: Set<string>;
export declare const MIME_HTML: string;
export declare const NS_HTML: string;

View File

@ -0,0 +1,30 @@
import { EventHandler } from './event.js';
export declare class Evaluator {
#private;
window: Window;
documentCache: WeakMap<WeakKey, any>;
check: boolean | undefined;
noexcept: boolean | undefined;
warn: boolean | undefined;
node: Document | DocumentFragment | Element | undefined;
pseudoElements: any[] | undefined;
constructor(window: Window);
get eventHandler(): EventHandler;
get invalidate(): boolean;
set invalidate(value: boolean);
get verifyShadowHost(): boolean;
setup(selector: string, node: Document | DocumentFragment | Element, opt?: import('../index.js').FindOptions): Evaluator;
onError(e: Error, opt?: import('../index.js').FindOptions): void;
destroy(): void;
clearResults(all?: boolean): void;
matchSelector(ast: import('css-tree').CssNode, node: Document | DocumentFragment | Element, opt: import('../index.js').FindOptions): boolean;
matchLeaves(leaves: Array<import('css-tree').CssNode>, node: Element, opt?: import('../index.js').FindOptions): boolean;
getFilterLeaves(leaves: Array<import('css-tree').CssNode>): Array<object>;
getUnescapedName(ast: import('css-tree').CssNode): string;
evaluateShadowHost(ast: import('css-tree').CssNode, node: DocumentFragment): boolean;
matchPseudoClassSelector(ast: import('css-tree').CssNode, node: Element, opt: import('../index.js').FindOptions): boolean;
createTreeWalker(node: Document | DocumentFragment | Element, opt: object): TreeWalker;
yieldCombinatorMatches(twig: import('./processor.js').ProcessedBranch, node: Element, opt: import('../index.js').FindOptions): Generator<any, void, unknown>;
yieldFindDescendantNodes(leaves: Array<import('css-tree').CssNode>, baseNode: DocumentFragment | Element, opt: import('../index.js').FindOptions): Generator<any, void, unknown>;
private #matchSelectorForElement;
}

View File

@ -0,0 +1,13 @@
export declare class EventHandler {
#private;
constructor(window: Window);
get currentEvent(): Event | null;
get currentFocus(): Event | null;
get lastFocusVisible(): Element | null;
set lastFocusVisible(node: Element);
handleFocusEvent(evt: Event): void;
handleKeyboardEvent(evt: KeyboardEvent): void;
handleMouseEvent(evt: MouseEvent): void;
registerEventListeners(): void;
destroy(): void;
}

View File

@ -0,0 +1,43 @@
import { Evaluator } from './evaluator.js';
export type StrategyOptions = {
complex?: boolean;
precede?: boolean;
dir?: string;
filterLeaves?: Array<import('css-tree').CssNode>;
};
export type TraversalOptions = {
force?: boolean;
precede?: boolean;
boundaryNode?: Element;
startNode?: Element;
targetType?: string;
};
export declare class Finder extends Evaluator {
#private;
get selectorAST(): import('css-tree').CssNode | null;
setup(selector: string, node: Document | DocumentFragment | Element, opt: import('../index.js').FindOptions): Finder;
find(targetType: string): Set<Element> | import('../index.js').CheckResult;
private #collectNodes;
private #findEntryNodes;
private #findEntryNodesForPseudoElement;
private #findEntryNodesForId;
private #findEntryNodesForClass;
private #findEntryNodesForType;
private #findEntryNodesForOther;
private #processPendingItems;
private #processComplexBranchAll;
private #dfsComplexBranchNext;
private #processComplexBranchFirst;
private #processComplexBranchFirstNext;
private #matchNodeNext;
private #processComplexBranchFirstPrev;
private #hasValidPathPrev;
private #checkSelfOrLinealTarget;
private #matchSelf;
private #findLineal;
private #filterAndFormatCollection;
private #fallbackToWalkerResult;
private #findNodeWalker;
private #findPrecede;
private #traverseAndCollectNodes;
}

View File

@ -0,0 +1,12 @@
export type MapperResult = {
ast: Array<import('./processor.js').ProcessedASTNode>;
invalidate: boolean;
nodes: Array<Array<Element>>;
selectorAST: import('css-tree').CssNode;
};
export declare class Mapper {
#private;
constructor(context: import('./finder.js').Finder);
correspond(selector: string): MapperResult;
private #prepareResult;
}

View File

@ -0,0 +1,12 @@
export declare const matchPseudoElementSelector: (astName: string, astType: string, { forgive, globalObject, warn }?: import('../index.js').FindOptions) => void;
export declare const matchDirectionPseudoClass: (ast: import('css-tree').CssNode, node: Element, dirCache?: WeakMap<any, any>) => boolean;
export declare const matchLanguagePseudoClass: (ast: import('css-tree').CssNode, node: Element, langCache?: WeakMap<any, any>) => boolean;
export declare const matchCheckedPseudoClass: (node: Element) => boolean;
export declare const matchLinkPseudoClass: (node: Element) => boolean;
export declare const matchOpenPseudoClass: (node: Element) => boolean;
export declare const matchPlaceholderShownPseudoClass: (node: Element, keys: Set<string>) => boolean;
export declare const matchRangePseudoClass: (astName: string, node: Element, keys: Set<string>) => boolean;
export declare const matchReadOnlyPseudoClass: (astName: string, node: Element) => boolean;
export declare const matchRequiredPseudoClass: (astName: string, node: Element, keys: Set<string>) => boolean;
export declare const matchAttributeSelector: (ast: import('css-tree').CssNode, node: Element, { check, forgive, globalObject }?: import('../index.js').FindOptions) => boolean;
export declare const matchTypeSelector: (ast: import('css-tree').CssNode, node: Element, { check, forgive, globalObject }?: import('../index.js').FindOptions) => boolean;

View File

@ -0,0 +1,64 @@
export type ResolverFactory = (c: Element | Array<Element> | NodeList, f?: ((element: Element) => boolean | void), x?: Element | Document | null, r?: boolean | Array<Element>) => boolean | Array<Element>;
export declare const concatCall: (nodes: Array<Element> | NodeList, callback?: ((element: Element) => boolean | void) | undefined) => Array<Element>;
export declare const isHTML: (node: Element | Document) => boolean;
export declare const isTarget: (node: Element) => boolean;
export declare const isIndeterminate: (node: Element) => boolean;
export declare const optimize: (selector: string, tokens: Array<string>) => string;
export declare const matchAssert: (factory: Array<ResolverFactory>, element: Element, callback?: ((element: Element) => boolean | void) | undefined) => boolean;
export declare const solveNth: (element: Element, dir: boolean | number, state: object, isOfType: boolean) => number;
export declare class Nwsapi {
#private;
hasDupes: boolean | undefined;
constructor(window: Window, document: Document, cacheSize?: number);
private #documentOrder;
private #unique;
byId(id: string, context: Element | Document): Array<Element>;
byTag(tag: string, context: Element | Document | DocumentFragment): Array<Element>;
byClass(cls: string, context: Element | Document | DocumentFragment): Array<Element>;
private #emit;
private #switchContext;
compileSelector(expression: string, source: string, mode: boolean): string;
compileUniversal(selector: string, source: string): {
source: string;
selector: string;
};
compileId(selector: string, source: string): {
source: string;
selector: string;
};
compileClass(selector: string, source: string): {
source: string;
selector: string;
};
compileTag(selector: string, source: string): {
source: string;
selector: string;
};
compileAttribute(selector: string, source: string): {
source: string;
selector: string;
};
compileCombinator(symbol: string, selector: string, source: string): {
source: string;
selector: string;
};
compilePseudo(selector: string, source: string, selectorString: string): {
source: string;
selector: string;
};
compilePseudoStructural(match: Array<string>, source: string): string;
compilePseudoTreeStruct(match: Array<string>, source: string, selectorString: string): string;
compilePseudoLogical(match: Array<string>, source: string): string;
compilePseudoLocation(match: Array<string>, source: string): string;
compilePseudoInputState(match: Array<string>, source: string): string;
compilePseudoInputValue(match: Array<string>, source: string): string;
compile(selector: string, mode: boolean): ResolverFactory;
collect(selectors: Array<string>, context: Element | Document, callback?: ((element: Element) => boolean | void) | undefined): object;
private #matchCollect;
private #parseSelector;
match(selectors: string, element: Element, callback?: ((element: Element) => boolean | void) | undefined): boolean;
closest(selectors: string, element: Element, callback?: ((element: Element) => boolean | void) | undefined): Element | null;
select(selectors: string, context: Element | Document, callback?: ((element: Element) => boolean | void) | undefined): Array<Element>;
first(selectors: string, context: Element | Document, callback?: ((element: Element) => boolean | void) | undefined): Element | null;
clear(clearAll?: boolean): void;
}

View File

@ -0,0 +1,20 @@
export declare const unescapeSelector: (selector?: string) => string;
export declare const preprocess: (value: string) => string;
export declare const parseSelector: (sel: string, context?: string) => import('css-tree').CssNode;
export declare const walkAST: (ast?: import('css-tree').CssNode, toObject?: boolean, callback?: (node: import('css-tree').CssNode) => void) => {
branches: Array<Array<import('css-tree').CssNode>>;
info: object;
};
export declare const compareASTNodes: (a: import('css-tree').CssNode, b: import('css-tree').CssNode) => number;
export declare const sortAST: (asts: Array<import('css-tree').CssNode>) => Array<import('css-tree').CssNode>;
export declare const parseAstName: (selector: string) => {
prefix: string;
localName: string;
};
export declare const extractSubjectsAst: (ast: import('css-tree').CssNode) => Array<{
id: string | null;
className: string | null;
tag: string | null;
}>;
export declare const findAST: typeof import('css-tree').find;
export declare const generateCSS: typeof import('css-tree').generate;

View File

@ -0,0 +1,19 @@
export type ProcessedBranch = {
combo: import('css-tree').CssNode | null;
leaves: Array<import('css-tree').CssNode>;
};
export type ProcessedASTNode = {
branch: Array<ProcessedBranch>;
dir: string | null;
filtered: boolean;
find: boolean;
};
export declare class SelectorProcessor {
#private;
constructor(context: import('./finder.js').Finder);
process(branches: Array<Array<import('css-tree').CssNode>>, selector: string): {
ast: Array<ProcessedASTNode>;
descendant: boolean;
invalidate?: boolean;
};
}

View File

@ -0,0 +1,31 @@
export declare class PseudoClassEvaluator {
#private;
constructor(evaluator: import('./evaluator.js').Evaluator);
clearResults(all?: boolean): void;
reset(): void;
matchPseudoClassSelector(ast: import('css-tree').CssNode, node: Element, opt?: import('../index.js').FindOptions): boolean;
private #evaluateLogicalPseudo;
private #evaluatePseudoClassFunc;
private #matchActivePseudoClass;
private #matchDefaultPseudoClass;
private #matchDisabledPseudoClass;
private #matchEmptyPseudoClass;
private #matchFocusPseudoClass;
private #matchFocusVisiblePseudoClass;
private #matchFocusWithinPseudoClass;
private #matchHoverPseudoClass;
private #matchIndeterminatePseudoClass;
private #matchLocalLinkPseudoClass;
private #matchTargetPseudoClass;
private #matchValidityPseudoClass;
private #matchAnPlusB;
private #getSelectorBranches;
private #filterNthChildOfSelectorBranches;
private #matchLogicalPseudoFunc;
private #evaluateHasPseudo;
private #buildHasAllowlist;
private #acquireSet;
private #matchHasPseudoFunc;
private #hasCombinatorMatch;
private #checkNode;
}

View File

@ -0,0 +1,12 @@
export declare const findNestedHas: (leaf: object) => object | null;
export declare const findLogicalWithNestedHas: (leaf: object) => object | null;
export declare const validateHasNesting: (astChildren: Array<object>) => boolean;
export declare const createHasValidator: (globalObj: object) => (node: object) => void;
export declare const isInvalidCombinator: (type: string, prevType: string | null, isLast: boolean) => boolean;
export declare const isSupportedAST: (ast: import('css-tree').CssNode) => boolean;
export declare const extractSubjectsRegExp: (selector: string, caseSensitive: boolean) => Array<{
id: string | null;
className: string | null;
tag: string | null;
}>;
export declare const filterSelector: (selector: string, target: string) => boolean;

View File

@ -0,0 +1,10 @@
export declare class ShadowDOMEvaluator {
#private;
constructor(evaluator: import('./evaluator.js').Evaluator);
get verifyShadowHost(): boolean;
reset(): void;
matchSelectorForShadowRoot(ast: import('css-tree').CssNode, node: DocumentFragment, opt?: object): boolean;
evaluateShadowHost(ast: import('css-tree').CssNode, node: DocumentFragment): boolean;
private #evaluateHostPseudo;
private #evaluateHostContextPseudo;
}

View File

@ -0,0 +1,12 @@
export declare class DOMTraverser {
#private;
constructor(evaluator: import('./evaluator.js').Evaluator);
reset(): void;
createTreeWalker(node: Document | DocumentFragment | Element, opt?: {
force?: boolean;
whatToShow?: number;
}): TreeWalker;
yieldCombinatorMatches(twig: import('./processor.js').ProcessedBranch, node: Element, opt?: import('../index.js').FindOptions): Generator<any, void, unknown>;
yieldFindDescendantNodes(leaves: Array<object>, baseNode: DocumentFragment | Element, opt: import('../index.js').FindOptions): Generator<any, void, unknown>;
yieldTraverseAllDescendants(baseNode: DocumentFragment | Element, leaves: Array<object>, opt: import('../index.js').FindOptions): Generator<Node, void, unknown>;
}

View File

@ -0,0 +1,33 @@
export declare const getType: (o: object) => string;
export declare const verifyArray: (arr: any[], type: string) => any[];
export declare const generateException: (msg: string, name: string, globalObject?: object) => DOMException;
export declare const stringifyValue: (value: unknown, globalObject?: object) => string;
export declare const resolveContent: (node: Document | DocumentFragment | Element) => Array<Document | DocumentFragment | Element | boolean>;
export declare const traverseNode: (node: Element, walker: TreeWalker, force?: boolean) => Element | null;
export declare const isHTMLElement: (node: Element) => boolean;
export declare const isCustomElement: (node: Element, { formAssociated }?: {
formAssociated?: boolean;
}) => boolean;
export declare const getSlottedTextContent: (node: Element) => string | null;
export declare const getDirectionality: (node: Element, dirCache?: WeakMap<Element, string>) => string | null;
export declare const getLanguageAttribute: (node: Element, langCache?: WeakMap<Element, string>) => string | null;
export declare const isContentEditable: (node: Element) => boolean;
export declare const isVisible: (node: Element) => boolean;
export declare const isFocusVisible: (node: Element) => boolean;
export declare const isFocusableArea: (node: Element) => boolean;
export declare const isFocusable: (node: Element) => boolean;
export declare const getNamespaceURI: (ns: string, node: Element) => string | null;
export declare const isNamespaceDeclared: (ns?: string, node?: Element) => boolean;
export declare const isPreceding: (nodeA: Element, nodeB: Element) => boolean;
export declare const compareNodes: (a: Element, b: Element) => number;
export declare const sortNodes: (nodes?: Array<Element> | Set<Element>) => Array<Element>;
export declare const findBestSeed: (nodes: Array<object>, state?: object) => object;
export declare const populateHasAllowlist: (current: Element, list: WeakSet<Element>, visitedAncestors: Set<Element>) => void;
export declare const collectAllDescendants: (node: Document | DocumentFragment | Element, document: Document) => Array<Element>;
export declare const hasAttributeLocalName: (node: Element, name: string) => boolean;
export declare const findByExactIdAttribute: (selector: string, node: Document | DocumentFragment | Element) => Element | null | undefined;
export declare const findBySimpleAttribute: (selector: string, node: Document | DocumentFragment | Element) => Array<Element> | null;
export declare const getTraversalStrategy: (branch: Array<object>, targetType: string, hasScope: boolean, scoped: boolean) => object;
export declare const canUseFastIdSearch: (node: Element, root: Document | DocumentFragment | Element) => boolean;
export declare const canUseFastClassSearch: (node: Document | DocumentFragment | Element) => boolean;
export declare const canUseFastTagSearch: (node: Document | DocumentFragment | Element, leafName: string) => boolean;

19
node_modules/@bramus/specificity/LICENSE generated vendored Normal file
View File

@ -0,0 +1,19 @@
Copyright (c) 2022 Bramus Van Damme - https://www.bram.us/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

164
node_modules/@bramus/specificity/README.md generated vendored Normal file
View File

@ -0,0 +1,164 @@
[![Calculate CSS Specificity](./screenshots/calculate-specificity.png)](https://codepen.io/bramus/pen/WNXyoYm)
# Specificity
`@bramus/specificity` is a package to calculate the specificity of CSS Selectors. It also includes some convenience functions to compare, sort, and filter an array of specificity values.
Supports [Selectors Level 4](https://www.w3.org/TR/selectors-4/), including those special cases `:is()`, `:where()`, `:not()`, etc.
Demo: [https://codepen.io/bramus/pen/WNXyoYm](https://codepen.io/bramus/pen/WNXyoYm)
## Installation
```bash
npm i @bramus/specificity
```
## Usage / Example
At its core, `@bramus/specificity` exposes a `Specificity` class. Its static `calculate` method can be used to calculate the specificity of a given CSS [Selector List](https://www.w3.org/TR/selectors-4/#grouping) string.
```js
import Specificity from '@bramus/specificity';
const specificities = Specificity.calculate('header:where(#top) nav li:nth-child(2n), #doormat');
```
Because `calculate` accepts a [Selector List](https://www.w3.org/TR/selectors-4/#grouping) — which can contain more than 1 [Selector](https://www.w3.org/TR/selectors-4/#selector) — it will always return an array, with each entry being a `Specificity` instance — one per found selector.
```js
const specificities = Specificity.calculate('header:where(#top) nav li:nth-child(2n), #doormat');
specificities.map((s) => s.toString()); // ~> ["(0,1,3)","(1,0,0)"]
```
💡 If you know you’re passing only a single Selector into `calculate()`, you can use JavaScript’s built-in destructuring to keep your variable names clean.
```js
const [s] = Specificity.calculate('header:where(#top) nav li:nth-child(2n)');
s.toString(); // ~> "(0,1,3)"
```
💡 Under the hood, `@bramus/specificity` uses [CSSTree](https://github.com/csstree/csstree) to do the parsing of strings to Selectors. As a result, the `calculate` method also accepts a [CSSTree AST](https://github.com/csstree/csstree/blob/master/docs/ast.md) of the types `Selector` and `SelectorList`.
If you have a pre-parsed CSSTree AST of the type `Selector` you can pass it into `Specificity.calculateForAST()`. It [performs slightly better](#benchmark) than `Specificity.calculate()` as it needs to check fewer things. It differs from `Specificity.calculate()` in that it does not return an array of `Specificity` instances but only a single value.
## The Return Format
A calculated specificity is represented as an instance of the `Specificity` class. The `Specificity` class includes methods to get the specificity value in a certain format, along with some convenience methods to compare it against other instances.
```js
// 🚀 Thunderbirds are go!
import Specificity from '@bramus/specificity';
// ✨ Calculate specificity for each Selector in the given Selector List
const specificities = Specificity.calculate('header:where(#top) nav li:nth-child(2n), #doormat');
// 🚚 The values in the array are instances of the Specificity class
const s = specificities[0]; // Instance of Specificity
// 👀 Read the specificity value using one of its accessors
s.value; // { a: 0, b: 1, c: 3 }
s.a; // 0
s.b; // 1
s.c; // 3
// 🛠 Convert the calculated value to various formats using one of the toXXX() instance methods
s.toString(); // "(0,1,3)"
s.toArray(); // [0, 1, 3]
s.toObject(); // { a: 0, b: 1, c: 3 }
// 💡 Extract the matched selector string
s.selectorString(); // "header:where(#top) nav li:nth-child(2n)"
// 🔀 Use one of its instance comparison methods to compare it to another Specificity instance
s.isEqualTo(specificities[1]); // false
s.isGreaterThan(specificities[1]); // false
s.isLessThan(specificities[1]); // true
// 💻 Don’t worry about JSON.stringify()
JSON.stringify(s);
// {
// "selector": 'header:where(#top) nav li:nth-child(2n)',
// "asObject": { "a": 0, "b": 1, "c": 3 },
// "asArray": [0, 1, 3],
// "asString": "(0,1,3)",
// }
```
## Utility Functions (Static Methods)
This package also exposes some utility functions to work with specificities. These utility functions are all exposed as static methods on the `Specificity` class.
- Comparing:
- `Specificity.compare(s1, s2)`: Compares s1 to s2. Returns a value that can be:
- `> 0` = Sort s2 before s1 _(i.e. s1 is more specific than s2)_
- `0` = Keep original order of s1 and s2 _(i.e. s1 and s2 are equally specific)_
- `< 0` = Sort s1 before s2 _(i.e. s1 is less specific than s2)_
- `Specificity.equals(s1, s2)`: Returns `true` if s1 and s2 have the same specificity. If not, `false` is returned.
- `Specificity.greaterThan(s1, s2)`: Returns `true` if s1 has a higher specificity than s2. If not, `false` is returned.
- `Specificity.lessThan(s1, s2)`: Returns `true` if s1 has a lower specificity than s2. If not, `false` is returned.
- Sorting:
- `Specificity.sortAsc(s1, s2, …, sN)`: Sorts the given specificities in ascending order _(low specificity to high specificity)_
- `Specificity.sortDesc(s1, s2, …, sN)`: Sorts the given specificities in descending order _(high specificity to low specificity)_
- Filtering:
- `Specificity.min(s1, s2, …, sN)`: Filters out the value with the lowest specificity
- `Specificity.max(s1, s2, …, sN)`: Filters out the value with the highest specificity
A specificity passed into any of these utility functions can be any of:
- An instance of the included `Specificity` class
- A simple Object such as `{'a': 1, 'b': 0, 'c': 2}`
## Utility Functions (Standalone)
All static methods the `Specificity` class exposes are also exported as standalone functions using [Subpath Exports](https://nodejs.org/api/packages.html#subpath-exports).
If you're only interested in including some of these functions into your project you can import them from their Subpath. As a result, your bundle size will be reduced greatly _(except for including the standalone `calculate`, as it returns an array of `Specificity` instances that relies on the whole lot)_
```js
import { calculate, calculateForAST } from '@bramus/specificity/core';
import { compare, equals, greaterThan, lessThan } from '@bramus/specificity/compare';
import { min, max } from '@bramus/specificity/filter';
import { sortAsc, sortDesc } from '@bramus/specificity/sort';
```
## Type Definitions
Although `@bramus/specificity` is written in Vanilla JavaScript, it does include [Type Definitions](https://www.typescriptlang.org/docs/handbook/2/type-declarations.html) which are exposed via its `package.json`.
## Binary/CLI
`@bramus/specificity` exposes a binary named `specificity` to calculate the specificity of a given selector list on the CLI. For each selector that it finds, it'll print out the calculated specificity as a string on a new line.
```bash
$ specificity "header:where(#top) nav li:nth-child(2n), #doormat"
(0,1,3)
(1,0,0)
```
## Benchmark
A benchmark is included, which you can invoke using `npm run benchmark`.
Sample results (tested on a MacBook Air M3):
```
Specificity.calculate(string) x 420,682 ops/sec ±0.34% (98 runs sampled)
Specificity.calculate(ast) - using SelectorList x 8,994,080 ops/sec ±0.25% (98 runs sampled)
Specificity.calculate(ast) - using Selector x 11,054,856 ops/sec ±0.39% (91 runs sampled)
Specificity.calculateForAST(ast) x 12,652,322 ops/sec ±0.35% (96 runs sampled)
```
## License
`@bramus/specificity` is released under the MIT public license. See the enclosed `LICENSE` for details.
## Acknowledgements
The idea to create this package was sparked by [the wonderful Specificity Calculator created by Kilian Valkhof / Polypane](https://polypane.app/css-specificity-calculator/), a highly educational tool that not only calculates the specificity, but also explains which parts are responsible for it.
The heavy lifting of doing the actual parsing of Selectors is done by [CSSTree](https://github.com/csstree/csstree).

14
node_modules/@bramus/specificity/bin/cli.js generated vendored Executable file
View File

@ -0,0 +1,14 @@
#!/usr/bin/env node
import Specificity from '../dist/index.js';
if (!process.argv[2]) {
console.error('❌ Missing selector argument');
process.exit(1);
}
try {
const specificities = Specificity.calculate(process.argv[2]);
console.log(specificities.map((specificity) => `${specificity}`).join('\n'));
} catch (e) {
console.error(`❌ ${e.message}`);
}

8
node_modules/@bramus/specificity/dist/index.cjs generated vendored Normal file

File diff suppressed because one or more lines are too long

7
node_modules/@bramus/specificity/dist/index.cjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

8
node_modules/@bramus/specificity/dist/index.js generated vendored Normal file

File diff suppressed because one or more lines are too long

7
node_modules/@bramus/specificity/dist/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

59
node_modules/@bramus/specificity/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,59 @@
// Types & Classes
export type SpecificityArray = [number, number, number];
export type SpecificityObject = { a: number; b: number; c: number };
export default class Specificity {
static calculate(selector: string | CSSTreeAST): Array<Specificity>;
static calculateForAST(selectorAST: CSSTreeAST): Specificity;
static compare(s1: SpecificityInstanceOrObject, s2: SpecificityInstanceOrObject): number;
static equals(s1: SpecificityInstanceOrObject, s2: SpecificityInstanceOrObject): boolean;
static lessThan(s1: SpecificityInstanceOrObject, s2: SpecificityInstanceOrObject): boolean;
static greaterThan(s1: SpecificityInstanceOrObject, s2: SpecificityInstanceOrObject): boolean;
static min(...specificities: SpecificityInstanceOrObject[]): SpecificityInstanceOrObject;
static max(...specificities: SpecificityInstanceOrObject[]): SpecificityInstanceOrObject;
static sortAsc(...specificities: SpecificityInstanceOrObject[]): SpecificityInstanceOrObject;
static sortDesc(...specificities: SpecificityInstanceOrObject[]): SpecificityInstanceOrObject;
constructor(value: SpecificityObject, selector?: any);
value: SpecificityObject;
selector: string | CSSTreeAST;
set a(arg: number);
get a(): number;
set b(arg: number);
get b(): number;
set c(arg: number);
get c(): number;
selectorString(): string;
toObject(): SpecificityObject;
toArray(): SpecificityArray;
toString(): string;
toJSON(): {
selector: string;
asObject: SpecificityObject;
asArray: SpecificityArray;
asString: string;
};
isEqualTo(otherSpecificity: SpecificityInstanceOrObject): boolean;
isGreaterThan(otherSpecificity: SpecificityInstanceOrObject): boolean;
isLessThan(otherSpecificity: SpecificityInstanceOrObject): boolean;
}
type SpecificityInstanceOrObject = Specificity | SpecificityObject;
type CSSTreeAST = Object; // @TODO: Define shape
// CORE
export function calculate(selector: string | CSSTreeAST): Array<Specificity>;
export function calculateForAST(selectorAST: CSSTreeAST): Specificity;
// UTIL: COMPARE
export function equals(s1: SpecificityInstanceOrObject, s2: SpecificityInstanceOrObject): boolean;
export function greaterThan(s1: SpecificityInstanceOrObject, s2: SpecificityInstanceOrObject): boolean;
export function lessThan(s1: SpecificityInstanceOrObject, s2: SpecificityInstanceOrObject): boolean;
export function compare(s1: SpecificityInstanceOrObject, s2: SpecificityInstanceOrObject): number;
// UTIL: FILTER
export function min(specificities: SpecificityInstanceOrObject[]): SpecificityInstanceOrObject;
export function max(specificities: SpecificityInstanceOrObject[]): SpecificityInstanceOrObject;
// UTIL: SORT
export function sortAsc(specificities: SpecificityInstanceOrObject[]): SpecificityInstanceOrObject[];
export function sortDesc(specificities: SpecificityInstanceOrObject[]): SpecificityInstanceOrObject[];

92
node_modules/@bramus/specificity/package.json generated vendored Normal file
View File

@ -0,0 +1,92 @@
{
"name": "@bramus/specificity",
"version": "2.4.3",
"description": "Calculate specificity of a CSS Selector",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"exports": {
".": {
"browser": "./dist/index.js",
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"./core": {
"import": "./src/core/index.js"
},
"./util": {
"import": "./src/util/index.js"
},
"./compare": {
"import": "./src/util/compare.js"
},
"./filter": {
"import": "./src/util/filter.js"
},
"./sort": {
"import": "./src/util/sort.js"
}
},
"unpkg": "./dist/index.js",
"jsdelivr": "./dist/index.js",
"files": [
"bin",
"src",
"dist",
"index.d.ts"
],
"types": "./index.d.ts",
"bin": {
"specificity": "./bin/cli.js"
},
"scripts": {
"build-esm": "esbuild --bundle ./src/index.js --outfile=./dist/index.js --format=esm --sourcemap --minify",
"build-cjs": "esbuild --bundle ./src/index.js --outfile=./dist/index.cjs --format=cjs --sourcemap --minify",
"lint": "prettier --check '{src,test}/**/*.{ts,tsx,js,jsx}'",
"format": "prettier --write '{src,test}/**/*.{ts,tsx,js,jsx}'",
"build": "npm run build-esm && npm run build-cjs",
"prepack": "npm run prevent-dirty-tree && npm run test",
"prepublish": "npm run build",
"pretest": "npm run build",
"test": "mocha",
"prebenchmark": "npm run build",
"benchmark": "node ./benchmark/bench.cjs",
"beta-version-patch": "npm version $(semver $npm_package_version -i prerelease --preid beta)",
"beta-version-minor": "npm version $(semver $npm_package_version -i preminor --preid beta)",
"beta-version-major": "npm version $(semver $npm_package_version -i premajor --preid beta)",
"rc-version": "npm version $(semver $npm_package_version -i prerelease --preid rc)",
"final-release": "npm version $(semver $npm_package_version -i)",
"preversion": "npm run prevent-dirty-tree && npm run test",
"prevent-dirty-tree": "exit $(git status --porcelain | wc -l)"
},
"repository": {
"type": "git",
"url": "git+https://github.com/bramus/specificity.git"
},
"keywords": [
"css",
"specificity"
],
"author": {
"name": "Bramus Van Damme",
"email": "bramus@bram.us",
"twitter": "@bramus",
"web": "https://www.bram.us/"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/bramus/specificity/issues"
},
"homepage": "https://github.com/bramus/specificity#readme",
"devDependencies": {
"benchmark": "^2.1.4",
"esbuild": "^0.28.2",
"microtime": "^3.1.1",
"mocha": "^12.0.3",
"prettier": "^3.9.9",
"semver": "^7.8.5"
},
"dependencies": {
"css-tree": "^3.2.1"
}
}

272
node_modules/@bramus/specificity/src/core/calculate.js generated vendored Normal file
View File

@ -0,0 +1,272 @@
import parse from 'css-tree/selector-parser';
import Specificity from '../index.js';
import { max } from './../util/index.js';
/** @param {import('css-tree').Selector} selectorAST */
const calculateForAST = (selectorAST) => {
// Quit while you're ahead
if (!selectorAST || selectorAST.type !== 'Selector') {
throw new TypeError(`Passed in source is not a Selector AST`);
}
// https://www.w3.org/TR/selectors-4/#specificity-rules
let a = 0; /* ID Selectors */
let b = 0; /* Class selectors, Attributes selectors, and Pseudo-classes */
let c = 0; /* Type selectors and Pseudo-elements */
selectorAST.children.forEach((child) => {
switch (child.type) {
case 'IdSelector':
a += 1;
break;
case 'AttributeSelector':
case 'ClassSelector':
b += 1;
break;
case 'PseudoClassSelector':
switch (child.name.toLowerCase()) {
// “The specificity of a :where() pseudo-class is replaced by zero.”
case 'where':
// Noop :)
break;
case '-webkit-any':
case 'any':
if (child.children?.first) {
b += 1;
}
break;
// “The specificity of an :is(), :not(), or :has() pseudo-class is replaced by the specificity of the most specific complex selector in its selector list argument.“
case '-moz-any':
case 'is':
case 'matches':
case 'not':
case 'has':
if (child.children?.first) {
// Calculate Specificity from nested SelectorList
const max1 = max(...calculate(child.children.first));
// Adjust orig specificity
a += max1.a;
b += max1.b;
c += max1.c;
}
break;
// “The specificity of an :nth-child() or :nth-last-child() selector is the specificity of the pseudo class itself (counting as one pseudo-class selector) plus the specificity of the most specific complex selector in its selector list argument”
case 'nth-child':
case 'nth-last-child':
b += 1;
if (child.children?.first?.selector) {
// Calculate Specificity from SelectorList
const max2 = max(...calculate(child.children.first.selector));
// Adjust orig specificity
a += max2.a;
b += max2.b;
c += max2.c;
}
break;
// “The specificity of :host is that of a pseudo-class. The specificity of :host() is that of a pseudo-class, plus the specificity of its argument.”
// “The specificity of :host-context() is that of a pseudo-class, plus the specificity of its argument.”
case 'host-context':
case 'host':
b += 1;
if (child.children?.first?.children) {
// Workaround to a css-tree bug in which it allows complex selectors instead of only compound selectors
// We work around it by filtering out any Combinator and successive Selectors
const childAST = { type: 'Selector', children: [] };
let foundCombinator = false;
child.children.first.children.forEach((entry) => {
if (foundCombinator) return false;
if (entry.type === 'Combinator') {
foundCombinator = true;
return false;
}
childAST.children.push(entry);
});
// Calculate Specificity from Selector
const childSpecificity = calculate(childAST)[0];
// Adjust orig specificity
a += childSpecificity.a;
b += childSpecificity.b;
c += childSpecificity.c;
}
break;
// Improper use of Pseudo-Class Selectors instead of a Pseudo-Element
// @ref https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements#index
case 'after':
case 'before':
case 'first-letter':
case 'first-line':
c += 1;
break;
default:
b += 1;
break;
}
break;
case 'PseudoElementSelector':
switch (child.name) {
// “The specificity of ::slotted() is that of a pseudo-element, plus the specificity of its argument.”
case 'slotted':
c += 1;
if (child.children?.first?.children) {
// Workaround to a css-tree bug in which it allows complex selectors instead of only compound selectors
// We work around it by filtering out any Combinator and successive Selectors
const childAST = { type: 'Selector', children: [] };
let foundCombinator = false;
child.children.first.children.forEach((entry) => {
if (foundCombinator) return false;
if (entry.type === 'Combinator') {
foundCombinator = true;
return false;
}
childAST.children.push(entry);
});
// Calculate Specificity from Selector
const childSpecificity = calculate(childAST)[0];
// Adjust orig specificity
a += childSpecificity.a;
b += childSpecificity.b;
c += childSpecificity.c;
}
break;
case 'view-transition-group':
case 'view-transition-image-pair':
case 'view-transition-old':
case 'view-transition-new':
// The specificity of a view-transition selector with a * argument is zero.
if (child.children?.first?.value === '*') {
break;
}
// The specificity of a view-transition selector with an argument is the same
// as for other pseudo - elements, and is equivalent to a type selector.
c += 1;
break;
case 'highlight':
if (child.children?.size > 0) {
// The specificity of a ::highlight() selector with a * argument is zero.
if (child.children.first?.value === '*') {
break;
}
// The specificity of a ::highlight() selector with a <custom-ident> argument
// is equivalent to a type selector.
c += 1;
}
break;
default:
c += 1;
break;
}
break;
case 'TypeSelector':
// Omit namespace
let typeSelector = child.name;
if (typeSelector.includes('|')) {
typeSelector = typeSelector.split('|')[1];
}
// “Ignore the universal selector”
if (typeSelector !== '*') {
c += 1;
}
break;
default:
// NOOP
break;
}
});
return new Specificity({ a, b, c }, selectorAST);
};
const convertToAST = (source) => {
// The passed in argument was a String.
// ~> Let's try and parse to an AST
if (typeof source === 'string' || source instanceof String) {
try {
return parse(source, {
context: 'selectorList',
});
} catch (e) {
throw new TypeError(`Could not convert passed in source '${source}' to SelectorList: ${e.message}`);
}
}
// The passed in argument was an Object.
// ~> Let's verify if it's a AST of the type Selector or SelectorList
if (source instanceof Object) {
if (source.type && ['Selector', 'SelectorList'].includes(source.type)) {
return source;
}
// Manually parsing subtree when the child is of the type Raw, most likely due to https://github.com/csstree/csstree/issues/151
if (source.type && source.type === 'Raw') {
try {
return parse(source.value, {
context: 'selectorList',
});
} catch (e) {
throw new TypeError(`Could not convert passed in source to SelectorList: ${e.message}`);
}
}
throw new TypeError(`Passed in source is an Object but no AST / AST of the type Selector or SelectorList`);
}
throw new TypeError(`Passed in source is not a String nor an Object. I don't know what to do with it.`);
};
/**
* @param {string} selector
* @returns {Specificity[]}
*/
const calculate = (selector) => {
// Quit while you're ahead
if (!selector) {
return [];
}
// Make sure we have a SelectorList AST
// If not, an exception will be thrown
const ast = convertToAST(selector);
// Selector?
if (ast.type === 'Selector') {
return [calculateForAST(selector)];
}
// SelectorList?
// ~> Calculate Specificity for each contained Selector
if (ast.type === 'SelectorList') {
const specificities = [];
ast.children.forEach((childAST) => {
const specificity = calculateForAST(childAST);
specificities.push(specificity);
});
return specificities;
}
};
export { calculate, calculateForAST };

1
node_modules/@bramus/specificity/src/core/index.js generated vendored Normal file
View File

@ -0,0 +1 @@
export { calculate, calculateForAST } from './calculate.js';

Some files were not shown because too many files have changed in this diff Show More