Compare commits
9
Commits
f4216e6868
...
7aa50eee6c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7aa50eee6c | ||
|
|
ada96b3534 | ||
|
|
10278981ba | ||
|
|
5093b50f5c | ||
|
|
65f12c931b | ||
|
|
40eee984da | ||
|
|
d373cc0daf | ||
|
|
a16a7b92c7 | ||
|
|
f990ad6767 |
@@ -1 +1,10 @@
|
||||
node_modules
|
||||
|
||||
# Reference source (legacy Next.js design in refs/): branding icons are not needed
|
||||
refs/public/icon.svg
|
||||
refs/public/icon-dark-32x32.png
|
||||
refs/public/icon-light-32x32.png
|
||||
refs/public/apple-icon.png
|
||||
refs/public/placeholder-logo.svg
|
||||
refs/public/placeholder-logo.png
|
||||
refs/public/placeholder.svg
|
||||
|
||||
+13
-3
@@ -28,10 +28,10 @@
|
||||
- **F1. Фон холста.** Реф: плоский серый `#EEF1F4`. Наш: белый + blueprint-сетка.
|
||||
Решение: совпасть с рефом (убрать сетку на демо) или оставить сетку как сигнатуру нового дизайна.
|
||||
- **F2. Бейдж типа шага** (BACKGROUND/TRANSFORM/STYLE). Реф: приглушённый серый `#6D787F`.
|
||||
Наш (`StepCard` type → `Badge accent`): синий `#1769D2`. Решение: сделать приглушённым
|
||||
(меняет `StepCard` глобально) или оставить синим.
|
||||
Решено C16: `StepCard` рендерит `type` как приглушённый моно-текст (не синий бейдж);
|
||||
индекс шага (`step-index`) — синий `#1769D2`, как в рефе.
|
||||
- **F3. Подписи превью-тайлов** (SOURCE / STEP 01 / FINAL OUTPUT). Реф: синий `#1769D2`,
|
||||
weight 400. Наш (`PreviewTile` label): серый, weight 500.
|
||||
weight 400. Решено C16: `PreviewTile` label — синий `#1769D2`.
|
||||
- **F4. Раскладка preview-stack.** Реф: одна колонка (5 строк, выше). Наш: 2 колонки (grid).
|
||||
Решение: одна колонка (как реф) или оставить 2 колонки как выбор нового дизайна.
|
||||
- **F5. Вес лейблов контролов.** Реф: 400. Наш (`MonoLabel`): 500. Мелко.
|
||||
@@ -76,6 +76,16 @@
|
||||
не меняются. Light-токены уже совпадают с рефом (`--background`, `--panel`,
|
||||
`--foreground`, `--muted`, `--line`, `--blue` равны).
|
||||
|
||||
## Состояние (C16)
|
||||
|
||||
Цветовые расхождения против `refs-html/demo.html` устранены: стек шрифтов сверен с
|
||||
рефом (`"IBM Plex Sans", sans-serif` / `"IBM Plex Mono", monospace`), бренд топбара —
|
||||
`--foreground`, индекс шага — синий, тип шага и подпись плитки — как в рефе,
|
||||
`Segmented` — 10px/32px. Аудит: токены light 10 / dark 16, элементы 47. Остаток —
|
||||
sub-pixel (10px→9px лейблы, letter-spacing) и структурные (`display`/`rect` от наших
|
||||
flex/grid раскладок против статичного мока); визуально незначимы, правим точечно при
|
||||
желании. Старые тесты (583) — без регрессий.
|
||||
|
||||
## План действий (предлагаю)
|
||||
|
||||
1. Сразу поправить B1 + B2 (чёткие баги, улучшают все страницы).
|
||||
|
||||
@@ -330,15 +330,14 @@ src/routes/preview/tools/[id]/+page.svelte
|
||||
`CATEGORIES`, `ToolCard`). Ссылки пока `#` (реальные `/preview/tools/[id]`
|
||||
подключим на C12).
|
||||
- [x] **[C11]** `/preview/demo` — зеркало воркспейса (4 шага + панель превью), статичный приёмочный стенд.
|
||||
- [ ] **[C12]** `/preview/tools/[id]` — раскладка gradient (settings-panel + preview-panel).
|
||||
- [ ] **[C13]** `/preview/tools/[id]` — раскладка background-remover (comparison-grid).
|
||||
- [ ] **[C14]** step-cards для chain в tool-page.
|
||||
- [x] **[C12]** `/preview/tools/[id]` — data-driven settings-panel + preview-panel (gradient live, остальные — плейсхолдер); `NumberField`, `entries()` для prerender, ToolCard-ссылки подключены.
|
||||
- [x] **[C13]** `/preview/tools/[id]` — comparison-grid для file-source инструментов (`Dropzone` + before/after `CheckerCanvas`, `result-meta`); охватывает background-remover и прочие.
|
||||
- [x] **[C14]** `/preview/tools/[id]` — исполняемая цепочка: `StepCard`-шаги (параметры inline) + «Add step» (chainable), живой прогон пайплайна на исходнике, превью каждого шага + итог + Download.
|
||||
|
||||
### Шаг 4. Переключатель и проверка
|
||||
|
||||
- [ ] **[C15]** Кнопка «Preview v2» + `localStorage`-флаг в старой шапке (ведёт на
|
||||
`/preview`).
|
||||
- [ ] **[C16]** Смоук §8, скриншоты против `refs-html/`, прогон старых тестов
|
||||
- [x] **[C15]** В старой шапке ссылка «Preview v2» → `/preview`, ставит `localStorage['easy-png-tools:preview-v2']='1'`.
|
||||
- [x] **[C16]** База под дизайн: рабочий переключатель тем (persist в localStorage, применяется на `<html>`; проверено — фон `#eef1f4`↔`#11171d`), `TopBar` приведён к виду `demo.html` (бренд + синий хлебный крош `/* страница */`, безрамочные иконки, язык — active = `--foreground`/`--background`), страницы `/preview/*` на всю ширину (убран `max-width`). Точечное выравнивание к рефу отложено: реф-дизайн неконсистентен.
|
||||
(доказательство отсутствия регресса). Фиксы по результатам — отдельными
|
||||
мелкими коммитами.
|
||||
|
||||
|
||||
+2
-1
@@ -7,7 +7,8 @@
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"dev": "pnpm --dir web dev",
|
||||
"build": "pnpm --dir web build",
|
||||
"format": "pnpm --dir web format"
|
||||
"format": "pnpm --dir web format",
|
||||
"html": "pnpm --dir refs build && node scripts/extract-static.mjs refs/.next/server/app refs-html"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "Ku6epXBOCTuK",
|
||||
|
||||
@@ -7,11 +7,6 @@
|
||||
@layer properties {
|
||||
@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))) {
|
||||
*,:before,:after,::backdrop {
|
||||
--tw-rotate-x:initial;
|
||||
--tw-rotate-y:initial;
|
||||
--tw-rotate-z:initial;
|
||||
--tw-skew-x:initial;
|
||||
--tw-skew-y:initial;
|
||||
--tw-border-style:solid;
|
||||
--tw-font-weight:initial;
|
||||
--tw-shadow:0 0 #0000;
|
||||
@@ -290,13 +285,7 @@ button,input:where([type=button],[type=reset],[type=submit]) {
|
||||
}
|
||||
@layer components;
|
||||
@layer utilities {
|
||||
.static {
|
||||
position:static
|
||||
}
|
||||
.inline {
|
||||
display:inline
|
||||
}
|
||||
.inline-flex {
|
||||
.inline-flex {
|
||||
display:inline-flex
|
||||
}
|
||||
.size-6 {
|
||||
@@ -330,9 +319,6 @@ button,input:where([type=button],[type=reset],[type=submit]) {
|
||||
.shrink-0 {
|
||||
flex-shrink:0
|
||||
}
|
||||
.transform {
|
||||
transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)
|
||||
}
|
||||
.items-center {
|
||||
align-items:center
|
||||
}
|
||||
@@ -630,7 +616,7 @@ button {
|
||||
--line:#33414c;
|
||||
--muted:#91a0ac;
|
||||
--blue:#54a2ff;
|
||||
background-image:linear-gradient(#1b252d 1px,#0000 1px),linear-gradient(90deg,#1b252d 1px,#0000 1px)
|
||||
background-image:linear-gradient(#1e2a3447 1px,#0000 1px),linear-gradient(90deg,#1e2a3447 1px,#0000 1px)
|
||||
}
|
||||
.topbar,.brand,.top-actions,.language,.status,.title-row,.pipeline-head,.step-heading,.step-tools,.pipeline-footer,.preview-top,.footer {
|
||||
align-items:center;
|
||||
@@ -643,6 +629,26 @@ button {
|
||||
height:64px;
|
||||
padding:0 clamp(20px,4vw,64px)
|
||||
}
|
||||
.topbar>.brand {
|
||||
color:var(--foreground);
|
||||
text-decoration:none
|
||||
}
|
||||
.top-nav {
|
||||
align-items:center;
|
||||
gap:22px;
|
||||
margin-left:auto;
|
||||
margin-right:28px;
|
||||
display:flex
|
||||
}
|
||||
.top-nav a {
|
||||
color:var(--muted);
|
||||
font:10px var(--font-mono);
|
||||
white-space:nowrap;
|
||||
text-decoration:none
|
||||
}
|
||||
.top-nav a:hover,.top-nav a.active {
|
||||
color:var(--blue)
|
||||
}
|
||||
.brand {
|
||||
font:600 14px var(--font-mono);
|
||||
gap:10px
|
||||
@@ -1103,6 +1109,9 @@ h1 {
|
||||
gap:32px
|
||||
}
|
||||
|
||||
}
|
||||
.dark-mode .app-shell {
|
||||
background-image:linear-gradient(#1e2a3447 1px,#0000 1px),linear-gradient(90deg,#1e2a3447 1px,#0000 1px)
|
||||
}
|
||||
.dark-mode .tile-canvas {
|
||||
background-color:#202a31;
|
||||
@@ -1113,7 +1122,22 @@ h1 {
|
||||
}
|
||||
@media (max-width:800px) {
|
||||
.topbar {
|
||||
padding:0 16px
|
||||
flex-wrap:wrap;
|
||||
gap:12px;
|
||||
height:auto;
|
||||
min-height:64px;
|
||||
padding:12px 16px
|
||||
}
|
||||
.top-nav {
|
||||
order:3;
|
||||
gap:12px;
|
||||
width:100%;
|
||||
margin:0;
|
||||
padding-bottom:2px;
|
||||
overflow:auto
|
||||
}
|
||||
.top-nav a {
|
||||
font-size:9px
|
||||
}
|
||||
.status {
|
||||
display:none
|
||||
@@ -1532,9 +1556,9 @@ h1 {
|
||||
}
|
||||
.catalog-page {
|
||||
width:100%;
|
||||
max-width:1680px;
|
||||
margin:0 auto;
|
||||
padding:64px clamp(24px,4vw,72px) 72px
|
||||
max-width:none;
|
||||
margin:0;
|
||||
padding:60px clamp(24px,4vw,72px) 72px
|
||||
}
|
||||
.catalog-head {
|
||||
border-bottom:1px solid var(--line);
|
||||
@@ -1803,26 +1827,6 @@ h1 {
|
||||
gap:12px 18px
|
||||
}
|
||||
|
||||
}
|
||||
@property --tw-rotate-x {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-rotate-y {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-rotate-z {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-skew-x {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-skew-y {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-border-style {
|
||||
syntax:"*";
|
||||
@@ -1984,43 +1988,57 @@ h1 {
|
||||
<!--$-->
|
||||
<!--/$-->
|
||||
</div>
|
||||
<main class="app-shell dark-mode">
|
||||
<main class="app-shell">
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<a class="brand" href="/">
|
||||
<span class="brand-mark">EP
|
||||
</span>
|
||||
<span>easy-png-tools
|
||||
</span>
|
||||
<span class="version">/ BACKGROUND REMOVER
|
||||
<span class="version">/
|
||||
<!-- -->BACKGROUND REMOVER
|
||||
</span>
|
||||
</div>
|
||||
</a>
|
||||
<nav class="top-nav" aria-label="Primary navigation">
|
||||
<a class="" href="/">Workspace
|
||||
</a>
|
||||
<a class="" href="/easy-png-tools/list-tools">Catalog
|
||||
</a>
|
||||
<a class="" href="/easy-png-tools/gradient">Gradient
|
||||
</a>
|
||||
<a class="active" href="/easy-png-tools/background-remover">Background remover
|
||||
</a>
|
||||
</nav>
|
||||
<div class="top-actions">
|
||||
<span class="status">
|
||||
<i>
|
||||
</i> AUTO PROCESSING
|
||||
</i>
|
||||
<!-- -->AUTO PROCESSING
|
||||
</span>
|
||||
<button class="icon-btn" aria-label="Toggle theme">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-sun" aria-hidden="true">
|
||||
<circle cx="12" cy="12" r="4">
|
||||
<button class="icon-btn" aria-label="Help">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-circle-question-mark" aria-hidden="true">
|
||||
<circle cx="12" cy="12" r="10">
|
||||
</circle>
|
||||
<path d="M12 2v2">
|
||||
<path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3">
|
||||
</path>
|
||||
<path d="M12 20v2">
|
||||
</path>
|
||||
<path d="m4.93 4.93 1.41 1.41">
|
||||
</path>
|
||||
<path d="m17.66 17.66 1.41 1.41">
|
||||
</path>
|
||||
<path d="M2 12h2">
|
||||
</path>
|
||||
<path d="M20 12h2">
|
||||
</path>
|
||||
<path d="m6.34 17.66-1.41 1.41">
|
||||
</path>
|
||||
<path d="m19.07 4.93-1.41 1.41">
|
||||
<path d="M12 17h.01">
|
||||
</path>
|
||||
</svg>
|
||||
</button>
|
||||
<button class="icon-btn" aria-label="Toggle theme">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-moon" aria-hidden="true">
|
||||
<path d="M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401">
|
||||
</path>
|
||||
</svg>
|
||||
</button>
|
||||
<div class="language">
|
||||
<button class="active">RU
|
||||
</button>
|
||||
<span>/
|
||||
</span>
|
||||
<button>EN
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<div class="tool-page">
|
||||
@@ -2214,5 +2232,19 @@ h1 {
|
||||
<template data-dgst="BAILOUT_TO_CLIENT_SIDE_RENDERING">
|
||||
</template>
|
||||
<!--/$-->
|
||||
</body>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
var btn = document.querySelector('button[aria-label="Toggle theme"]');
|
||||
var shell = document.querySelector('.app-shell');
|
||||
if (!btn || window.__themeToggleInjected) return;
|
||||
window.__themeToggleInjected = true;
|
||||
btn.addEventListener('click', function () {
|
||||
document.documentElement.classList.toggle('dark-mode');
|
||||
if (shell) shell.classList.toggle('dark-mode');
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
+78
-46
@@ -7,11 +7,6 @@
|
||||
@layer properties {
|
||||
@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))) {
|
||||
*,:before,:after,::backdrop {
|
||||
--tw-rotate-x:initial;
|
||||
--tw-rotate-y:initial;
|
||||
--tw-rotate-z:initial;
|
||||
--tw-skew-x:initial;
|
||||
--tw-skew-y:initial;
|
||||
--tw-border-style:solid;
|
||||
--tw-font-weight:initial;
|
||||
--tw-shadow:0 0 #0000;
|
||||
@@ -290,13 +285,7 @@ button,input:where([type=button],[type=reset],[type=submit]) {
|
||||
}
|
||||
@layer components;
|
||||
@layer utilities {
|
||||
.static {
|
||||
position:static
|
||||
}
|
||||
.inline {
|
||||
display:inline
|
||||
}
|
||||
.inline-flex {
|
||||
.inline-flex {
|
||||
display:inline-flex
|
||||
}
|
||||
.size-6 {
|
||||
@@ -330,9 +319,6 @@ button,input:where([type=button],[type=reset],[type=submit]) {
|
||||
.shrink-0 {
|
||||
flex-shrink:0
|
||||
}
|
||||
.transform {
|
||||
transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)
|
||||
}
|
||||
.items-center {
|
||||
align-items:center
|
||||
}
|
||||
@@ -630,7 +616,7 @@ button {
|
||||
--line:#33414c;
|
||||
--muted:#91a0ac;
|
||||
--blue:#54a2ff;
|
||||
background-image:linear-gradient(#1b252d 1px,#0000 1px),linear-gradient(90deg,#1b252d 1px,#0000 1px)
|
||||
background-image:linear-gradient(#1e2a3447 1px,#0000 1px),linear-gradient(90deg,#1e2a3447 1px,#0000 1px)
|
||||
}
|
||||
.topbar,.brand,.top-actions,.language,.status,.title-row,.pipeline-head,.step-heading,.step-tools,.pipeline-footer,.preview-top,.footer {
|
||||
align-items:center;
|
||||
@@ -643,6 +629,26 @@ button {
|
||||
height:64px;
|
||||
padding:0 clamp(20px,4vw,64px)
|
||||
}
|
||||
.topbar>.brand {
|
||||
color:var(--foreground);
|
||||
text-decoration:none
|
||||
}
|
||||
.top-nav {
|
||||
align-items:center;
|
||||
gap:22px;
|
||||
margin-left:auto;
|
||||
margin-right:28px;
|
||||
display:flex
|
||||
}
|
||||
.top-nav a {
|
||||
color:var(--muted);
|
||||
font:10px var(--font-mono);
|
||||
white-space:nowrap;
|
||||
text-decoration:none
|
||||
}
|
||||
.top-nav a:hover,.top-nav a.active {
|
||||
color:var(--blue)
|
||||
}
|
||||
.brand {
|
||||
font:600 14px var(--font-mono);
|
||||
gap:10px
|
||||
@@ -1103,6 +1109,9 @@ h1 {
|
||||
gap:32px
|
||||
}
|
||||
|
||||
}
|
||||
.dark-mode .app-shell {
|
||||
background-image:linear-gradient(#1e2a3447 1px,#0000 1px),linear-gradient(90deg,#1e2a3447 1px,#0000 1px)
|
||||
}
|
||||
.dark-mode .tile-canvas {
|
||||
background-color:#202a31;
|
||||
@@ -1113,7 +1122,22 @@ h1 {
|
||||
}
|
||||
@media (max-width:800px) {
|
||||
.topbar {
|
||||
padding:0 16px
|
||||
flex-wrap:wrap;
|
||||
gap:12px;
|
||||
height:auto;
|
||||
min-height:64px;
|
||||
padding:12px 16px
|
||||
}
|
||||
.top-nav {
|
||||
order:3;
|
||||
gap:12px;
|
||||
width:100%;
|
||||
margin:0;
|
||||
padding-bottom:2px;
|
||||
overflow:auto
|
||||
}
|
||||
.top-nav a {
|
||||
font-size:9px
|
||||
}
|
||||
.status {
|
||||
display:none
|
||||
@@ -1532,9 +1556,9 @@ h1 {
|
||||
}
|
||||
.catalog-page {
|
||||
width:100%;
|
||||
max-width:1680px;
|
||||
margin:0 auto;
|
||||
padding:64px clamp(24px,4vw,72px) 72px
|
||||
max-width:none;
|
||||
margin:0;
|
||||
padding:60px clamp(24px,4vw,72px) 72px
|
||||
}
|
||||
.catalog-head {
|
||||
border-bottom:1px solid var(--line);
|
||||
@@ -1803,26 +1827,6 @@ h1 {
|
||||
gap:12px 18px
|
||||
}
|
||||
|
||||
}
|
||||
@property --tw-rotate-x {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-rotate-y {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-rotate-z {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-skew-x {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-skew-y {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-border-style {
|
||||
syntax:"*";
|
||||
@@ -1986,18 +1990,30 @@ h1 {
|
||||
</div>
|
||||
<main class="app-shell">
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<a class="brand" href="/">
|
||||
<span class="brand-mark">EP
|
||||
</span>
|
||||
<span>easy-png-tools
|
||||
</span>
|
||||
<span class="version">/ DEMO
|
||||
<span class="version">/
|
||||
<!-- -->WORKSPACE
|
||||
</span>
|
||||
</div>
|
||||
</a>
|
||||
<nav class="top-nav" aria-label="Primary navigation">
|
||||
<a class="" href="/">Workspace
|
||||
</a>
|
||||
<a class="" href="/easy-png-tools/list-tools">Catalog
|
||||
</a>
|
||||
<a class="" href="/easy-png-tools/gradient">Gradient
|
||||
</a>
|
||||
<a class="" href="/easy-png-tools/background-remover">Background remover
|
||||
</a>
|
||||
</nav>
|
||||
<div class="top-actions">
|
||||
<span class="status">
|
||||
<i>
|
||||
</i> AUTO PIPELINE
|
||||
</i>
|
||||
<!-- -->AUTO PIPELINE
|
||||
</span>
|
||||
<button class="icon-btn" aria-label="Help">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-circle-question-mark" aria-hidden="true">
|
||||
@@ -2018,7 +2034,9 @@ h1 {
|
||||
<div class="language">
|
||||
<button class="active">RU
|
||||
</button>
|
||||
<button class="">EN
|
||||
<span>/
|
||||
</span>
|
||||
<button>EN
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -2572,5 +2590,19 @@ h1 {
|
||||
<template data-dgst="BAILOUT_TO_CLIENT_SIDE_RENDERING">
|
||||
</template>
|
||||
<!--/$-->
|
||||
</body>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
var btn = document.querySelector('button[aria-label="Toggle theme"]');
|
||||
var shell = document.querySelector('.app-shell');
|
||||
if (!btn || window.__themeToggleInjected) return;
|
||||
window.__themeToggleInjected = true;
|
||||
btn.addEventListener('click', function () {
|
||||
document.documentElement.classList.toggle('dark-mode');
|
||||
if (shell) shell.classList.toggle('dark-mode');
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
+98
-62
@@ -7,11 +7,6 @@
|
||||
@layer properties {
|
||||
@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))) {
|
||||
*,:before,:after,::backdrop {
|
||||
--tw-rotate-x:initial;
|
||||
--tw-rotate-y:initial;
|
||||
--tw-rotate-z:initial;
|
||||
--tw-skew-x:initial;
|
||||
--tw-skew-y:initial;
|
||||
--tw-border-style:solid;
|
||||
--tw-font-weight:initial;
|
||||
--tw-shadow:0 0 #0000;
|
||||
@@ -290,13 +285,7 @@ button,input:where([type=button],[type=reset],[type=submit]) {
|
||||
}
|
||||
@layer components;
|
||||
@layer utilities {
|
||||
.static {
|
||||
position:static
|
||||
}
|
||||
.inline {
|
||||
display:inline
|
||||
}
|
||||
.inline-flex {
|
||||
.inline-flex {
|
||||
display:inline-flex
|
||||
}
|
||||
.size-6 {
|
||||
@@ -330,9 +319,6 @@ button,input:where([type=button],[type=reset],[type=submit]) {
|
||||
.shrink-0 {
|
||||
flex-shrink:0
|
||||
}
|
||||
.transform {
|
||||
transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)
|
||||
}
|
||||
.items-center {
|
||||
align-items:center
|
||||
}
|
||||
@@ -630,7 +616,7 @@ button {
|
||||
--line:#33414c;
|
||||
--muted:#91a0ac;
|
||||
--blue:#54a2ff;
|
||||
background-image:linear-gradient(#1b252d 1px,#0000 1px),linear-gradient(90deg,#1b252d 1px,#0000 1px)
|
||||
background-image:linear-gradient(#1e2a3447 1px,#0000 1px),linear-gradient(90deg,#1e2a3447 1px,#0000 1px)
|
||||
}
|
||||
.topbar,.brand,.top-actions,.language,.status,.title-row,.pipeline-head,.step-heading,.step-tools,.pipeline-footer,.preview-top,.footer {
|
||||
align-items:center;
|
||||
@@ -643,6 +629,26 @@ button {
|
||||
height:64px;
|
||||
padding:0 clamp(20px,4vw,64px)
|
||||
}
|
||||
.topbar>.brand {
|
||||
color:var(--foreground);
|
||||
text-decoration:none
|
||||
}
|
||||
.top-nav {
|
||||
align-items:center;
|
||||
gap:22px;
|
||||
margin-left:auto;
|
||||
margin-right:28px;
|
||||
display:flex
|
||||
}
|
||||
.top-nav a {
|
||||
color:var(--muted);
|
||||
font:10px var(--font-mono);
|
||||
white-space:nowrap;
|
||||
text-decoration:none
|
||||
}
|
||||
.top-nav a:hover,.top-nav a.active {
|
||||
color:var(--blue)
|
||||
}
|
||||
.brand {
|
||||
font:600 14px var(--font-mono);
|
||||
gap:10px
|
||||
@@ -1103,6 +1109,9 @@ h1 {
|
||||
gap:32px
|
||||
}
|
||||
|
||||
}
|
||||
.dark-mode .app-shell {
|
||||
background-image:linear-gradient(#1e2a3447 1px,#0000 1px),linear-gradient(90deg,#1e2a3447 1px,#0000 1px)
|
||||
}
|
||||
.dark-mode .tile-canvas {
|
||||
background-color:#202a31;
|
||||
@@ -1113,7 +1122,22 @@ h1 {
|
||||
}
|
||||
@media (max-width:800px) {
|
||||
.topbar {
|
||||
padding:0 16px
|
||||
flex-wrap:wrap;
|
||||
gap:12px;
|
||||
height:auto;
|
||||
min-height:64px;
|
||||
padding:12px 16px
|
||||
}
|
||||
.top-nav {
|
||||
order:3;
|
||||
gap:12px;
|
||||
width:100%;
|
||||
margin:0;
|
||||
padding-bottom:2px;
|
||||
overflow:auto
|
||||
}
|
||||
.top-nav a {
|
||||
font-size:9px
|
||||
}
|
||||
.status {
|
||||
display:none
|
||||
@@ -1532,9 +1556,9 @@ h1 {
|
||||
}
|
||||
.catalog-page {
|
||||
width:100%;
|
||||
max-width:1680px;
|
||||
margin:0 auto;
|
||||
padding:64px clamp(24px,4vw,72px) 72px
|
||||
max-width:none;
|
||||
margin:0;
|
||||
padding:60px clamp(24px,4vw,72px) 72px
|
||||
}
|
||||
.catalog-head {
|
||||
border-bottom:1px solid var(--line);
|
||||
@@ -1803,26 +1827,6 @@ h1 {
|
||||
gap:12px 18px
|
||||
}
|
||||
|
||||
}
|
||||
@property --tw-rotate-x {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-rotate-y {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-rotate-z {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-skew-x {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-skew-y {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-border-style {
|
||||
syntax:"*";
|
||||
@@ -1984,39 +1988,57 @@ h1 {
|
||||
<!--$-->
|
||||
<!--/$-->
|
||||
</div>
|
||||
<main class="app-shell dark-mode">
|
||||
<main class="app-shell">
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<a class="brand" href="/">
|
||||
<span class="brand-mark">EP
|
||||
</span>
|
||||
<span>easy-png-tools
|
||||
</span>
|
||||
<span class="version">/ GRADIENT
|
||||
<span class="version">/
|
||||
<!-- -->GRADIENT
|
||||
</span>
|
||||
</div>
|
||||
</a>
|
||||
<nav class="top-nav" aria-label="Primary navigation">
|
||||
<a class="" href="/">Workspace
|
||||
</a>
|
||||
<a class="" href="/easy-png-tools/list-tools">Catalog
|
||||
</a>
|
||||
<a class="active" href="/easy-png-tools/gradient">Gradient
|
||||
</a>
|
||||
<a class="" href="/easy-png-tools/background-remover">Background remover
|
||||
</a>
|
||||
</nav>
|
||||
<div class="top-actions">
|
||||
<button class="icon-btn" aria-label="Toggle theme">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-sun" aria-hidden="true">
|
||||
<circle cx="12" cy="12" r="4">
|
||||
<span class="status">
|
||||
<i>
|
||||
</i>
|
||||
<!-- -->LIVE PREVIEW
|
||||
</span>
|
||||
<button class="icon-btn" aria-label="Help">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-circle-question-mark" aria-hidden="true">
|
||||
<circle cx="12" cy="12" r="10">
|
||||
</circle>
|
||||
<path d="M12 2v2">
|
||||
<path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3">
|
||||
</path>
|
||||
<path d="M12 20v2">
|
||||
</path>
|
||||
<path d="m4.93 4.93 1.41 1.41">
|
||||
</path>
|
||||
<path d="m17.66 17.66 1.41 1.41">
|
||||
</path>
|
||||
<path d="M2 12h2">
|
||||
</path>
|
||||
<path d="M20 12h2">
|
||||
</path>
|
||||
<path d="m6.34 17.66-1.41 1.41">
|
||||
</path>
|
||||
<path d="m19.07 4.93-1.41 1.41">
|
||||
<path d="M12 17h.01">
|
||||
</path>
|
||||
</svg>
|
||||
</button>
|
||||
<button class="icon-btn" aria-label="Toggle theme">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-moon" aria-hidden="true">
|
||||
<path d="M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401">
|
||||
</path>
|
||||
</svg>
|
||||
</button>
|
||||
<div class="language">
|
||||
<button class="active">RU
|
||||
</button>
|
||||
<span>/
|
||||
</span>
|
||||
<button>EN
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<div class="tool-page">
|
||||
@@ -2205,5 +2227,19 @@ opacity: 1;</pre>
|
||||
<template data-dgst="BAILOUT_TO_CLIENT_SIDE_RENDERING">
|
||||
</template>
|
||||
<!--/$-->
|
||||
</body>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
var btn = document.querySelector('button[aria-label="Toggle theme"]');
|
||||
var shell = document.querySelector('.app-shell');
|
||||
if (!btn || window.__themeToggleInjected) return;
|
||||
window.__themeToggleInjected = true;
|
||||
btn.addEventListener('click', function () {
|
||||
document.documentElement.classList.toggle('dark-mode');
|
||||
if (shell) shell.classList.toggle('dark-mode');
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
+78
-46
@@ -7,11 +7,6 @@
|
||||
@layer properties {
|
||||
@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))) {
|
||||
*,:before,:after,::backdrop {
|
||||
--tw-rotate-x:initial;
|
||||
--tw-rotate-y:initial;
|
||||
--tw-rotate-z:initial;
|
||||
--tw-skew-x:initial;
|
||||
--tw-skew-y:initial;
|
||||
--tw-border-style:solid;
|
||||
--tw-font-weight:initial;
|
||||
--tw-shadow:0 0 #0000;
|
||||
@@ -290,13 +285,7 @@ button,input:where([type=button],[type=reset],[type=submit]) {
|
||||
}
|
||||
@layer components;
|
||||
@layer utilities {
|
||||
.static {
|
||||
position:static
|
||||
}
|
||||
.inline {
|
||||
display:inline
|
||||
}
|
||||
.inline-flex {
|
||||
.inline-flex {
|
||||
display:inline-flex
|
||||
}
|
||||
.size-6 {
|
||||
@@ -330,9 +319,6 @@ button,input:where([type=button],[type=reset],[type=submit]) {
|
||||
.shrink-0 {
|
||||
flex-shrink:0
|
||||
}
|
||||
.transform {
|
||||
transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)
|
||||
}
|
||||
.items-center {
|
||||
align-items:center
|
||||
}
|
||||
@@ -630,7 +616,7 @@ button {
|
||||
--line:#33414c;
|
||||
--muted:#91a0ac;
|
||||
--blue:#54a2ff;
|
||||
background-image:linear-gradient(#1b252d 1px,#0000 1px),linear-gradient(90deg,#1b252d 1px,#0000 1px)
|
||||
background-image:linear-gradient(#1e2a3447 1px,#0000 1px),linear-gradient(90deg,#1e2a3447 1px,#0000 1px)
|
||||
}
|
||||
.topbar,.brand,.top-actions,.language,.status,.title-row,.pipeline-head,.step-heading,.step-tools,.pipeline-footer,.preview-top,.footer {
|
||||
align-items:center;
|
||||
@@ -643,6 +629,26 @@ button {
|
||||
height:64px;
|
||||
padding:0 clamp(20px,4vw,64px)
|
||||
}
|
||||
.topbar>.brand {
|
||||
color:var(--foreground);
|
||||
text-decoration:none
|
||||
}
|
||||
.top-nav {
|
||||
align-items:center;
|
||||
gap:22px;
|
||||
margin-left:auto;
|
||||
margin-right:28px;
|
||||
display:flex
|
||||
}
|
||||
.top-nav a {
|
||||
color:var(--muted);
|
||||
font:10px var(--font-mono);
|
||||
white-space:nowrap;
|
||||
text-decoration:none
|
||||
}
|
||||
.top-nav a:hover,.top-nav a.active {
|
||||
color:var(--blue)
|
||||
}
|
||||
.brand {
|
||||
font:600 14px var(--font-mono);
|
||||
gap:10px
|
||||
@@ -1103,6 +1109,9 @@ h1 {
|
||||
gap:32px
|
||||
}
|
||||
|
||||
}
|
||||
.dark-mode .app-shell {
|
||||
background-image:linear-gradient(#1e2a3447 1px,#0000 1px),linear-gradient(90deg,#1e2a3447 1px,#0000 1px)
|
||||
}
|
||||
.dark-mode .tile-canvas {
|
||||
background-color:#202a31;
|
||||
@@ -1113,7 +1122,22 @@ h1 {
|
||||
}
|
||||
@media (max-width:800px) {
|
||||
.topbar {
|
||||
padding:0 16px
|
||||
flex-wrap:wrap;
|
||||
gap:12px;
|
||||
height:auto;
|
||||
min-height:64px;
|
||||
padding:12px 16px
|
||||
}
|
||||
.top-nav {
|
||||
order:3;
|
||||
gap:12px;
|
||||
width:100%;
|
||||
margin:0;
|
||||
padding-bottom:2px;
|
||||
overflow:auto
|
||||
}
|
||||
.top-nav a {
|
||||
font-size:9px
|
||||
}
|
||||
.status {
|
||||
display:none
|
||||
@@ -1532,9 +1556,9 @@ h1 {
|
||||
}
|
||||
.catalog-page {
|
||||
width:100%;
|
||||
max-width:1680px;
|
||||
margin:0 auto;
|
||||
padding:64px clamp(24px,4vw,72px) 72px
|
||||
max-width:none;
|
||||
margin:0;
|
||||
padding:60px clamp(24px,4vw,72px) 72px
|
||||
}
|
||||
.catalog-head {
|
||||
border-bottom:1px solid var(--line);
|
||||
@@ -1803,26 +1827,6 @@ h1 {
|
||||
gap:12px 18px
|
||||
}
|
||||
|
||||
}
|
||||
@property --tw-rotate-x {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-rotate-y {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-rotate-z {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-skew-x {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-skew-y {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-border-style {
|
||||
syntax:"*";
|
||||
@@ -1986,18 +1990,30 @@ h1 {
|
||||
</div>
|
||||
<main class="app-shell">
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<a class="brand" href="/">
|
||||
<span class="brand-mark">EP
|
||||
</span>
|
||||
<span>easy-png-tools
|
||||
</span>
|
||||
<span class="version">/ DEMO
|
||||
<span class="version">/
|
||||
<!-- -->WORKSPACE
|
||||
</span>
|
||||
</div>
|
||||
</a>
|
||||
<nav class="top-nav" aria-label="Primary navigation">
|
||||
<a class="active" href="/">Workspace
|
||||
</a>
|
||||
<a class="" href="/easy-png-tools/list-tools">Catalog
|
||||
</a>
|
||||
<a class="" href="/easy-png-tools/gradient">Gradient
|
||||
</a>
|
||||
<a class="" href="/easy-png-tools/background-remover">Background remover
|
||||
</a>
|
||||
</nav>
|
||||
<div class="top-actions">
|
||||
<span class="status">
|
||||
<i>
|
||||
</i> AUTO PIPELINE
|
||||
</i>
|
||||
<!-- -->AUTO PIPELINE
|
||||
</span>
|
||||
<button class="icon-btn" aria-label="Help">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-circle-question-mark" aria-hidden="true">
|
||||
@@ -2018,7 +2034,9 @@ h1 {
|
||||
<div class="language">
|
||||
<button class="active">RU
|
||||
</button>
|
||||
<button class="">EN
|
||||
<span>/
|
||||
</span>
|
||||
<button>EN
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -2572,5 +2590,19 @@ h1 {
|
||||
<template data-dgst="BAILOUT_TO_CLIENT_SIDE_RENDERING">
|
||||
</template>
|
||||
<!--/$-->
|
||||
</body>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
var btn = document.querySelector('button[aria-label="Toggle theme"]');
|
||||
var shell = document.querySelector('.app-shell');
|
||||
if (!btn || window.__themeToggleInjected) return;
|
||||
window.__themeToggleInjected = true;
|
||||
btn.addEventListener('click', function () {
|
||||
document.documentElement.classList.toggle('dark-mode');
|
||||
if (shell) shell.classList.toggle('dark-mode');
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
+108
-48
@@ -7,11 +7,6 @@
|
||||
@layer properties {
|
||||
@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))) {
|
||||
*,:before,:after,::backdrop {
|
||||
--tw-rotate-x:initial;
|
||||
--tw-rotate-y:initial;
|
||||
--tw-rotate-z:initial;
|
||||
--tw-skew-x:initial;
|
||||
--tw-skew-y:initial;
|
||||
--tw-border-style:solid;
|
||||
--tw-font-weight:initial;
|
||||
--tw-shadow:0 0 #0000;
|
||||
@@ -290,13 +285,7 @@ button,input:where([type=button],[type=reset],[type=submit]) {
|
||||
}
|
||||
@layer components;
|
||||
@layer utilities {
|
||||
.static {
|
||||
position:static
|
||||
}
|
||||
.inline {
|
||||
display:inline
|
||||
}
|
||||
.inline-flex {
|
||||
.inline-flex {
|
||||
display:inline-flex
|
||||
}
|
||||
.size-6 {
|
||||
@@ -330,9 +319,6 @@ button,input:where([type=button],[type=reset],[type=submit]) {
|
||||
.shrink-0 {
|
||||
flex-shrink:0
|
||||
}
|
||||
.transform {
|
||||
transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)
|
||||
}
|
||||
.items-center {
|
||||
align-items:center
|
||||
}
|
||||
@@ -630,7 +616,7 @@ button {
|
||||
--line:#33414c;
|
||||
--muted:#91a0ac;
|
||||
--blue:#54a2ff;
|
||||
background-image:linear-gradient(#1b252d 1px,#0000 1px),linear-gradient(90deg,#1b252d 1px,#0000 1px)
|
||||
background-image:linear-gradient(#1e2a3447 1px,#0000 1px),linear-gradient(90deg,#1e2a3447 1px,#0000 1px)
|
||||
}
|
||||
.topbar,.brand,.top-actions,.language,.status,.title-row,.pipeline-head,.step-heading,.step-tools,.pipeline-footer,.preview-top,.footer {
|
||||
align-items:center;
|
||||
@@ -643,6 +629,26 @@ button {
|
||||
height:64px;
|
||||
padding:0 clamp(20px,4vw,64px)
|
||||
}
|
||||
.topbar>.brand {
|
||||
color:var(--foreground);
|
||||
text-decoration:none
|
||||
}
|
||||
.top-nav {
|
||||
align-items:center;
|
||||
gap:22px;
|
||||
margin-left:auto;
|
||||
margin-right:28px;
|
||||
display:flex
|
||||
}
|
||||
.top-nav a {
|
||||
color:var(--muted);
|
||||
font:10px var(--font-mono);
|
||||
white-space:nowrap;
|
||||
text-decoration:none
|
||||
}
|
||||
.top-nav a:hover,.top-nav a.active {
|
||||
color:var(--blue)
|
||||
}
|
||||
.brand {
|
||||
font:600 14px var(--font-mono);
|
||||
gap:10px
|
||||
@@ -1103,6 +1109,9 @@ h1 {
|
||||
gap:32px
|
||||
}
|
||||
|
||||
}
|
||||
.dark-mode .app-shell {
|
||||
background-image:linear-gradient(#1e2a3447 1px,#0000 1px),linear-gradient(90deg,#1e2a3447 1px,#0000 1px)
|
||||
}
|
||||
.dark-mode .tile-canvas {
|
||||
background-color:#202a31;
|
||||
@@ -1113,7 +1122,22 @@ h1 {
|
||||
}
|
||||
@media (max-width:800px) {
|
||||
.topbar {
|
||||
padding:0 16px
|
||||
flex-wrap:wrap;
|
||||
gap:12px;
|
||||
height:auto;
|
||||
min-height:64px;
|
||||
padding:12px 16px
|
||||
}
|
||||
.top-nav {
|
||||
order:3;
|
||||
gap:12px;
|
||||
width:100%;
|
||||
margin:0;
|
||||
padding-bottom:2px;
|
||||
overflow:auto
|
||||
}
|
||||
.top-nav a {
|
||||
font-size:9px
|
||||
}
|
||||
.status {
|
||||
display:none
|
||||
@@ -1532,9 +1556,9 @@ h1 {
|
||||
}
|
||||
.catalog-page {
|
||||
width:100%;
|
||||
max-width:1680px;
|
||||
margin:0 auto;
|
||||
padding:64px clamp(24px,4vw,72px) 72px
|
||||
max-width:none;
|
||||
margin:0;
|
||||
padding:60px clamp(24px,4vw,72px) 72px
|
||||
}
|
||||
.catalog-head {
|
||||
border-bottom:1px solid var(--line);
|
||||
@@ -1803,26 +1827,6 @@ h1 {
|
||||
gap:12px 18px
|
||||
}
|
||||
|
||||
}
|
||||
@property --tw-rotate-x {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-rotate-y {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-rotate-z {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-skew-x {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-skew-y {
|
||||
syntax:"*";
|
||||
inherits:false
|
||||
}
|
||||
@property --tw-border-style {
|
||||
syntax:"*";
|
||||
@@ -1984,19 +1988,60 @@ h1 {
|
||||
<!--$-->
|
||||
<!--/$-->
|
||||
</div>
|
||||
<main class="catalog-page">
|
||||
<header class="catalog-nav">
|
||||
<a class="catalog-brand" href="/">easy-png-tools
|
||||
<main class="app-shell">
|
||||
<header class="topbar">
|
||||
<a class="brand" href="/">
|
||||
<span class="brand-mark">EP
|
||||
</span>
|
||||
<span>easy-png-tools
|
||||
</span>
|
||||
<span class="version">/
|
||||
<!-- -->CATALOG
|
||||
</span>
|
||||
</a>
|
||||
<nav>
|
||||
<a href="/">Workspace
|
||||
<nav class="top-nav" aria-label="Primary navigation">
|
||||
<a class="" href="/">Workspace
|
||||
</a>
|
||||
<a class="current" href="/easy-png-tools/list-tools">Catalog
|
||||
<a class="active" href="/easy-png-tools/list-tools">Catalog
|
||||
</a>
|
||||
<a class="" href="/easy-png-tools/gradient">Gradient
|
||||
</a>
|
||||
<a class="" href="/easy-png-tools/background-remover">Background remover
|
||||
</a>
|
||||
</nav>
|
||||
<span class="catalog-nav-status">LOCAL MODE / READY
|
||||
<div class="top-actions">
|
||||
<span class="status">
|
||||
<i>
|
||||
</i>
|
||||
<!-- -->LOCAL MODE / READY
|
||||
</span>
|
||||
<button class="icon-btn" aria-label="Help">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-circle-question-mark" aria-hidden="true">
|
||||
<circle cx="12" cy="12" r="10">
|
||||
</circle>
|
||||
<path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3">
|
||||
</path>
|
||||
<path d="M12 17h.01">
|
||||
</path>
|
||||
</svg>
|
||||
</button>
|
||||
<button class="icon-btn" aria-label="Toggle theme">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-moon" aria-hidden="true">
|
||||
<path d="M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401">
|
||||
</path>
|
||||
</svg>
|
||||
</button>
|
||||
<div class="language">
|
||||
<button class="active">RU
|
||||
</button>
|
||||
<span>/
|
||||
</span>
|
||||
<button>EN
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<div class="catalog-page">
|
||||
<div class="catalog-head">
|
||||
<div>
|
||||
<div class="eyebrow">EASY-PNG-TOOLS / CATALOG
|
||||
@@ -2901,6 +2946,7 @@ h1 {
|
||||
<span>•
|
||||
</span> YOUR FILES NEVER LEAVE THIS DEVICE
|
||||
</footer>
|
||||
</div>
|
||||
</main>
|
||||
<!--$-->
|
||||
<!--/$-->
|
||||
@@ -2908,5 +2954,19 @@ h1 {
|
||||
<template data-dgst="BAILOUT_TO_CLIENT_SIDE_RENDERING">
|
||||
</template>
|
||||
<!--/$-->
|
||||
</body>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
var btn = document.querySelector('button[aria-label="Toggle theme"]');
|
||||
var shell = document.querySelector('.app-shell');
|
||||
if (!btn || window.__themeToggleInjected) return;
|
||||
window.__themeToggleInjected = true;
|
||||
btn.addEventListener('click', function () {
|
||||
document.documentElement.classList.toggle('dark-mode');
|
||||
if (shell) shell.classList.toggle('dark-mode');
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,20 +1,20 @@
|
||||
'use client'
|
||||
|
||||
import TopBar from '@/components/top-bar'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Download, Moon, RotateCcw, Sun, Upload, Check } from 'lucide-react'
|
||||
import { Download, RotateCcw, Upload, Check } from 'lucide-react'
|
||||
|
||||
export default function BackgroundRemoverPage() {
|
||||
const [color, setColor] = useState('#E8EEF2')
|
||||
const [similarity, setSimilarity] = useState(72)
|
||||
const [outerOnly, setOuterOnly] = useState(true)
|
||||
const [showMask, setShowMask] = useState(false)
|
||||
const [dark, setDark] = useState(true)
|
||||
const [downloaded, setDownloaded] = useState(false)
|
||||
const previewBackground = showMask ? 'repeating-conic-gradient(#7b8791 0 25%, #cbd3da 0 50%) 50% / 28px 28px' : 'repeating-conic-gradient(#d7dce0 0 25%, #f3f5f6 0 50%) 50% / 28px 28px'
|
||||
const subjectStyle = useMemo(() => ({ background: showMask ? '#596773' : 'linear-gradient(145deg,#1769d2 0 38%,#00a8c7 38% 66%,#bd7411 66%)', opacity: showMask ? .88 : 1, clipPath: `polygon(23% 11%, 73% 8%, 89% 30%, 79% 81%, 52% 93%, 17% 78%, 8% 39%)` }), [showMask])
|
||||
const reset = () => { setColor('#E8EEF2'); setSimilarity(72); setOuterOnly(true); setShowMask(false) }
|
||||
return <main className={`app-shell ${dark ? 'dark-mode' : ''}`}>
|
||||
<header className="topbar"><div className="brand"><span className="brand-mark">EP</span><span>easy-png-tools</span><span className="version">/ BACKGROUND REMOVER</span></div><div className="top-actions"><span className="status"><i /> AUTO PROCESSING</span><button className="icon-btn" aria-label="Toggle theme" onClick={() => setDark(!dark)}>{dark ? <Sun size={17} /> : <Moon size={17} />}</button></div></header>
|
||||
return <main className="app-shell">
|
||||
<TopBar section="BACKGROUND REMOVER" status="AUTO PROCESSING" />
|
||||
<div className="tool-page"><div className="eyebrow">PNG PROCESSING <span>/</span> SINGLE TOOL</div><div className="tool-title"><div><h1>Remove background.</h1><p className="lede">Select a background color and tune the edge detection. Changes are processed automatically in your browser.</p></div><span className="tool-status"><i /> LIVE PREVIEW</span></div>
|
||||
<div className="remover-layout"><section className="settings-panel"><div className="panel-heading"><div><span className="label">REMOVER SETTINGS</span><strong>Configure detection</strong></div><span className="step-type">TOOL 02</span></div>
|
||||
<div className="setting-group"><label>BACKGROUND COLOR</label><div className="color-field"><span className="swatch" style={{ background: color }} /><input value={color} onChange={e => setColor(e.target.value)} /><input className="native-color" type="color" value={color} onChange={e => setColor(e.target.value)} aria-label="Choose background color" /></div><div className="color-reference"><span style={{ background: color }} /> sampled from image background</div></div>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
'use client'
|
||||
|
||||
import TopBar from '@/components/top-bar'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Check, ChevronDown, Copy, Download, Moon, RotateCcw, Sun } from 'lucide-react'
|
||||
import { Check, ChevronDown, Copy, Download, RotateCcw } from 'lucide-react'
|
||||
|
||||
const directions = ['0° →', '45° ↗', '90° ↑', '135° ↖', '180° ←', '225° ↙', '270° ↓', '315° ↘']
|
||||
|
||||
@@ -11,14 +12,13 @@ export default function GradientPage() {
|
||||
const [direction, setDirection] = useState(135)
|
||||
const [opacity, setOpacity] = useState(100)
|
||||
const [type, setType] = useState<'linear' | 'radial'>('linear')
|
||||
const [dark, setDark] = useState(true)
|
||||
const [copied, setCopied] = useState(false)
|
||||
const gradient = useMemo(() => type === 'linear' ? `linear-gradient(${direction}deg, ${start} 0%, ${end} 100%)` : `radial-gradient(circle, ${start} 0%, ${end} 100%)`, [direction, end, start, type])
|
||||
const css = `background: ${gradient};\nopacity: ${opacity / 100};`
|
||||
const reset = () => { setStart('#1769D2'); setEnd('#00A8C7'); setDirection(135); setOpacity(100); setType('linear') }
|
||||
const copyCss = async () => { await navigator.clipboard?.writeText(css); setCopied(true); setTimeout(() => setCopied(false), 1400) }
|
||||
return <main className={`app-shell ${dark ? 'dark-mode' : ''}`}>
|
||||
<header className="topbar"><div className="brand"><span className="brand-mark">EP</span><span>easy-png-tools</span><span className="version">/ GRADIENT</span></div><div className="top-actions"><button className="icon-btn" aria-label="Toggle theme" onClick={() => setDark(!dark)}>{dark ? <Sun size={17} /> : <Moon size={17} />}</button></div></header>
|
||||
return <main className="app-shell">
|
||||
<TopBar section="GRADIENT" status="LIVE PREVIEW" />
|
||||
<div className="tool-page"><div className="eyebrow">PNG PROCESSING <span>/</span> SINGLE TOOL</div><div className="tool-title"><div><h1>Gradient background.</h1><p className="lede">Create a clean, export-ready gradient with precise control over color, direction and transparency.</p></div><span className="tool-status"><i /> LIVE PREVIEW</span></div>
|
||||
<div className="gradient-layout"><section className="settings-panel"><div className="panel-heading"><div><span className="label">GRADIENT SETTINGS</span><strong>Configure output</strong></div><span className="step-type">TOOL 01</span></div>
|
||||
<div className="setting-group"><label>GRADIENT TYPE</label><div className="segmented wide"><button className={type === 'linear' ? 'selected' : ''} onClick={() => setType('linear')}>Linear</button><button className={type === 'radial' ? 'selected' : ''} onClick={() => setType('radial')}>Radial</button></div></div>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import TopBar from '@/components/top-bar'
|
||||
import Link from "next/link"
|
||||
import { useMemo, useState } from "react"
|
||||
import { ArrowUpRight, FileImage, Filter, Search, Sparkles } from "lucide-react"
|
||||
@@ -17,11 +18,11 @@ export default function ListToolsPage() {
|
||||
const [query, setQuery] = useState("")
|
||||
const [active, setActive] = useState("ALL")
|
||||
const filtered = useMemo(() => groups.map(group => ({ ...group, tools: group.tools.filter(([name, description]) => (active === "ALL" || active === group.name) && `${name} ${description}`.toLowerCase().includes(query.toLowerCase())) })).filter(group => group.tools.length), [query, active])
|
||||
return <main className="catalog-page"><header className="catalog-nav"><Link href="/" className="catalog-brand">easy-png-tools</Link><nav><Link href="/">Workspace</Link><Link className="current" href="/easy-png-tools/list-tools">Catalog</Link></nav><span className="catalog-nav-status">LOCAL MODE / READY</span></header>
|
||||
return <main className="app-shell"><TopBar section="CATALOG" status="LOCAL MODE / READY" /><div className="catalog-page">
|
||||
<div className="catalog-head"><div><div className="eyebrow">EASY-PNG-TOOLS / CATALOG</div><h1>Tool catalog</h1><p>Focused utilities for working with PNG. Inspect, transform, and export — locally in your browser.</p></div><div className="catalog-total"><b>32</b><span>TOOLS<br />AVAILABLE</span></div></div>
|
||||
<div className="catalog-toolbar"><label className="catalog-search"><Search size={16} /><input aria-label="Search tools" placeholder="Search tools..." value={query} onChange={e => setQuery(e.target.value)} /></label><div className="catalog-filters"><Filter size={15} />{["ALL", ...groups.map(g => g.name)].map(name => <button key={name} className={active === name ? "active" : ""} onClick={() => setActive(name)}>{name}</button>)}</div></div>
|
||||
<div className="catalog-groups">{filtered.map(group => <section className="catalog-group" key={group.name}><div className="group-title"><span>{group.name}</span><i>{String(group.tools.length).padStart(2, "0")} TOOLS</i></div><div className="tool-cards">{group.tools.map(([name, description, href], index) => <Link className="tool-card" href={href || "#"} key={name} onClick={e => { if (!href) e.preventDefault() }}><span className="tool-icon"><FileImage size={19} /></span><span className="tool-copy"><strong>{name}</strong><span>{description}</span></span><span className="tool-index">{String(index + 1).padStart(2, "0")}</span><ArrowUpRight size={16} className="tool-arrow" /></Link>)}</div></section>)}</div>
|
||||
{!filtered.length && <div className="catalog-empty"><Sparkles size={18} /> No tools match your search.</div>}
|
||||
<footer className="catalog-footer">ALL OPERATIONS RUN LOCALLY <span>•</span> YOUR FILES NEVER LEAVE THIS DEVICE</footer>
|
||||
</main>
|
||||
</div></main>
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
+4
-4
@@ -1,7 +1,8 @@
|
||||
'use client'
|
||||
|
||||
import TopBar from '@/components/top-bar'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { ArrowDownToLine, Check, ChevronDown, CircleHelp, Download, GripVertical, Link2, Moon, MoreHorizontal, Plus, RotateCcw, Settings2, SlidersHorizontal, Sun, Upload, X } from 'lucide-react'
|
||||
import { ArrowDownToLine, Check, ChevronDown, Download, GripVertical, Link2, MoreHorizontal, Plus, RotateCcw, Settings2, SlidersHorizontal, Upload, X } from 'lucide-react'
|
||||
|
||||
const initialSteps = [
|
||||
{ id: 1, title: 'Gradient background', type: 'BACKGROUND' },
|
||||
@@ -20,14 +21,13 @@ export default function Page() {
|
||||
const [radius, setRadius] = useState(18)
|
||||
const [outline, setOutline] = useState(2)
|
||||
const [language, setLanguage] = useState('RU')
|
||||
const [dark, setDark] = useState(false)
|
||||
const [showIntermediate, setShowIntermediate] = useState(true)
|
||||
const [gradient, setGradient] = useState('#DCEBFF')
|
||||
const gradientStyle = useMemo(() => ({ background: `linear-gradient(${angle}deg, ${gradient}, #8BC8F5)` }), [angle, gradient])
|
||||
const finalStyle = { ...gradientStyle, borderRadius: radius, boxShadow: `0 0 0 ${outline}px #16202B` }
|
||||
|
||||
return <main className={dark ? 'app-shell dark-mode' : 'app-shell'}>
|
||||
<header className="topbar"><div className="brand"><span className="brand-mark">EP</span><span>easy-png-tools</span><span className="version">/ DEMO</span></div><div className="top-actions"><span className="status"><i /> AUTO PIPELINE</span><button className="icon-btn" aria-label="Help"><CircleHelp size={17} /></button><button className="icon-btn" aria-label="Toggle theme" onClick={() => setDark(!dark)}>{dark ? <Sun size={17} /> : <Moon size={17} />}</button><div className="language"><button className={language === 'RU' ? 'active' : ''} onClick={() => setLanguage('RU')}>RU</button><button className={language === 'EN' ? 'active' : ''} onClick={() => setLanguage('EN')}>EN</button></div></div></header>
|
||||
return <main className="app-shell">
|
||||
<TopBar section="WORKSPACE" status="AUTO PIPELINE" />
|
||||
<div className="page-grid">
|
||||
<section className="workspace"><div className="eyebrow">PNG PROCESSING <span>/</span> WORKSPACE</div><div className="title-row"><div><h1>Build your image pipeline.</h1><p className="lede">Chain simple tools together. Every change is processed automatically and previewed at each stage.</p></div><div className="file-chip"><Upload size={15} /><span>source.png</span><b>1.8 MB</b></div></div>
|
||||
<div className="pipeline-head"><div><span className="label">PROCESSING PIPELINE</span><strong>{steps.length} active steps <em>• LIVE</em></strong></div><button className="add-btn" onClick={() => setSteps([...steps, { id: Date.now(), title: 'New adjustment', type: 'STYLE' }])}><Plus size={15} /> Add tool</button></div>
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"use client"
|
||||
|
||||
import Link from "next/link"
|
||||
import { CircleHelp, Moon, Sun } from "lucide-react"
|
||||
import { usePathname } from "next/navigation"
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
const links = [
|
||||
["Workspace", "/"],
|
||||
["Catalog", "/easy-png-tools/list-tools"],
|
||||
["Gradient", "/easy-png-tools/gradient"],
|
||||
["Background remover", "/easy-png-tools/background-remover"],
|
||||
] as const
|
||||
|
||||
export function TopBar({ section = "WORKSPACE", status = "LOCAL MODE / READY" }: { section?: string; status?: string }) {
|
||||
const pathname = usePathname()
|
||||
const [dark, setDark] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const stored = window.localStorage.getItem("ep-theme")
|
||||
const isDark = stored === "dark"
|
||||
setDark(isDark)
|
||||
document.documentElement.classList.toggle("dark-mode", isDark)
|
||||
}, [])
|
||||
|
||||
const toggleTheme = () => {
|
||||
const next = !dark
|
||||
setDark(next)
|
||||
document.documentElement.classList.toggle("dark-mode", next)
|
||||
window.localStorage.setItem("ep-theme", next ? "dark" : "light")
|
||||
}
|
||||
|
||||
return <header className="topbar"><Link href="/" className="brand"><span className="brand-mark">EP</span><span>easy-png-tools</span><span className="version">/ {section}</span></Link><nav className="top-nav" aria-label="Primary navigation">{links.map(([label, href]) => <Link key={href} className={pathname === href ? "active" : ""} href={href}>{label}</Link>)}</nav><div className="top-actions"><span className="status"><i /> {status}</span><button className="icon-btn" aria-label="Help"><CircleHelp size={17} /></button><button className="icon-btn" aria-label="Toggle theme" onClick={toggleTheme}>{dark ? <Sun size={17} /> : <Moon size={17} />}</button><div className="language"><button className="active">RU</button><span>/</span><button>EN</button></div></div></header>
|
||||
}
|
||||
|
||||
export default TopBar
|
||||
@@ -5,7 +5,6 @@
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"html": "node extract-static.mjs .next\\server\\app ..\\refs-html",
|
||||
"start": "next start"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
Generated
+1
-4
@@ -4,9 +4,6 @@ settings:
|
||||
autoInstallPeers: true
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
overrides:
|
||||
hono: 4.12.25
|
||||
|
||||
importers:
|
||||
|
||||
.:
|
||||
@@ -268,7 +265,7 @@ packages:
|
||||
resolution: {integrity: sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==}
|
||||
engines: {node: '>=18.14.1'}
|
||||
peerDependencies:
|
||||
hono: 4.12.25
|
||||
hono: ^4
|
||||
|
||||
'@img/colour@1.1.0':
|
||||
resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.0 KiB |
@@ -7,6 +7,31 @@ import { join, dirname, basename } from 'node:path';
|
||||
const root = process.argv[2];
|
||||
const dest = process.argv[3];
|
||||
|
||||
// --- inject a minimal theme toggle (extraction strips all <script> tags, so the
|
||||
// ref pages would otherwise have no working dark-mode switch) ---
|
||||
const THEME_TOGGLE = `
|
||||
<script>
|
||||
(function () {
|
||||
var btn = document.querySelector('button[aria-label="Toggle theme"]');
|
||||
var shell = document.querySelector('.app-shell');
|
||||
if (!btn || window.__themeToggleInjected) return;
|
||||
window.__themeToggleInjected = true;
|
||||
btn.addEventListener('click', function () {
|
||||
document.documentElement.classList.toggle('dark-mode');
|
||||
if (shell) shell.classList.toggle('dark-mode');
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
`;
|
||||
|
||||
function injectThemeToggle(html) {
|
||||
if (html.includes('__themeToggleInjected')) return html;
|
||||
const tag = '</body>';
|
||||
if (html.includes(tag)) return html.replace(tag, THEME_TOGGLE + '\n' + tag);
|
||||
if (html.includes('</html>')) return html.replace('</html>', THEME_TOGGLE + '\n</html>');
|
||||
return html + '\n' + THEME_TOGGLE;
|
||||
}
|
||||
|
||||
// --- CSS: find the compiled chunk and pretty-print it ---
|
||||
const cssChunks = join(root, '..', '..', 'static', 'chunks');
|
||||
const cssFile = readdirSync(cssChunks)
|
||||
@@ -110,6 +135,7 @@ for (const [src, out] of pages) {
|
||||
);
|
||||
|
||||
html = fmtHtml(html);
|
||||
html = injectThemeToggle(html);
|
||||
|
||||
const file = join(dest, out);
|
||||
mkdirSync(dirname(file), { recursive: true });
|
||||
@@ -6,3 +6,4 @@ pnpm-lock.yaml
|
||||
static
|
||||
*.log
|
||||
.DS_Store
|
||||
audit
|
||||
|
||||
+6
-3
@@ -1,6 +1,7 @@
|
||||
# sv
|
||||
|
||||
Everything you need to build a Svelte project, powered by [`sv`](https://github.com/sveltejs/cli).
|
||||
Everything you need to build a Svelte project, powered by
|
||||
[`sv`](https://github.com/sveltejs/cli).
|
||||
|
||||
## Creating a project
|
||||
|
||||
@@ -20,7 +21,8 @@ pnpm dlx sv@0.17.0 create --template minimal --types ts --install pnpm web
|
||||
|
||||
## Developing
|
||||
|
||||
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
|
||||
Once you've created a project and installed dependencies with `npm install` (or
|
||||
`pnpm install` or `yarn`), start a development server:
|
||||
|
||||
```sh
|
||||
npm run dev
|
||||
@@ -39,4 +41,5 @@ npm run build
|
||||
|
||||
You can preview the production build with `npm run preview`.
|
||||
|
||||
> To deploy your app, you may need to install an [adapter](https://svelte.dev/docs/kit/adapters) for your target environment.
|
||||
> To deploy your app, you may need to install an
|
||||
> [adapter](https://svelte.dev/docs/kit/adapters) for your target environment.
|
||||
|
||||
+112
-487
File diff suppressed because it is too large
Load Diff
+109
-202
@@ -2,13 +2,13 @@
|
||||
|
||||
vs C:\+XBOCTuK\+life_projects\easy-png-tools\refs-html\demo.html
|
||||
|
||||
_2026-08-27T18:45:14.461Z_
|
||||
_2026-08-28T07:02:47.972Z_
|
||||
|
||||
## Сводка
|
||||
|
||||
- Токены light: **12** расх.
|
||||
- Токены dark: **18** расх.
|
||||
- Элементы (стиль/геометрия): **48** расх.
|
||||
- Токены light: **10** расх.
|
||||
- Токены dark: **16** расх.
|
||||
- Элементы (стиль/геометрия): **47** расх.
|
||||
- Только у нас: 14, только в рефе: 7
|
||||
|
||||
## Токены — Light
|
||||
@@ -17,8 +17,6 @@ _2026-08-27T18:45:14.461Z_
|
||||
|---|---|---|
|
||||
| `--danger` | #e5484d | — |
|
||||
| `--success` | #25a96a | — |
|
||||
| `--font-sans` | "IBM Plex Sans", system-ui, -apple-system, sans-serif | "IBM Plex Sans", sans-serif |
|
||||
| `--font-mono` | "IBM Plex Mono", ui-monospace, "SFMono-Regular", monospace | "IBM Plex Mono", monospace |
|
||||
| `--text-sm--line-height` | — | calc(1.25 / .875) |
|
||||
| `--text-xs--line-height` | — | calc(1 / .75) |
|
||||
| `--font-weight-medium` | — | 500 |
|
||||
@@ -40,8 +38,6 @@ _2026-08-27T18:45:14.461Z_
|
||||
| `--foreground` | #e8eef2 | #17212b |
|
||||
| `--success` | #25a96a | — |
|
||||
| `--line` | #33414c | #cbd3da |
|
||||
| `--font-sans` | "IBM Plex Sans", system-ui, -apple-system, sans-serif | "IBM Plex Sans", sans-serif |
|
||||
| `--font-mono` | "IBM Plex Mono", ui-monospace, "SFMono-Regular", monospace | "IBM Plex Mono", monospace |
|
||||
| `--text-sm--line-height` | — | calc(1.25 / .875) |
|
||||
| `--text-xs--line-height` | — | calc(1 / .75) |
|
||||
| `--font-weight-medium` | — | 500 |
|
||||
@@ -51,103 +47,25 @@ _2026-08-27T18:45:14.461Z_
|
||||
| `--radius-lg` | — | .5rem |
|
||||
| `--text-sm` | — | .875rem |
|
||||
|
||||
## Расхождения элементов (топ 48)
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(1)>div:nth-child(1)>span:nth-child(3)` — "BACKGROUND"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **color**: `rgb(23, 105, 210)` → `rgb(109, 120, 131)`
|
||||
- **padding**: `2.4px 7.2px` → `0px`
|
||||
- **letterSpacing**: `0.8px` → `1.2px`
|
||||
- **borderRadius**: `4px` → `0px`
|
||||
- **display**: `flex` → `inline`
|
||||
- **gap**: `4.8px` → `normal`
|
||||
- **rect**: `116,507 84x20` → `143,489 67x12`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(2)>div:nth-child(1)>span:nth-child(3)` — "TRANSFORM"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **color**: `rgb(23, 105, 210)` → `rgb(109, 120, 131)`
|
||||
- **padding**: `2.4px 7.2px` → `0px`
|
||||
- **letterSpacing**: `0.8px` → `1.2px`
|
||||
- **borderRadius**: `4px` → `0px`
|
||||
- **display**: `flex` → `inline`
|
||||
- **gap**: `4.8px` → `normal`
|
||||
- **rect**: `116,670 78x20` → `143,651 60x12`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(3)>div:nth-child(1)>span:nth-child(3)` — "STYLE"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **color**: `rgb(23, 105, 210)` → `rgb(109, 120, 131)`
|
||||
- **padding**: `2.4px 7.2px` → `0px`
|
||||
- **letterSpacing**: `0.8px` → `1.2px`
|
||||
- **borderRadius**: `4px` → `0px`
|
||||
- **display**: `flex` → `inline`
|
||||
- **gap**: `4.8px` → `normal`
|
||||
- **rect**: `116,785 50x20` → `143,799 34x12`
|
||||
## Расхождения элементов (топ 47)
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>header:nth-child(1)>div:nth-child(2)>div:nth-child(4)>button:nth-child(1)` — "RU"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `11px` → `10px`
|
||||
- **color**: `rgb(255, 255, 255)` → `rgb(238, 241, 244)`
|
||||
- **backgroundColor**: `rgb(23, 105, 210)` → `rgb(23, 33, 43)`
|
||||
- **padding**: `4.8px 11.2px` → `6px 9px`
|
||||
- **letterSpacing**: `0.66px` → `normal`
|
||||
- **rect**: `1307,20 37x24` → `1323,20 29x24`
|
||||
- **padding**: `0px 11.2px` → `6px 9px`
|
||||
- **letterSpacing**: `0.6px` → `normal`
|
||||
- **display**: `flex` → `block`
|
||||
- **rect**: `1309,17 36x30` → `1323,20 29x24`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>span:nth-child(1)` — "COLOR"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **fontWeight**: `500` → `400`
|
||||
- **margin**: `0px` → `0px 0px 8px`
|
||||
- **letterSpacing**: `1px` → `0.8px`
|
||||
- **lineHeight**: `12px` → `normal`
|
||||
- **display**: `block` → `flex`
|
||||
- **rect**: `71,576 203x12` → `143,546 189x12`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(2)>div:nth-child(1)>span:nth-child(1)` — "SOURCE"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `10px` → `9px`
|
||||
- **fontWeight**: `500` → `400`
|
||||
- **color**: `rgb(109, 120, 131)` → `rgb(23, 105, 210)`
|
||||
- **letterSpacing**: `1px` → `normal`
|
||||
- **lineHeight**: `12px` → `normal`
|
||||
- **rect**: `806,320 262x12` → `808,663 30x10`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(2)>div:nth-child(2)>span:nth-child(1)` — "STEP 01"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `10px` → `9px`
|
||||
- **fontWeight**: `500` → `400`
|
||||
- **color**: `rgb(109, 120, 131)` → `rgb(23, 105, 210)`
|
||||
- **letterSpacing**: `1px` → `normal`
|
||||
- **lineHeight**: `12px` → `normal`
|
||||
- **rect**: `1094,320 262x12` → `1096,663 35x10`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(2)>div:nth-child(3)>span:nth-child(1)` — "STEP 02"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `10px` → `9px`
|
||||
- **fontWeight**: `500` → `400`
|
||||
- **color**: `rgb(109, 120, 131)` → `rgb(23, 105, 210)`
|
||||
- **letterSpacing**: `1px` → `normal`
|
||||
- **lineHeight**: `12px` → `normal`
|
||||
- **rect**: `806,752 262x12` → `808,1021 35x10`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(2)>div:nth-child(4)>span:nth-child(1)` — "STEP 03"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `10px` → `9px`
|
||||
- **fontWeight**: `500` → `400`
|
||||
- **color**: `rgb(109, 120, 131)` → `rgb(23, 105, 210)`
|
||||
- **letterSpacing**: `1px` → `normal`
|
||||
- **lineHeight**: `12px` → `normal`
|
||||
- **rect**: `1094,752 262x12` → `1096,1021 35x10`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(2)>div:nth-child(5)>span:nth-child(1)` — "FINAL OUTPUT"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `10px` → `9px`
|
||||
- **fontWeight**: `500` → `400`
|
||||
- **color**: `rgb(109, 120, 131)` → `rgb(23, 105, 210)`
|
||||
- **letterSpacing**: `1px` → `normal`
|
||||
- **lineHeight**: `12px` → `normal`
|
||||
- **rect**: `806,1183 262x12` → `808,1378 59x10`
|
||||
- **rect**: `71,575 203x12` → `143,546 189x12`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(1)>div:nth-child(2)>button:nth-child(2)>span:nth-child(2)>span:nth-child(1)` — "1.2 MB"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `10px` → `11px`
|
||||
- **color**: `rgb(255, 255, 255)` → `rgb(23, 33, 43)`
|
||||
- **margin**: `0px` → `5px 0px 0px`
|
||||
@@ -155,196 +73,185 @@ _2026-08-27T18:45:14.461Z_
|
||||
- **rect**: `1090,240 36x13` → `1246,291 79x13`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>header:nth-child(1)>div:nth-child(2)>div:nth-child(4)>button:nth-child(2)` — "EN"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `11px` → `10px`
|
||||
- **padding**: `4.8px 11.2px` → `6px 9px`
|
||||
- **letterSpacing**: `0.66px` → `normal`
|
||||
- **rect**: `1344,20 38x24` → `1352,20 29x24`
|
||||
- **padding**: `0px 11.2px` → `6px 9px`
|
||||
- **letterSpacing**: `0.6px` → `normal`
|
||||
- **display**: `flex` → `block`
|
||||
- **rect**: `1345,17 37x30` → `1352,20 29x24`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(3)>div:nth-child(2)>button:nth-child(1)` — "100"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `11px` → `10px`
|
||||
- **padding**: `4.8px 11.2px` → `0px`
|
||||
- **letterSpacing**: `0.66px` → `normal`
|
||||
- **rect**: `491,597 44x24` → `520,567 46x30`
|
||||
- **padding**: `0px 11.2px` → `0px`
|
||||
- **letterSpacing**: `0.6px` → `normal`
|
||||
- **display**: `flex` → `block`
|
||||
- **rect**: `491,596 42x30` → `520,567 46x30`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(3)>div:nth-child(2)>button:nth-child(2)` — "75"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `11px` → `10px`
|
||||
- **padding**: `4.8px 11.2px` → `0px`
|
||||
- **letterSpacing**: `0.66px` → `normal`
|
||||
- **rect**: `535,597 38x24` → `566,567 46x30`
|
||||
- **padding**: `0px 11.2px` → `0px`
|
||||
- **letterSpacing**: `0.6px` → `normal`
|
||||
- **display**: `flex` → `block`
|
||||
- **rect**: `533,596 37x30` → `566,567 46x30`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(3)>div:nth-child(2)>button:nth-child(3)` — "50"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `11px` → `10px`
|
||||
- **padding**: `4.8px 11.2px` → `0px`
|
||||
- **letterSpacing**: `0.66px` → `normal`
|
||||
- **rect**: `573,597 38x24` → `612,567 46x30`
|
||||
- **padding**: `0px 11.2px` → `0px`
|
||||
- **letterSpacing**: `0.6px` → `normal`
|
||||
- **display**: `flex` → `block`
|
||||
- **rect**: `569,596 37x30` → `612,567 46x30`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(3)>div:nth-child(2)>button:nth-child(4)` — "25"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `11px` → `10px`
|
||||
- **padding**: `4.8px 11.2px` → `0px`
|
||||
- **letterSpacing**: `0.66px` → `normal`
|
||||
- **rect**: `611,597 38x24` → `658,567 46x30`
|
||||
- **padding**: `0px 11.2px` → `0px`
|
||||
- **letterSpacing**: `0.6px` → `normal`
|
||||
- **display**: `flex` → `block`
|
||||
- **rect**: `606,596 37x30` → `658,567 46x30`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(4)>div:nth-child(2)>div:nth-child(2)>label:nth-child(2)>span:nth-child(1)` — "Preserve aspect ratio"
|
||||
- **fontFamily**: `"IBM Plex Sans", system-ui, -apple-system, sans-serif` → `"IBM Plex Sans", sans-serif`
|
||||
- **fontSize**: `13.6px` → `16px`
|
||||
- **lineHeight**: `normal` → `24px`
|
||||
- **display**: `block` → `inline`
|
||||
- **rect**: `399,1036 129x18` → `432,1021 156x17`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(1)>div:nth-child(1)>span:nth-child(2)` — "01"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **color**: `rgb(109, 120, 131)` → `rgb(23, 105, 210)`
|
||||
- **padding**: `0px` → `17px 0px 0px 15px`
|
||||
- **rect**: `95,510 13x14` → `59,466 46x150`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(1)>div:nth-child(1)>span:nth-child(4)` — "Gradient background"
|
||||
- **fontFamily**: `"IBM Plex Sans", system-ui, -apple-system, sans-serif` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `14.4px` → `15px`
|
||||
- **margin**: `0px` → `5px 0px 18px`
|
||||
- **rect**: `208,508 467x19` → `143,510 157x18`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(2)>div:nth-child(1)>span:nth-child(2)` — "02"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **color**: `rgb(109, 120, 131)` → `rgb(23, 105, 210)`
|
||||
- **padding**: `0px` → `17px 0px 0px 15px`
|
||||
- **rect**: `95,673 13x14` → `59,628 46x136`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(2)>div:nth-child(1)>span:nth-child(4)` — "Remove background"
|
||||
- **fontFamily**: `"IBM Plex Sans", system-ui, -apple-system, sans-serif` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `14.4px` → `15px`
|
||||
- **margin**: `0px` → `5px 0px 18px`
|
||||
- **rect**: `201,671 473x19` → `143,672 140x18`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(3)>div:nth-child(1)>span:nth-child(2)` — "03"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **color**: `rgb(109, 120, 131)` → `rgb(23, 105, 210)`
|
||||
- **padding**: `0px` → `17px 0px 0px 15px`
|
||||
- **rect**: `95,788 13x14` → `59,776 46x150`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(3)>div:nth-child(1)>span:nth-child(4)` — "Add outline"
|
||||
- **fontFamily**: `"IBM Plex Sans", system-ui, -apple-system, sans-serif` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `14.4px` → `15px`
|
||||
- **margin**: `0px` → `5px 0px 18px`
|
||||
- **rect**: `174,785 501x19` → `143,820 91x18`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(4)>div:nth-child(1)>span:nth-child(2)` — "04"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **color**: `rgb(109, 120, 131)` → `rgb(23, 105, 210)`
|
||||
- **padding**: `0px` → `17px 0px 0px 15px`
|
||||
- **rect**: `95,951 13x14` → `59,938 46x142`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(4)>div:nth-child(1)>span:nth-child(4)` — "Round corners"
|
||||
- **fontFamily**: `"IBM Plex Sans", system-ui, -apple-system, sans-serif` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `14.4px` → `15px`
|
||||
- **margin**: `0px` → `5px 0px 18px`
|
||||
- **rect**: `174,948 501x19` → `143,982 107x18`
|
||||
- **rect**: `399,1032 129x18` → `432,1021 156x17`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(1)>div:nth-child(2)>div:nth-child(3)>div:nth-child(1)>span:nth-child(1)` — "DIMENSIONS"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `10px` → `9px`
|
||||
- **letterSpacing**: `1px` → `normal`
|
||||
- **rect**: `1150,215 70x13` → `1073,271 79x10`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(1)>div:nth-child(2)>div:nth-child(3)>div:nth-child(2)>span:nth-child(1)` — "FORMAT"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `10px` → `9px`
|
||||
- **letterSpacing**: `1px` → `normal`
|
||||
- **rect**: `1150,239 42x13` → `1159,271 79x10`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(1)>div:nth-child(2)>div:nth-child(3)>div:nth-child(3)>span:nth-child(1)` — "SIZE"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **fontSize**: `10px` → `9px`
|
||||
- **letterSpacing**: `1px` → `normal`
|
||||
- **rect**: `1150,264 28x13` → `1246,271 79x10`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>header:nth-child(1)>div:nth-child(1)>span:nth-child(2)` — "easy-png-tools"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **color**: `rgb(0, 0, 0)` → `rgb(23, 33, 43)`
|
||||
- **rect**: `98,23 118x18` → `98,23 108x17`
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(2)>div:nth-child(1)>span:nth-child(1)` — "SOURCE"
|
||||
- **fontSize**: `10px` → `9px`
|
||||
- **letterSpacing**: `0.8px` → `normal`
|
||||
- **rect**: `806,320 262x13` → `808,663 30x10`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(2)>div:nth-child(2)>span:nth-child(1)` — "STEP 01"
|
||||
- **fontSize**: `10px` → `9px`
|
||||
- **letterSpacing**: `0.8px` → `normal`
|
||||
- **rect**: `1094,320 262x13` → `1096,663 35x10`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(2)>div:nth-child(3)>span:nth-child(1)` — "STEP 02"
|
||||
- **fontSize**: `10px` → `9px`
|
||||
- **letterSpacing**: `0.8px` → `normal`
|
||||
- **rect**: `806,753 262x13` → `808,1021 35x10`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(2)>div:nth-child(4)>span:nth-child(1)` — "STEP 03"
|
||||
- **fontSize**: `10px` → `9px`
|
||||
- **letterSpacing**: `0.8px` → `normal`
|
||||
- **rect**: `1094,753 262x13` → `1096,1021 35x10`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(2)>div:nth-child(5)>span:nth-child(1)` — "FINAL OUTPUT"
|
||||
- **fontSize**: `10px` → `9px`
|
||||
- **letterSpacing**: `0.8px` → `normal`
|
||||
- **rect**: `806,1185 262x13` → `808,1378 59x10`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(1)>span:nth-child(1)` — "/"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **color**: `rgb(23, 105, 210)` → `rgb(109, 120, 131)`
|
||||
- **rect**: `173,124 7x13` → `165,124 13x12`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(2)>div:nth-child(1)>h1:nth-child(1)` — "Build your image pipeline."
|
||||
- **fontFamily**: `"IBM Plex Sans", system-ui, -apple-system, sans-serif` → `"IBM Plex Sans", sans-serif`
|
||||
- **lineHeight**: `normal` → `57.6px`
|
||||
- **rect**: `58,155 474x150` → `58,154 482x115`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(1)>div:nth-child(1)>span:nth-child(2)` — "01"
|
||||
- **padding**: `0px` → `17px 0px 0px 15px`
|
||||
- **rect**: `95,510 13x14` → `59,466 46x150`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(1)>div:nth-child(1)>span:nth-child(3)` — "BACKGROUND"
|
||||
- **display**: `block` → `inline`
|
||||
- **rect**: `116,510 72x13` → `143,489 67x12`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(1)>div:nth-child(1)>span:nth-child(4)` — "Gradient background"
|
||||
- **margin**: `0px` → `5px 0px 18px`
|
||||
- **rect**: `196,507 171x19` → `143,510 157x18`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(2)>div:nth-child(1)>span:nth-child(2)` — "02"
|
||||
- **padding**: `0px` → `17px 0px 0px 15px`
|
||||
- **rect**: `95,672 13x14` → `59,628 46x136`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(2)>div:nth-child(1)>span:nth-child(3)` — "TRANSFORM"
|
||||
- **display**: `block` → `inline`
|
||||
- **rect**: `116,672 65x13` → `143,651 60x12`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(2)>div:nth-child(1)>span:nth-child(4)` — "Remove background"
|
||||
- **margin**: `0px` → `5px 0px 18px`
|
||||
- **rect**: `189,669 153x19` → `143,672 140x18`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(3)>div:nth-child(1)>span:nth-child(2)` — "03"
|
||||
- **padding**: `0px` → `17px 0px 0px 15px`
|
||||
- **rect**: `95,786 13x14` → `59,776 46x150`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(3)>div:nth-child(1)>span:nth-child(3)` — "STYLE"
|
||||
- **display**: `block` → `inline`
|
||||
- **rect**: `116,786 36x13` → `143,799 34x12`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(3)>div:nth-child(1)>span:nth-child(4)` — "Add outline"
|
||||
- **margin**: `0px` → `5px 0px 18px`
|
||||
- **rect**: `160,783 99x19` → `143,820 91x18`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(4)>div:nth-child(1)>span:nth-child(2)` — "04"
|
||||
- **padding**: `0px` → `17px 0px 0px 15px`
|
||||
- **rect**: `95,948 13x14` → `59,938 46x142`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(4)>div:nth-child(4)>div:nth-child(1)>span:nth-child(4)` — "Round corners"
|
||||
- **margin**: `0px` → `5px 0px 18px`
|
||||
- **rect**: `160,945 117x19` → `143,982 107x18`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(1)>div:nth-child(2)>div:nth-child(3)>div:nth-child(1)>span:nth-child(2)` — "1200 × 800 px"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **margin**: `0px` → `5px 0px 0px`
|
||||
- **rect**: `1236,214 86x14` → `1073,291 79x13`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(1)>div:nth-child(2)>div:nth-child(3)>div:nth-child(2)>span:nth-child(2)` — "PNG-24"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **margin**: `0px` → `5px 0px 0px`
|
||||
- **rect**: `1282,238 40x14` → `1159,291 79x13`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>header:nth-child(1)>div:nth-child(1)>span:nth-child(2)` — "easy-png-tools"
|
||||
- **rect**: `98,23 118x18` → `98,23 108x17`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(2)>div:nth-child(1)>p:nth-child(2)` — "Chain simple tools together. Every chang"
|
||||
- **fontFamily**: `"IBM Plex Sans", system-ui, -apple-system, sans-serif` → `"IBM Plex Sans", sans-serif`
|
||||
- **rect**: `58,321 474x51` → `58,285 482x51`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(2)>div:nth-child(2)>span:nth-child(2)` — "source.png"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **rect**: `597,347 66x14` → `606,311 60x13`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(2)>div:nth-child(2)>b:nth-child(3)` — "1.8 MB"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **rect**: `671,347 40x14` → `674,311 36x13`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(3)>div:nth-child(1)>span:nth-child(1)` — "PROCESSING PIPELINE"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **rect**: `58,434 137x13` → `58,400 127x12`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(1)>div:nth-child(3)>div:nth-child(1)>strong:nth-child(2)>em:nth-child(1)` — "• LIVE"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **rect**: `184,457 36x13` → `173,425 33x12`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(1)>div:nth-child(1)>span:nth-child(1)` — "PIPELINE OUTPUTS"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **rect**: `799,177 58x33` → `799,188 54x36`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(1)>div:nth-child(1)>strong:nth-child(2)` — "Visual history"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **rect**: `799,216 93x36` → `799,233 87x34`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(2)>div:nth-child(1)>div:nth-child(2)>div:nth-child(1)>div:nth-child(1)>span:nth-child(1)` — "PNG"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **rect**: `923,498 28x19` → `923,478 27x18`
|
||||
- **rect**: `923,499 28x19` → `923,478 27x18`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(2)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>span:nth-child(2)` — "original.png · 1200 × 800"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **rect**: `925,706 135x11` → `942,663 124x10`
|
||||
- **rect**: `925,707 135x11` → `942,663 124x10`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(2)>div:nth-child(2)>div:nth-child(2)>div:nth-child(2)>span:nth-child(2)` — "gradient applied"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **rect**: `1262,706 86x11` → `1275,663 79x10`
|
||||
- **rect**: `1262,707 86x11` → `1275,663 79x10`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(2)>div:nth-child(3)>div:nth-child(2)>div:nth-child(2)>span:nth-child(2)` — "background removed"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **rect**: `962,1138 97x11` → `977,1021 89x10`
|
||||
- **rect**: `962,1140 97x11` → `977,1021 89x10`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(2)>div:nth-child(4)>div:nth-child(2)>div:nth-child(2)>span:nth-child(2)` — "outline added"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **rect**: `1278,1138 70x11` → `1290,1021 64x10`
|
||||
- **rect**: `1278,1140 70x11` → `1290,1021 64x10`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>div:nth-child(2)>div:nth-child(5)>div:nth-child(2)>div:nth-child(2)>span:nth-child(2)` — "ready · PNG-24"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **rect**: `984,1569 76x11` → `997,1378 69x10`
|
||||
- **rect**: `984,1572 76x11` → `997,1378 69x10`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>div:nth-child(2)>div:nth-child(2)>div:nth-child(1)>section:nth-child(2)>p:nth-child(3)` — "Output is generated in-browser. Your fil"
|
||||
- **fontFamily**: `"IBM Plex Sans", system-ui, -apple-system, sans-serif` → `"IBM Plex Sans", sans-serif`
|
||||
- **rect**: `799,1624 565x17` → `799,1425 565x17`
|
||||
|
||||
### `body>div:nth-child(1)>div:nth-child(1)>header:nth-child(1)>div:nth-child(1)>span:nth-child(1)` — "EP"
|
||||
- **fontFamily**: `"IBM Plex Mono", ui-monospace, SFMono-Regular, monospace` → `"IBM Plex Mono", monospace`
|
||||
- **rect**: `799,1627 565x17` → `799,1425 565x17`
|
||||
|
||||
## Только у нас (структурно)
|
||||
|
||||
|
||||
+18
-9
@@ -10,6 +10,20 @@ import tseslint from "typescript-eslint";
|
||||
// включается на весь код (см. план-redesign §10, шаг 6).
|
||||
const newCode = ["**/src/lib/components/kit/**", "**/src/routes/preview/**"];
|
||||
|
||||
// Полные recommended-наборы — только на новый код (см. ниже, блок перед prettier).
|
||||
const jsRecommended = Array.isArray(js.configs.recommended)
|
||||
? js.configs.recommended
|
||||
: [js.configs.recommended];
|
||||
const svelteRecommended = Array.isArray(svelte.configs["flat/recommended"])
|
||||
? svelte.configs["flat/recommended"]
|
||||
: [svelte.configs["flat/recommended"]];
|
||||
// Svelte-рекомендации применяем только к .svelte-файлам нового кода, иначе
|
||||
// svelte-eslint-parser "съедает" обычные .ts в тех же папках (напр. +page.ts).
|
||||
const svelteFiles = [
|
||||
"**/src/lib/components/kit/**/*.svelte",
|
||||
"**/src/routes/preview/**/*.svelte",
|
||||
];
|
||||
|
||||
export default tseslint.config(
|
||||
{
|
||||
ignores: [
|
||||
@@ -68,15 +82,10 @@ export default tseslint.config(
|
||||
},
|
||||
// Полные recommended-наборы — только на новый код.
|
||||
...[
|
||||
...(Array.isArray(js.configs.recommended)
|
||||
? js.configs.recommended
|
||||
: [js.configs.recommended]),
|
||||
...tseslint.configs.recommended,
|
||||
...svelte.configs["flat/recommended"],
|
||||
].map((cfg) => ({
|
||||
...cfg,
|
||||
files: newCode,
|
||||
})),
|
||||
...jsRecommended.map((cfg) => ({ ...cfg, files: newCode })),
|
||||
...tseslint.configs.recommended.map((cfg) => ({ ...cfg, files: newCode })),
|
||||
...svelteRecommended.map((cfg) => ({ ...cfg, files: svelteFiles })),
|
||||
],
|
||||
|
||||
// В Svelte 5 пропсы деструктурируются через `let` (конвенция документации и
|
||||
// наш AGENTS.md), поэтому prefer-const на них — ложноположительный.
|
||||
|
||||
+58
-23
@@ -38,7 +38,7 @@ const FIELDS = [
|
||||
"lineHeight",
|
||||
"borderRadius",
|
||||
"display",
|
||||
"gap"
|
||||
"gap",
|
||||
];
|
||||
|
||||
const waitFor = async (url, ms = 60000) => {
|
||||
@@ -58,7 +58,8 @@ const snapshot = (page, url) =>
|
||||
const readTokens = () => {
|
||||
const s = getComputedStyle(document.documentElement);
|
||||
const out = {};
|
||||
for (const k of s) if (k.startsWith("--")) out[k] = s.getPropertyValue(k).trim();
|
||||
for (const k of s)
|
||||
if (k.startsWith("--")) out[k] = s.getPropertyValue(k).trim();
|
||||
return out;
|
||||
};
|
||||
const tokensLight = readTokens();
|
||||
@@ -85,14 +86,19 @@ const snapshot = (page, url) =>
|
||||
"lineHeight",
|
||||
"borderRadius",
|
||||
"display",
|
||||
"gap"
|
||||
"gap",
|
||||
])
|
||||
o[f] = s[f];
|
||||
return o;
|
||||
};
|
||||
const rect = (el) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
return { x: Math.round(r.x), y: Math.round(r.y), w: Math.round(r.width), h: Math.round(r.height) };
|
||||
return {
|
||||
x: Math.round(r.x),
|
||||
y: Math.round(r.y),
|
||||
w: Math.round(r.width),
|
||||
h: Math.round(r.height),
|
||||
};
|
||||
};
|
||||
const walk = (el, path) => {
|
||||
if (["SCRIPT", "STYLE", "NOSCRIPT"].includes(el.tagName)) return [];
|
||||
@@ -101,12 +107,18 @@ const snapshot = (page, url) =>
|
||||
out.push({
|
||||
path,
|
||||
tag: el.tagName.toLowerCase(),
|
||||
text: el.children.length === 0 ? el.textContent.trim().slice(0, 40) : "",
|
||||
text:
|
||||
el.children.length === 0 ? el.textContent.trim().slice(0, 40) : "",
|
||||
rect: rect(el),
|
||||
style: sig(el)
|
||||
style: sig(el),
|
||||
});
|
||||
for (let i = 0; i < kids.length; i++)
|
||||
out.push(...walk(kids[i], `${path}>${kids[i].tagName.toLowerCase()}:nth-child(${i + 1})`));
|
||||
out.push(
|
||||
...walk(
|
||||
kids[i],
|
||||
`${path}>${kids[i].tagName.toLowerCase()}:nth-child(${i + 1})`,
|
||||
),
|
||||
);
|
||||
return out;
|
||||
};
|
||||
return { tokensLight, tokensDark, tree: walk(document.body, "body") };
|
||||
@@ -120,13 +132,16 @@ async function main() {
|
||||
cwd: WEB,
|
||||
stdio: "ignore",
|
||||
shell: true,
|
||||
detached: process.platform !== "win32"
|
||||
detached: process.platform !== "win32",
|
||||
});
|
||||
await waitFor(OURS);
|
||||
}
|
||||
|
||||
const browser = await chromium.launch();
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 900 }, deviceScaleFactor: 1 });
|
||||
const page = await browser.newPage({
|
||||
viewport: { width: 1440, height: 900 },
|
||||
deviceScaleFactor: 1,
|
||||
});
|
||||
try {
|
||||
await page.goto(OURS, { waitUntil: "load" });
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
@@ -154,7 +169,7 @@ async function main() {
|
||||
};
|
||||
const tokenDiffs = {
|
||||
light: tokDiff(ours.tokensLight, ref.tokensLight),
|
||||
dark: tokDiff(ours.tokensDark, ref.tokensDark)
|
||||
dark: tokDiff(ours.tokensDark, ref.tokensDark),
|
||||
};
|
||||
|
||||
// element diff: совпадающие по тексту элементы (структуры разные,
|
||||
@@ -183,9 +198,15 @@ async function main() {
|
||||
}
|
||||
const dr = o.rect;
|
||||
const rr = r.rect;
|
||||
if (Math.abs(dr.x - rr.x) > 2 || Math.abs(dr.y - rr.y) > 2 || Math.abs(dr.w - rr.w) > 2 || Math.abs(dr.h - rr.h) > 2)
|
||||
if (
|
||||
Math.abs(dr.x - rr.x) > 2 ||
|
||||
Math.abs(dr.y - rr.y) > 2 ||
|
||||
Math.abs(dr.w - rr.w) > 2 ||
|
||||
Math.abs(dr.h - rr.h) > 2
|
||||
)
|
||||
deltas.rect = { ours: dr, ref: rr };
|
||||
if (Object.keys(deltas).length) elementDiffs.push({ path: o.path, tag: o.tag, text: k, deltas });
|
||||
if (Object.keys(deltas).length)
|
||||
elementDiffs.push({ path: o.path, tag: o.tag, text: k, deltas });
|
||||
}
|
||||
for (const [k] of txtR) if (!txtO.has(k)) onlyRef.push(k);
|
||||
|
||||
@@ -202,16 +223,22 @@ async function main() {
|
||||
tokenDark: tokenDiffs.dark.length,
|
||||
elements: elementDiffs.length,
|
||||
onlyOurs: onlyOurs.length,
|
||||
onlyRef: onlyRef.length
|
||||
}
|
||||
onlyRef: onlyRef.length,
|
||||
},
|
||||
};
|
||||
|
||||
mkdirSync(resolve(WEB, "audit"), { recursive: true });
|
||||
writeFileSync(resolve(WEB, "audit/audit-report.json"), JSON.stringify(report, null, 2));
|
||||
writeFileSync(resolve(WEB, "audit/audit-report.md"), toMarkdown(report, ours, ref));
|
||||
writeFileSync(
|
||||
resolve(WEB, "audit/audit-report.json"),
|
||||
JSON.stringify(report, null, 2),
|
||||
);
|
||||
writeFileSync(
|
||||
resolve(WEB, "audit/audit-report.md"),
|
||||
toMarkdown(report, ours, ref),
|
||||
);
|
||||
console.log(
|
||||
`audit done: tokens light/dark=${tokenDiffs.light.length}/${tokenDiffs.dark.length}, ` +
|
||||
`elements=${elementDiffs.length}, onlyOurs=${onlyOurs.length}, onlyRef=${onlyRef.length}`
|
||||
`elements=${elementDiffs.length}, onlyOurs=${onlyOurs.length}, onlyRef=${onlyRef.length}`,
|
||||
);
|
||||
console.log(`report: web/audit/audit-report.md`);
|
||||
} finally {
|
||||
@@ -219,7 +246,9 @@ async function main() {
|
||||
if (server) {
|
||||
try {
|
||||
if (process.platform === "win32")
|
||||
spawn("taskkill", ["/pid", String(server.pid), "/f", "/t"], { stdio: "ignore" });
|
||||
spawn("taskkill", ["/pid", String(server.pid), "/f", "/t"], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
else server.kill("SIGTERM");
|
||||
} catch {}
|
||||
}
|
||||
@@ -233,7 +262,7 @@ function toMarkdown(report, ours, ref) {
|
||||
rows.map((r) => `| \`${r.key}\` | ${r.ours} | ${r.ref} |`).join("\n")
|
||||
: "_все совпадают_";
|
||||
const sorted = [...report.elementDiffs].sort(
|
||||
(x, y) => Object.keys(y.deltas).length - Object.keys(x.deltas).length
|
||||
(x, y) => Object.keys(y.deltas).length - Object.keys(x.deltas).length,
|
||||
);
|
||||
const elRows = sorted
|
||||
.slice(0, 100)
|
||||
@@ -250,7 +279,8 @@ function toMarkdown(report, ours, ref) {
|
||||
return `### \`${e.path}\`${e.text ? ` — "${e.text}"` : ""}\n${d}`;
|
||||
})
|
||||
.join("\n\n");
|
||||
return `# Style audit: ${report.ours}\n\nvs ${report.ref}\n\n_${report.generatedAt}_\n\n` +
|
||||
return (
|
||||
`# Style audit: ${report.ours}\n\nvs ${report.ref}\n\n_${report.generatedAt}_\n\n` +
|
||||
`## Сводка\n\n- Токены light: **${report.counts.tokenLight}** расх.\n` +
|
||||
`- Токены dark: **${report.counts.tokenDark}** расх.\n` +
|
||||
`- Элементы (стиль/геометрия): **${report.counts.elements}** расх.\n` +
|
||||
@@ -259,10 +289,15 @@ function toMarkdown(report, ours, ref) {
|
||||
`## Токены — Dark\n\n${tokTable(report.tokenDiffs.dark)}\n\n` +
|
||||
`## Расхождения элементов (топ ${Math.min(100, sorted.length)})\n\n${elRows}\n\n` +
|
||||
`## Только у нас (структурно)\n\n` +
|
||||
(report.onlyOurs.length ? report.onlyOurs.map((p) => `- \`${p}\``).join("\n") : "_—_") +
|
||||
(report.onlyOurs.length
|
||||
? report.onlyOurs.map((p) => `- \`${p}\``).join("\n")
|
||||
: "_—_") +
|
||||
`\n\n## Только в рефе (структурно)\n\n` +
|
||||
(report.onlyRef.length ? report.onlyRef.map((p) => `- \`${p}\``).join("\n") : "_—_") +
|
||||
`\n`;
|
||||
(report.onlyRef.length
|
||||
? report.onlyRef.map((p) => `- \`${p}\``).join("\n")
|
||||
: "_—_") +
|
||||
`\n`
|
||||
);
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
|
||||
+5
-4
@@ -39,11 +39,12 @@
|
||||
--control-max-width: 16rem;
|
||||
|
||||
--font-sans:
|
||||
system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
--font-mono: ui-monospace, 'Cascadia Code', Consolas, monospace;
|
||||
system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial,
|
||||
sans-serif;
|
||||
--font-mono: ui-monospace, "Cascadia Code", Consolas, monospace;
|
||||
}
|
||||
|
||||
[data-theme='dark'] {
|
||||
[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
|
||||
--bg: #12151a;
|
||||
@@ -150,7 +151,7 @@ select {
|
||||
max-width: var(--control-max-width);
|
||||
}
|
||||
|
||||
input.control[type='number'] {
|
||||
input.control[type="number"] {
|
||||
font-family: var(--font-mono);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
Vendored
+1
-1
@@ -10,7 +10,7 @@ declare global {
|
||||
}
|
||||
}
|
||||
|
||||
declare module '*.css?raw' {
|
||||
declare module "*.css?raw" {
|
||||
const content: string;
|
||||
export default content;
|
||||
}
|
||||
|
||||
+6
-6
@@ -7,16 +7,16 @@
|
||||
<script>
|
||||
(() => {
|
||||
try {
|
||||
const saved = localStorage.getItem('theme');
|
||||
const saved = localStorage.getItem("theme");
|
||||
const theme =
|
||||
saved === 'dark' || saved === 'light'
|
||||
saved === "dark" || saved === "light"
|
||||
? saved
|
||||
: matchMedia('(prefers-color-scheme: dark)').matches
|
||||
? 'dark'
|
||||
: 'light';
|
||||
: matchMedia("(prefers-color-scheme: dark)").matches
|
||||
? "dark"
|
||||
: "light";
|
||||
document.documentElement.dataset.theme = theme;
|
||||
} catch {
|
||||
document.documentElement.dataset.theme = 'light';
|
||||
document.documentElement.dataset.theme = "light";
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
|
||||
+16
-16
@@ -1,24 +1,24 @@
|
||||
export type CategoryId =
|
||||
| 'convert'
|
||||
| 'alpha'
|
||||
| 'color'
|
||||
| 'geometry'
|
||||
| 'analyze'
|
||||
| 'generate'
|
||||
| 'filters'
|
||||
| 'text';
|
||||
| "convert"
|
||||
| "alpha"
|
||||
| "color"
|
||||
| "geometry"
|
||||
| "analyze"
|
||||
| "generate"
|
||||
| "filters"
|
||||
| "text";
|
||||
|
||||
/**
|
||||
* Порядок категорий в каталоге. Человекочитаемые названия живут в словарях
|
||||
* i18n: секция categories, ключ = CategoryId.
|
||||
*/
|
||||
export const CATEGORIES: readonly CategoryId[] = [
|
||||
'convert',
|
||||
'alpha',
|
||||
'color',
|
||||
'geometry',
|
||||
'filters',
|
||||
'text',
|
||||
'analyze',
|
||||
'generate'
|
||||
"convert",
|
||||
"alpha",
|
||||
"color",
|
||||
"geometry",
|
||||
"filters",
|
||||
"text",
|
||||
"analyze",
|
||||
"generate",
|
||||
];
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<script lang="ts">
|
||||
import Button from './ui/Button.svelte';
|
||||
import { downloadBlob, encode } from '$lib/core/io';
|
||||
import type { PixelImage } from '$lib/core/types';
|
||||
import type { OutputFormat } from '$lib/registry';
|
||||
import { t } from '$lib/i18n/t';
|
||||
import Button from "./ui/Button.svelte";
|
||||
import { downloadBlob, encode } from "$lib/core/io";
|
||||
import type { PixelImage } from "$lib/core/types";
|
||||
import type { OutputFormat } from "$lib/registry";
|
||||
import { t } from "$lib/i18n/t";
|
||||
|
||||
interface Props {
|
||||
image: PixelImage | null;
|
||||
@@ -21,9 +21,13 @@
|
||||
if (!image || !format || busy) return;
|
||||
busy = true;
|
||||
try {
|
||||
const raw = format.qualityParamId ? params[format.qualityParamId] : undefined;
|
||||
const raw = format.qualityParamId
|
||||
? params[format.qualityParamId]
|
||||
: undefined;
|
||||
const quality =
|
||||
typeof raw === 'number' ? Math.min(Math.max(raw, 1), 100) / 100 : undefined;
|
||||
typeof raw === "number"
|
||||
? Math.min(Math.max(raw, 1), 100) / 100
|
||||
: undefined;
|
||||
const blob = await encode(image, format.mime, quality);
|
||||
downloadBlob(blob, `${baseName}.${format.ext}`);
|
||||
} catch (e) {
|
||||
@@ -39,8 +43,8 @@
|
||||
fullWidth
|
||||
disabled={!image || !format}
|
||||
{busy}
|
||||
busyText={t('download.busy')}
|
||||
busyText={t("download.busy")}
|
||||
onclick={download}
|
||||
>
|
||||
{t('download.file', { ext: format?.ext ?? 'png' })}
|
||||
{t("download.file", { ext: format?.ext ?? "png" })}
|
||||
</Button>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
import { isSupportedImage, unsupportedImageError } from '$lib/core/io';
|
||||
import { t } from '$lib/i18n/t';
|
||||
import type { Snippet } from "svelte";
|
||||
import { isSupportedImage, unsupportedImageError } from "$lib/core/io";
|
||||
import { t } from "$lib/i18n/t";
|
||||
|
||||
interface Props {
|
||||
onFile: (file: File) => void;
|
||||
@@ -13,8 +13,8 @@
|
||||
let {
|
||||
onFile,
|
||||
onError,
|
||||
label = t('dropZone.overlayDefault'),
|
||||
children
|
||||
label = t("dropZone.overlayDefault"),
|
||||
children,
|
||||
}: Props = $props();
|
||||
|
||||
let depth = $state(0);
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
<script lang="ts">
|
||||
import { ACCEPTED_IMAGE_TYPES, isSupportedImage, unsupportedImageError } from '$lib/core/io';
|
||||
import { t } from '$lib/i18n/t';
|
||||
import {
|
||||
ACCEPTED_IMAGE_TYPES,
|
||||
isSupportedImage,
|
||||
unsupportedImageError,
|
||||
} from "$lib/core/io";
|
||||
import { t } from "$lib/i18n/t";
|
||||
|
||||
interface Props {
|
||||
onFile: (file: File) => void;
|
||||
@@ -8,7 +12,7 @@
|
||||
label?: string;
|
||||
}
|
||||
|
||||
let { onFile, onError, label = t('dropZone.pickDefault') }: Props = $props();
|
||||
let { onFile, onError, label = t("dropZone.pickDefault") }: Props = $props();
|
||||
|
||||
let input = $state<HTMLInputElement | undefined>();
|
||||
let depth = $state(0);
|
||||
@@ -52,7 +56,7 @@
|
||||
aria-label={label}
|
||||
onclick={openPicker}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
openPicker();
|
||||
}
|
||||
@@ -78,7 +82,7 @@
|
||||
onchange={() => {
|
||||
accept(input?.files?.[0]);
|
||||
if (input) {
|
||||
input.value = '';
|
||||
input.value = "";
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<script lang="ts">
|
||||
import type { ImageInfo } from '$lib/core/analyze';
|
||||
import { LOCALE_TAGS } from '$lib/i18n/dict';
|
||||
import { getLocale } from '$lib/i18n/locale.svelte';
|
||||
import { t } from '$lib/i18n/t';
|
||||
import type { ImageInfo } from "$lib/core/analyze";
|
||||
import { LOCALE_TAGS } from "$lib/i18n/dict";
|
||||
import { getLocale } from "$lib/i18n/locale.svelte";
|
||||
import { t } from "$lib/i18n/t";
|
||||
|
||||
interface Props {
|
||||
info: ImageInfo | null;
|
||||
@@ -14,15 +14,17 @@
|
||||
{#if info}
|
||||
<dl>
|
||||
<div class="panel">
|
||||
<dt>{t('infoPanel.dimensions')}</dt>
|
||||
<dt>{t("infoPanel.dimensions")}</dt>
|
||||
<dd>{info.width} × {info.height} px</dd>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<dt>{t('infoPanel.alpha')}</dt>
|
||||
<dd>{info.hasAlpha ? t('infoPanel.alphaYes') : t('infoPanel.alphaNo')}</dd>
|
||||
<dt>{t("infoPanel.alpha")}</dt>
|
||||
<dd>
|
||||
{info.hasAlpha ? t("infoPanel.alphaYes") : t("infoPanel.alphaNo")}
|
||||
</dd>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<dt>{t('infoPanel.colorCount')}</dt>
|
||||
<dt>{t("infoPanel.colorCount")}</dt>
|
||||
<dd>{info.colorCount.toLocaleString(LOCALE_TAGS[getLocale()])}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
<script lang="ts">
|
||||
import CheckboxField from './ui/CheckboxField.svelte';
|
||||
import ColorField from './ui/ColorField.svelte';
|
||||
import SelectField from './ui/SelectField.svelte';
|
||||
import SliderField from './ui/SliderField.svelte';
|
||||
import TextField from './ui/TextField.svelte';
|
||||
import type { ParamDef, ToolEntry } from '$lib/registry';
|
||||
import { optionLabel, paramLabel } from '$lib/i18n/tool-strings';
|
||||
import { t } from '$lib/i18n/t';
|
||||
import CheckboxField from "./ui/CheckboxField.svelte";
|
||||
import ColorField from "./ui/ColorField.svelte";
|
||||
import SelectField from "./ui/SelectField.svelte";
|
||||
import SliderField from "./ui/SliderField.svelte";
|
||||
import TextField from "./ui/TextField.svelte";
|
||||
import type { ParamDef, ToolEntry } from "$lib/registry";
|
||||
import { optionLabel, paramLabel } from "$lib/i18n/tool-strings";
|
||||
import { t } from "$lib/i18n/t";
|
||||
|
||||
interface Props {
|
||||
tool: ToolEntry;
|
||||
@@ -25,19 +25,27 @@
|
||||
pipetteTargetId = null,
|
||||
onPipetteToggle,
|
||||
hasMask = false,
|
||||
showMask = $bindable(false)
|
||||
showMask = $bindable(false),
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
<div class="params-grid">
|
||||
{#if hasMask}
|
||||
<CheckboxField id="show-mask" label={t('ui.showMask')} bind:checked={showMask} />
|
||||
<CheckboxField
|
||||
id="show-mask"
|
||||
label={t("ui.showMask")}
|
||||
bind:checked={showMask}
|
||||
/>
|
||||
{/if}
|
||||
{#each params as param (param.id)}
|
||||
<div class="field">
|
||||
{#if param.type === 'checkbox'}
|
||||
<CheckboxField id={param.id} label={paramLabel(tool, param)} bind:checked={values[param.id]} />
|
||||
{:else if param.type === 'number'}
|
||||
{#if param.type === "checkbox"}
|
||||
<CheckboxField
|
||||
id={param.id}
|
||||
label={paramLabel(tool, param)}
|
||||
bind:checked={values[param.id]}
|
||||
/>
|
||||
{:else if param.type === "number"}
|
||||
<TextField
|
||||
id={param.id}
|
||||
label={paramLabel(tool, param)}
|
||||
@@ -47,7 +55,7 @@
|
||||
step={param.step}
|
||||
bind:value={values[param.id]}
|
||||
/>
|
||||
{:else if param.type === 'slider'}
|
||||
{:else if param.type === "slider"}
|
||||
<SliderField
|
||||
id={param.id}
|
||||
label={paramLabel(tool, param)}
|
||||
@@ -57,17 +65,17 @@
|
||||
default={param.default}
|
||||
bind:value={values[param.id]}
|
||||
/>
|
||||
{:else if param.type === 'select'}
|
||||
{:else if param.type === "select"}
|
||||
<SelectField
|
||||
id={param.id}
|
||||
label={paramLabel(tool, param)}
|
||||
options={param.options.map((o) => ({
|
||||
value: o.value,
|
||||
label: optionLabel(tool, param, o.value)
|
||||
label: optionLabel(tool, param, o.value),
|
||||
}))}
|
||||
bind:value={values[param.id]}
|
||||
/>
|
||||
{:else if param.type === 'color'}
|
||||
{:else if param.type === "color"}
|
||||
<ColorField
|
||||
id={param.id}
|
||||
label={paramLabel(tool, param)}
|
||||
@@ -75,7 +83,7 @@
|
||||
pipetteActive={pipetteTargetId === param.id}
|
||||
onPipetteToggle={() => onPipetteToggle?.(param.id)}
|
||||
/>
|
||||
{:else if param.type === 'text'}
|
||||
{:else if param.type === "text"}
|
||||
<TextField
|
||||
id={param.id}
|
||||
label={paramLabel(tool, param)}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { rgbToHex } from '$lib/core/color';
|
||||
import type { PixelImage } from '$lib/core/types';
|
||||
import PipetteLoupe from './tool/PipetteLoupe.svelte';
|
||||
import { rgbToHex } from "$lib/core/color";
|
||||
import type { PixelImage } from "$lib/core/types";
|
||||
import PipetteLoupe from "./tool/PipetteLoupe.svelte";
|
||||
|
||||
interface Props {
|
||||
image: PixelImage | null;
|
||||
@@ -12,27 +12,42 @@
|
||||
let { image, pipetteActive = false, onPickColor }: Props = $props();
|
||||
|
||||
let canvas = $state<HTMLCanvasElement | undefined>();
|
||||
let hover = $state<{ clientX: number; clientY: number; px: number; py: number; hex: string } | null>(
|
||||
null
|
||||
);
|
||||
let hover = $state<{
|
||||
clientX: number;
|
||||
clientY: number;
|
||||
px: number;
|
||||
py: number;
|
||||
hex: string;
|
||||
} | null>(null);
|
||||
|
||||
$effect(() => {
|
||||
if (!canvas || !image) return;
|
||||
canvas.width = image.width;
|
||||
canvas.height = image.height;
|
||||
const ctx = canvas.getContext('2d');
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) return;
|
||||
ctx.putImageData(new ImageData(image.data, image.width, image.height), 0, 0);
|
||||
ctx.putImageData(
|
||||
new ImageData(image.data, image.width, image.height),
|
||||
0,
|
||||
0,
|
||||
);
|
||||
});
|
||||
|
||||
function pixelAt(event: MouseEvent): { px: number; py: number; hex: string } | null {
|
||||
function pixelAt(
|
||||
event: MouseEvent,
|
||||
): { px: number; py: number; hex: string } | null {
|
||||
if (!canvas || !image) return null;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
if (rect.width === 0 || rect.height === 0) return null;
|
||||
const px = Math.floor((event.clientX - rect.left) * (canvas.width / rect.width));
|
||||
const py = Math.floor((event.clientY - rect.top) * (canvas.height / rect.height));
|
||||
if (px < 0 || py < 0 || px >= canvas.width || py >= canvas.height) return null;
|
||||
const ctx = canvas.getContext('2d');
|
||||
const px = Math.floor(
|
||||
(event.clientX - rect.left) * (canvas.width / rect.width),
|
||||
);
|
||||
const py = Math.floor(
|
||||
(event.clientY - rect.top) * (canvas.height / rect.height),
|
||||
);
|
||||
if (px < 0 || py < 0 || px >= canvas.width || py >= canvas.height)
|
||||
return null;
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) return null;
|
||||
const [r, g, b] = ctx.getImageData(px, py, 1, 1).data;
|
||||
return { px, py, hex: rgbToHex(r, g, b) };
|
||||
@@ -53,7 +68,13 @@
|
||||
}
|
||||
const pixel = pixelAt(event);
|
||||
hover = pixel
|
||||
? { clientX: event.clientX, clientY: event.clientY, px: pixel.px, py: pixel.py, hex: pixel.hex }
|
||||
? {
|
||||
clientX: event.clientX,
|
||||
clientY: event.clientY,
|
||||
px: pixel.px,
|
||||
py: pixel.py,
|
||||
hex: pixel.hex,
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
@@ -90,8 +111,10 @@
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
max-height: 32rem;
|
||||
background:
|
||||
repeating-conic-gradient(var(--check-a) 0% 25%, var(--check-b) 0% 50%);
|
||||
background: repeating-conic-gradient(
|
||||
var(--check-a) 0% 25%,
|
||||
var(--check-b) 0% 50%
|
||||
);
|
||||
background-size: 16px 16px;
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
@@ -1,60 +1,81 @@
|
||||
<script lang="ts">
|
||||
import { imageInfo, type ImageInfo } from '$lib/core/analyze';
|
||||
import { ToolError } from '$lib/core/errors';
|
||||
import { decodeFile, isSupportedImage, unsupportedImageError } from '$lib/core/io';
|
||||
import type { PixelImage } from '$lib/core/types';
|
||||
import { defaultParams, getTool, outputOf, sanitizeParams, type ToolEntry } from '$lib/registry';
|
||||
import { loadStoredSteps, newStepId, saveSteps, type PipelineStep } from '$lib/tools/pipeline';
|
||||
import { TOOL_ICONS } from '$lib/tools/tool-icons';
|
||||
import DownloadButton from './DownloadButton.svelte';
|
||||
import ParamForm from './ParamForm.svelte';
|
||||
import Preview from './Preview.svelte';
|
||||
import ToolSearch from './search/ToolSearch.svelte';
|
||||
import { createAutoRunner } from '$lib/tools/auto-run';
|
||||
import { executeStep } from '$lib/tools/executor';
|
||||
import { clearOverlay, setOverlay } from '$lib/tools/overlay-store.svelte';
|
||||
import { t } from '$lib/i18n/t';
|
||||
import { toolDescription, toolTitle } from '$lib/i18n/tool-strings';
|
||||
import type { StageStatus } from './stage/stage-props';
|
||||
import ChainToolBlock from './chain/ChainToolBlock.svelte';
|
||||
import ToolStage from './stage/ToolStage.svelte';
|
||||
import ToolStageClassic from './stage/ToolStageClassic.svelte';
|
||||
import { imageInfo, type ImageInfo } from "$lib/core/analyze";
|
||||
import { ToolError } from "$lib/core/errors";
|
||||
import {
|
||||
decodeFile,
|
||||
isSupportedImage,
|
||||
unsupportedImageError,
|
||||
} from "$lib/core/io";
|
||||
import type { PixelImage } from "$lib/core/types";
|
||||
import {
|
||||
defaultParams,
|
||||
getTool,
|
||||
outputOf,
|
||||
sanitizeParams,
|
||||
type ToolEntry,
|
||||
} from "$lib/registry";
|
||||
import {
|
||||
loadStoredSteps,
|
||||
newStepId,
|
||||
saveSteps,
|
||||
type PipelineStep,
|
||||
} from "$lib/tools/pipeline";
|
||||
import { TOOL_ICONS } from "$lib/tools/tool-icons";
|
||||
import DownloadButton from "./DownloadButton.svelte";
|
||||
import ParamForm from "./ParamForm.svelte";
|
||||
import Preview from "./Preview.svelte";
|
||||
import ToolSearch from "./search/ToolSearch.svelte";
|
||||
import { createAutoRunner } from "$lib/tools/auto-run";
|
||||
import { executeStep } from "$lib/tools/executor";
|
||||
import { clearOverlay, setOverlay } from "$lib/tools/overlay-store.svelte";
|
||||
import { t } from "$lib/i18n/t";
|
||||
import { toolDescription, toolTitle } from "$lib/i18n/tool-strings";
|
||||
import type { StageStatus } from "./stage/stage-props";
|
||||
import ChainToolBlock from "./chain/ChainToolBlock.svelte";
|
||||
import ToolStage from "./stage/ToolStage.svelte";
|
||||
import ToolStageClassic from "./stage/ToolStageClassic.svelte";
|
||||
|
||||
export type PresetStep = { toolId: string; values?: Record<string, unknown> };
|
||||
|
||||
let {
|
||||
tool,
|
||||
restoreChain = false,
|
||||
stageVariant = 'inline',
|
||||
stageVariant = "inline",
|
||||
presetBaseValues,
|
||||
presetChain
|
||||
presetChain,
|
||||
}: {
|
||||
tool: ToolEntry;
|
||||
restoreChain?: boolean;
|
||||
stageVariant?: 'classic' | 'inline';
|
||||
stageVariant?: "classic" | "inline";
|
||||
presetBaseValues?: Record<string, unknown>;
|
||||
presetChain?: PresetStep[];
|
||||
} = $props();
|
||||
|
||||
const StageComponent = $derived(stageVariant === 'classic' ? ToolStageClassic : ToolStage);
|
||||
const StageComponent = $derived(
|
||||
stageVariant === "classic" ? ToolStageClassic : ToolStage,
|
||||
);
|
||||
|
||||
type Status = StageStatus;
|
||||
|
||||
const isPreset = $derived(
|
||||
(presetChain?.length ?? 0) > 0 || Object.keys(presetBaseValues ?? {}).length > 0
|
||||
(presetChain?.length ?? 0) > 0 ||
|
||||
Object.keys(presetBaseValues ?? {}).length > 0,
|
||||
);
|
||||
|
||||
let status = $state<Status>('idle');
|
||||
let status = $state<Status>("idle");
|
||||
let source = $state<PixelImage | null>(null);
|
||||
let result = $state<PixelImage | null>(null);
|
||||
let previewResult = $state<PixelImage | null>(null);
|
||||
let textResult = $state<string | null>(null);
|
||||
let showMask = $state(false);
|
||||
let info = $state<ImageInfo | null>(null);
|
||||
let errorText = $state('');
|
||||
let errorText = $state("");
|
||||
let overlayImage = $state<PixelImage | null>(null);
|
||||
// svelte-ignore state_referenced_locally
|
||||
let values = $state<Record<string, any>>({ ...defaultParams(tool), ...presetBaseValues });
|
||||
let values = $state<Record<string, any>>({
|
||||
...defaultParams(tool),
|
||||
...presetBaseValues,
|
||||
});
|
||||
// svelte-ignore state_referenced_locally
|
||||
let chain = $state<PipelineStep[]>(
|
||||
restoreChain
|
||||
@@ -66,28 +87,30 @@
|
||||
{
|
||||
id: newStepId(),
|
||||
toolId: preset.toolId,
|
||||
values: { ...defaultParams(stepTool), ...preset.values }
|
||||
}
|
||||
values: { ...defaultParams(stepTool), ...preset.values },
|
||||
},
|
||||
]
|
||||
: [];
|
||||
})
|
||||
}),
|
||||
);
|
||||
let chainResults = $state<(PixelImage | null)[]>([]);
|
||||
let lastRunChainJson = '';
|
||||
let lastRunChainJson = "";
|
||||
|
||||
const isInfo = $derived(tool.resultType === 'info');
|
||||
const isSourceless = $derived(tool.sourceMode === 'none');
|
||||
const isTextSource = $derived(tool.sourceMode === 'text');
|
||||
const isInfo = $derived(tool.resultType === "info");
|
||||
const isSourceless = $derived(tool.sourceMode === "none");
|
||||
const isTextSource = $derived(tool.sourceMode === "text");
|
||||
const sanitized = $derived(sanitizeParams(tool, values));
|
||||
const canChainBase = $derived(
|
||||
(tool.resultType ?? 'image') === 'image' && tool.sourceMode !== 'text'
|
||||
(tool.resultType ?? "image") === "image" && tool.sourceMode !== "text",
|
||||
);
|
||||
const hasMask = $derived(typeof tool.preview === 'function');
|
||||
const shownBase = $derived(showMask && previewResult ? previewResult : result);
|
||||
const hasFilledSteps = $derived(chain.some((step) => step.toolId !== ''));
|
||||
const hasMask = $derived(typeof tool.preview === "function");
|
||||
const shownBase = $derived(
|
||||
showMask && previewResult ? previewResult : result,
|
||||
);
|
||||
const hasFilledSteps = $derived(chain.some((step) => step.toolId !== ""));
|
||||
|
||||
function addChainStep() {
|
||||
chain.push({ id: newStepId(), toolId: '', values: {} });
|
||||
chain.push({ id: newStepId(), toolId: "", values: {} });
|
||||
}
|
||||
|
||||
function removeChainStep(index: number) {
|
||||
@@ -118,7 +141,7 @@
|
||||
const runner = createAutoRunner();
|
||||
let hasLastRun = false;
|
||||
let lastRunSource: PixelImage | null = null;
|
||||
let lastRunValuesJson = '';
|
||||
let lastRunValuesJson = "";
|
||||
let pipetteTargetId = $state<string | null>(null);
|
||||
|
||||
function handlePipetteToggle(id: string) {
|
||||
@@ -132,8 +155,8 @@
|
||||
}
|
||||
|
||||
async function handleFile(file: File) {
|
||||
errorText = '';
|
||||
status = 'processing';
|
||||
errorText = "";
|
||||
status = "processing";
|
||||
try {
|
||||
source = await decodeFile(file);
|
||||
values = defaultParams(tool);
|
||||
@@ -143,7 +166,7 @@
|
||||
pipetteTargetId = null;
|
||||
info = isInfo ? imageInfo(source) : null;
|
||||
if (isInfo) {
|
||||
status = 'loaded';
|
||||
status = "loaded";
|
||||
} else {
|
||||
await runTool();
|
||||
}
|
||||
@@ -154,15 +177,15 @@
|
||||
|
||||
async function handleTextSubmit(text: string) {
|
||||
if (!isTextSource) return;
|
||||
errorText = '';
|
||||
status = 'processing';
|
||||
errorText = "";
|
||||
status = "processing";
|
||||
if (tool.textToText) {
|
||||
try {
|
||||
result = null;
|
||||
previewResult = null;
|
||||
info = null;
|
||||
textResult = await tool.textToText(text);
|
||||
status = 'loaded';
|
||||
status = "loaded";
|
||||
} catch (e) {
|
||||
showError(e);
|
||||
}
|
||||
@@ -196,7 +219,7 @@
|
||||
let next: PixelImage | null = null;
|
||||
let nextText: string | null = null;
|
||||
|
||||
if (tool.resultType === 'text') {
|
||||
if (tool.resultType === "text") {
|
||||
nextText = await tool.toText!(source!, sanitized);
|
||||
} else if (isSourceless) {
|
||||
next = await tool.generate!(sanitized);
|
||||
@@ -221,23 +244,31 @@
|
||||
let current: PixelImage | null = next ?? source;
|
||||
for (let i = 0; i < chain.length; i++) {
|
||||
const step = chain[i];
|
||||
const stepTool = step.toolId === '' ? undefined : getTool(step.toolId);
|
||||
const stepTool = step.toolId === "" ? undefined : getTool(step.toolId);
|
||||
if (!current || !stepTool?.run) {
|
||||
collected.push(null);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
current = await executeStep(stepTool, current, sanitizeParams(stepTool, step.values));
|
||||
current = await executeStep(
|
||||
stepTool,
|
||||
current,
|
||||
sanitizeParams(stepTool, step.values),
|
||||
);
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
t('toolPage.stepError', { n: i + 2, title: toolTitle(stepTool), msg: errorMessage(e) })
|
||||
t("toolPage.stepError", {
|
||||
n: i + 2,
|
||||
title: toolTitle(stepTool),
|
||||
msg: errorMessage(e),
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (!runner.isCurrent(token)) return;
|
||||
collected.push(current);
|
||||
}
|
||||
chainResults = collected;
|
||||
status = 'loaded';
|
||||
status = "loaded";
|
||||
} catch (e) {
|
||||
if (!runner.isCurrent(token)) return;
|
||||
showError(e);
|
||||
@@ -262,7 +293,7 @@
|
||||
|
||||
$effect(() => {
|
||||
if (isPreset) return;
|
||||
const filled = chain.filter((step) => step.toolId !== '');
|
||||
const filled = chain.filter((step) => step.toolId !== "");
|
||||
if (filled.length === 0 && !hasLastRun) return;
|
||||
saveSteps(filled);
|
||||
});
|
||||
@@ -273,7 +304,7 @@
|
||||
}
|
||||
|
||||
function showError(e: unknown) {
|
||||
status = source ? 'loaded' : 'idle';
|
||||
status = source ? "loaded" : "idle";
|
||||
errorText = errorMessage(e);
|
||||
}
|
||||
|
||||
@@ -285,8 +316,8 @@
|
||||
showMask = false;
|
||||
pipetteTargetId = null;
|
||||
info = null;
|
||||
errorText = '';
|
||||
status = 'idle';
|
||||
errorText = "";
|
||||
status = "idle";
|
||||
clearOverlay();
|
||||
values = { ...defaultParams(tool), ...presetBaseValues };
|
||||
}
|
||||
@@ -303,7 +334,7 @@
|
||||
const items = event.clipboardData?.items;
|
||||
if (!items) return;
|
||||
for (const item of items) {
|
||||
if (!item.type.startsWith('image/')) continue;
|
||||
if (!item.type.startsWith("image/")) continue;
|
||||
const file = item.getAsFile();
|
||||
if (file) {
|
||||
event.preventDefault();
|
||||
@@ -331,32 +362,32 @@
|
||||
<StageComponent
|
||||
mode="base"
|
||||
{tool}
|
||||
source={source}
|
||||
result={result}
|
||||
{source}
|
||||
{result}
|
||||
displayImage={shownBase}
|
||||
info={info}
|
||||
status={status}
|
||||
isInfo={isInfo}
|
||||
isSourceless={isSourceless}
|
||||
isTextSource={isTextSource}
|
||||
textResult={textResult}
|
||||
sanitized={sanitized}
|
||||
canChainBase={canChainBase}
|
||||
{info}
|
||||
{status}
|
||||
{isInfo}
|
||||
{isSourceless}
|
||||
{isTextSource}
|
||||
{textResult}
|
||||
{sanitized}
|
||||
{canChainBase}
|
||||
hasChain={chain.length > 0}
|
||||
hasMask={hasMask}
|
||||
{hasMask}
|
||||
bind:showMask
|
||||
bind:values
|
||||
pipetteTargetId={pipetteTargetId}
|
||||
handleFile={handleFile}
|
||||
{pipetteTargetId}
|
||||
{handleFile}
|
||||
onTextSubmit={handleTextSubmit}
|
||||
onSourceError={(e) => (errorText = errorMessage(e))}
|
||||
reset={reset}
|
||||
toggleChain={toggleChain}
|
||||
handlePipetteToggle={handlePipetteToggle}
|
||||
handlePickColor={handlePickColor}
|
||||
showError={showError}
|
||||
errorMessage={errorMessage}
|
||||
overlayImage={overlayImage}
|
||||
{reset}
|
||||
{toggleChain}
|
||||
{handlePipetteToggle}
|
||||
{handlePickColor}
|
||||
{showError}
|
||||
{errorMessage}
|
||||
{overlayImage}
|
||||
onOverlayFile={(f) => void handleOverlayFile(f)}
|
||||
onOverlayError={(e) => (errorText = errorMessage(e))}
|
||||
onOverlayClear={clearOverlay}
|
||||
@@ -364,33 +395,38 @@
|
||||
|
||||
<div class="chain-stack">
|
||||
{#each chain as step, index (step.id)}
|
||||
{#if step.toolId === ''}
|
||||
{#if step.toolId === ""}
|
||||
<div class="panel empty-slot">
|
||||
<header>
|
||||
<h3 class="heading-section">{t('toolPage.stepHeading', { n: index + 2 })}</h3>
|
||||
<h3 class="heading-section">
|
||||
{t("toolPage.stepHeading", { n: index + 2 })}
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
class="remove-step"
|
||||
aria-label={t('toolPage.removeStepAria')}
|
||||
aria-label={t("toolPage.removeStepAria")}
|
||||
onclick={() => removeChainStep(index)}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</header>
|
||||
<ToolSearch onSelect={(id) => applyChainTool(index, id)} chainableOnly />
|
||||
<ToolSearch
|
||||
onSelect={(id) => applyChainTool(index, id)}
|
||||
chainableOnly
|
||||
/>
|
||||
</div>
|
||||
{:else if getTool(step.toolId)}
|
||||
{@const stepTool = getTool(step.toolId)!}
|
||||
{#if stageVariant === 'inline'}
|
||||
{#if stageVariant === "inline"}
|
||||
{@const StepIcon = TOOL_ICONS[stepTool.id]}
|
||||
<ToolStage
|
||||
mode="chain"
|
||||
index={index}
|
||||
{index}
|
||||
tool={stepTool}
|
||||
bind:values={step.values}
|
||||
input={index === 0 ? result : (chainResults[index - 1] ?? null)}
|
||||
result={chainResults[index] ?? null}
|
||||
busy={status === 'processing'}
|
||||
busy={status === "processing"}
|
||||
isLast={index === chain.length - 1}
|
||||
onRemove={() => removeChainStep(index)}
|
||||
onError={showError}
|
||||
@@ -404,12 +440,15 @@
|
||||
<StepIcon size={14} strokeWidth={2} />
|
||||
</span>
|
||||
{/if}
|
||||
{t('chain.stepLabel', { n: index + 2, title: toolTitle(stepTool) })}
|
||||
{t("chain.stepLabel", {
|
||||
n: index + 2,
|
||||
title: toolTitle(stepTool),
|
||||
})}
|
||||
<button
|
||||
type="button"
|
||||
class="remove-step"
|
||||
aria-label={t('toolPage.removeStepAria')}
|
||||
title={t('toolPage.removeStepAria')}
|
||||
aria-label={t("toolPage.removeStepAria")}
|
||||
title={t("toolPage.removeStepAria")}
|
||||
onclick={() => removeChainStep(index)}
|
||||
>
|
||||
✕
|
||||
@@ -419,12 +458,12 @@
|
||||
</ToolStage>
|
||||
{:else}
|
||||
<ChainToolBlock
|
||||
index={index}
|
||||
{index}
|
||||
tool={stepTool}
|
||||
bind:values={step.values}
|
||||
input={index === 0 ? result : (chainResults[index - 1] ?? null)}
|
||||
result={chainResults[index] ?? null}
|
||||
busy={status === 'processing'}
|
||||
busy={status === "processing"}
|
||||
isLast={index === chain.length - 1}
|
||||
onRemove={() => removeChainStep(index)}
|
||||
onError={showError}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
<script lang="ts">
|
||||
import { outputOf, sanitizeParams, type ToolEntry } from '$lib/registry';
|
||||
import type { PixelImage } from '$lib/core/types';
|
||||
import { t } from '$lib/i18n/t';
|
||||
import { toolTitle } from '$lib/i18n/tool-strings';
|
||||
import DownloadButton from '../DownloadButton.svelte';
|
||||
import Button from '../ui/Button.svelte';
|
||||
import EmptyState from '../ui/EmptyState.svelte';
|
||||
import ParamsCard from '../tool/ParamsCard.svelte';
|
||||
import Preview from '../Preview.svelte';
|
||||
import { TOOL_ICONS } from '$lib/tools/tool-icons';
|
||||
import { outputOf, sanitizeParams, type ToolEntry } from "$lib/registry";
|
||||
import type { PixelImage } from "$lib/core/types";
|
||||
import { t } from "$lib/i18n/t";
|
||||
import { toolTitle } from "$lib/i18n/tool-strings";
|
||||
import DownloadButton from "../DownloadButton.svelte";
|
||||
import Button from "../ui/Button.svelte";
|
||||
import EmptyState from "../ui/EmptyState.svelte";
|
||||
import ParamsCard from "../tool/ParamsCard.svelte";
|
||||
import Preview from "../Preview.svelte";
|
||||
import { TOOL_ICONS } from "$lib/tools/tool-icons";
|
||||
|
||||
interface Props {
|
||||
index: number;
|
||||
@@ -35,7 +35,7 @@
|
||||
onRemove,
|
||||
onError,
|
||||
onAddStep,
|
||||
onRemoveChain
|
||||
onRemoveChain,
|
||||
}: Props = $props();
|
||||
|
||||
const format = $derived(outputOf(tool));
|
||||
@@ -47,14 +47,16 @@
|
||||
<div class="panel tool-stage">
|
||||
<span class="edge-legend step-legend">
|
||||
{#if StepIcon}
|
||||
<span class="step-icon" aria-hidden="true"><StepIcon size={14} strokeWidth={2} /></span>
|
||||
<span class="step-icon" aria-hidden="true"
|
||||
><StepIcon size={14} strokeWidth={2} /></span
|
||||
>
|
||||
{/if}
|
||||
{t('chain.stepLabel', { n: index + 2, title: toolTitle(tool) })}
|
||||
{t("chain.stepLabel", { n: index + 2, title: toolTitle(tool) })}
|
||||
<button
|
||||
type="button"
|
||||
class="remove"
|
||||
aria-label={t('chain.removeStepAria')}
|
||||
title={t('chain.removeStepAria')}
|
||||
aria-label={t("chain.removeStepAria")}
|
||||
title={t("chain.removeStepAria")}
|
||||
onclick={onRemove}
|
||||
>
|
||||
✕
|
||||
@@ -62,34 +64,44 @@
|
||||
</span>
|
||||
|
||||
<div class="cell">
|
||||
<span class="edge-legend cell-legend" aria-hidden="true">{t('chain.inputLegend')}</span>
|
||||
<span class="edge-legend cell-legend" aria-hidden="true"
|
||||
>{t("chain.inputLegend")}</span
|
||||
>
|
||||
<div class="cell-media">
|
||||
<Preview image={input} />
|
||||
</div>
|
||||
</div>
|
||||
<div class="cell">
|
||||
<span class="edge-legend cell-legend" aria-hidden="true">{t('chain.resultLegend')}</span>
|
||||
<span class="edge-legend cell-legend" aria-hidden="true"
|
||||
>{t("chain.resultLegend")}</span
|
||||
>
|
||||
{#if busy && !result}
|
||||
<div class="cell-media">
|
||||
<EmptyState title={t('chain.busyTitle')} hint={t('chain.busyHint')} />
|
||||
<EmptyState title={t("chain.busyTitle")} hint={t("chain.busyHint")} />
|
||||
</div>
|
||||
{:else}
|
||||
<div class="cell-media">
|
||||
<Preview image={result} />
|
||||
{#if busy}
|
||||
<span class="recalc" aria-live="polite">{t('resultCard.recalc')}</span>
|
||||
<span class="recalc" aria-live="polite"
|
||||
>{t("resultCard.recalc")}</span
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="actions-row">
|
||||
<DownloadButton
|
||||
image={result}
|
||||
format={format}
|
||||
{format}
|
||||
baseName="{index + 2}-{tool.id}"
|
||||
params={safeParams}
|
||||
{onError}
|
||||
/>
|
||||
<Button variant="secondary" fullWidth onclick={isLast ? onAddStep : onRemoveChain}>
|
||||
{isLast ? t('resultCard.nextTool') : t('resultCard.breakChain')}
|
||||
<Button
|
||||
variant="secondary"
|
||||
fullWidth
|
||||
onclick={isLast ? onAddStep : onRemoveChain}
|
||||
>
|
||||
{isLast ? t("resultCard.nextTool") : t("resultCard.breakChain")}
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -98,9 +110,11 @@
|
||||
|
||||
{#if tool.params.length > 0}
|
||||
<div class="params-sep">
|
||||
<span class="edge-legend" aria-hidden="true">{t('chain.paramsLegend')}</span>
|
||||
<span class="edge-legend" aria-hidden="true"
|
||||
>{t("chain.paramsLegend")}</span
|
||||
>
|
||||
</div>
|
||||
<ParamsCard tool={tool} params={tool.params} bind:values />
|
||||
<ParamsCard {tool} params={tool.params} bind:values />
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
<script lang="ts">
|
||||
import { Upload } from "@lucide/svelte";
|
||||
|
||||
interface Props {
|
||||
accept?: string;
|
||||
onfile?: (file: File) => void;
|
||||
}
|
||||
let { accept = "image/*", onfile }: Props = $props();
|
||||
|
||||
let dragging = $state(false);
|
||||
let input = $state<HTMLInputElement | null>(null);
|
||||
|
||||
function handleFiles(files: FileList | null | undefined) {
|
||||
const file = files?.[0];
|
||||
if (file) onfile?.(file);
|
||||
}
|
||||
|
||||
function onDrop(e: DragEvent) {
|
||||
e.preventDefault();
|
||||
dragging = false;
|
||||
handleFiles(e.dataTransfer?.files);
|
||||
}
|
||||
|
||||
function open() {
|
||||
input?.click();
|
||||
}
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="dropzone"
|
||||
class:dragging
|
||||
role="button"
|
||||
tabindex="0"
|
||||
ondragover={(e) => {
|
||||
e.preventDefault();
|
||||
dragging = true;
|
||||
}}
|
||||
ondragleave={() => (dragging = false)}
|
||||
ondrop={onDrop}
|
||||
onclick={open}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
open();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<input
|
||||
bind:this={input}
|
||||
type="file"
|
||||
{accept}
|
||||
hidden
|
||||
onchange={(e) => handleFiles((e.target as HTMLInputElement).files)}
|
||||
/>
|
||||
<Upload size={22} />
|
||||
<span class="dz-title">Drop a PNG here</span>
|
||||
<span class="dz-sub">or click to browse — processed locally</span>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.dropzone {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
min-height: 220px;
|
||||
padding: 2rem;
|
||||
border: 1px dashed var(--line);
|
||||
border-radius: var(--radius);
|
||||
color: var(--muted);
|
||||
background: var(--background);
|
||||
cursor: pointer;
|
||||
text-align: center;
|
||||
transition:
|
||||
border-color 0.15s ease,
|
||||
background 0.15s ease;
|
||||
}
|
||||
.dropzone:hover,
|
||||
.dropzone:focus-visible,
|
||||
.dropzone.dragging {
|
||||
border-color: var(--blue);
|
||||
color: var(--foreground);
|
||||
outline: none;
|
||||
}
|
||||
.dz-title {
|
||||
font: 600 0.9rem var(--font-mono);
|
||||
color: var(--foreground);
|
||||
}
|
||||
.dz-sub {
|
||||
font: 10px var(--font-mono);
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
</style>
|
||||
@@ -6,10 +6,11 @@
|
||||
icon: Component<{ size?: number; class?: string }>;
|
||||
label: string;
|
||||
onclick?: () => void;
|
||||
variant?: "ghost" | "solid" | "accent";
|
||||
variant?: "ghost" | "solid" | "accent" | "bare";
|
||||
size?: number;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
let {
|
||||
icon,
|
||||
label,
|
||||
@@ -57,6 +58,18 @@
|
||||
color: #042;
|
||||
border-color: var(--cyan);
|
||||
}
|
||||
.icon-btn--bare {
|
||||
width: auto;
|
||||
height: auto;
|
||||
padding: 6px;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
color: var(--muted);
|
||||
}
|
||||
.icon-btn--bare:hover:not(:disabled) {
|
||||
color: var(--foreground);
|
||||
border-color: transparent;
|
||||
}
|
||||
.icon-btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
<script lang="ts">
|
||||
import Field from "./Field.svelte";
|
||||
|
||||
interface Props {
|
||||
label: string;
|
||||
value: number;
|
||||
min?: number;
|
||||
max?: number;
|
||||
step?: number;
|
||||
oninput?: (value: number) => void;
|
||||
}
|
||||
let { label, value = $bindable(), min, max, step, oninput }: Props = $props();
|
||||
|
||||
function handle(e: Event) {
|
||||
value = Number((e.target as HTMLInputElement).value);
|
||||
oninput?.(value);
|
||||
}
|
||||
</script>
|
||||
|
||||
<Field {label}>
|
||||
<input
|
||||
class="number-field"
|
||||
type="number"
|
||||
{min}
|
||||
{max}
|
||||
{step}
|
||||
{value}
|
||||
oninput={handle}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<style>
|
||||
.number-field {
|
||||
width: 100%;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
color: var(--foreground);
|
||||
background: var(--background);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
padding: 0.35rem 0.5rem;
|
||||
}
|
||||
.number-field:focus {
|
||||
outline: none;
|
||||
border-color: var(--blue);
|
||||
}
|
||||
</style>
|
||||
@@ -1,6 +1,5 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from "svelte";
|
||||
import MonoLabel from "./MonoLabel.svelte";
|
||||
|
||||
interface Props {
|
||||
label: string;
|
||||
@@ -10,7 +9,7 @@
|
||||
</script>
|
||||
|
||||
<div class="preview-tile">
|
||||
<MonoLabel>{label}</MonoLabel>
|
||||
<span class="tile-label">{label}</span>
|
||||
<div class="tile-canvas">{@render children()}</div>
|
||||
</div>
|
||||
|
||||
@@ -24,6 +23,12 @@
|
||||
padding: 0.4rem;
|
||||
background: var(--panel);
|
||||
}
|
||||
.tile-label {
|
||||
font: 10px var(--font-mono);
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--blue);
|
||||
}
|
||||
.tile-canvas {
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
<style>
|
||||
.segmented {
|
||||
display: inline-flex;
|
||||
height: 32px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
@@ -44,11 +45,13 @@
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
font-size: 10px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
padding: 0.3rem 0.7rem;
|
||||
padding: 0 0.7rem;
|
||||
cursor: pointer;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
.segment + .segment {
|
||||
border-left: 1px solid var(--line);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from "svelte";
|
||||
import { GripVertical, X } from "@lucide/svelte";
|
||||
import Badge from "./Badge.svelte";
|
||||
|
||||
interface Props {
|
||||
index: number;
|
||||
@@ -17,7 +16,7 @@
|
||||
<div class="step-heading">
|
||||
<span class="drag" aria-hidden="true"><GripVertical size={16} /></span>
|
||||
<span class="step-index">{index.toString().padStart(2, "0")}</span>
|
||||
{#if type}<Badge tone="accent">{type}</Badge>{/if}
|
||||
{#if type}<span class="step-type">{type}</span>{/if}
|
||||
{#if title}<span class="step-title">{title}</span>{/if}
|
||||
<button
|
||||
type="button"
|
||||
@@ -54,13 +53,18 @@
|
||||
.step-index {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
color: var(--blue);
|
||||
}
|
||||
.step-title {
|
||||
font-weight: 600;
|
||||
font-size: 0.9rem;
|
||||
font: 600 15px var(--font-mono);
|
||||
color: var(--foreground);
|
||||
flex: 1;
|
||||
margin: 0;
|
||||
}
|
||||
.step-type {
|
||||
color: var(--muted);
|
||||
font: 10px var(--font-mono);
|
||||
letter-spacing: 0.12em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.step-remove {
|
||||
margin-left: auto;
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
<script lang="ts">
|
||||
import IconButton from "./IconButton.svelte";
|
||||
import Segmented from "./Segmented.svelte";
|
||||
import StatusDot from "./StatusDot.svelte";
|
||||
import { CircleHelp, Moon, Sun } from "@lucide/svelte";
|
||||
|
||||
interface Props {
|
||||
theme: "light" | "dark";
|
||||
crumb?: string;
|
||||
ontoggle: () => void;
|
||||
}
|
||||
|
||||
let { theme, ontoggle }: Props = $props();
|
||||
let { theme, crumb, ontoggle }: Props = $props();
|
||||
|
||||
let lang = $state("RU");
|
||||
</script>
|
||||
@@ -18,22 +18,36 @@
|
||||
<div class="brand">
|
||||
<span class="brand-mark">EP</span>
|
||||
<span>easy-png-tools</span>
|
||||
{#if crumb}<span class="version">{crumb}</span>{/if}
|
||||
</div>
|
||||
<div class="top-actions">
|
||||
<span class="status"><StatusDot /> AUTO PIPELINE</span>
|
||||
<IconButton icon={CircleHelp} label="Help" onclick={() => {}} />
|
||||
<IconButton
|
||||
icon={CircleHelp}
|
||||
label="Help"
|
||||
variant="bare"
|
||||
onclick={() => {}}
|
||||
/>
|
||||
<IconButton
|
||||
icon={theme === "light" ? Moon : Sun}
|
||||
label="Toggle theme"
|
||||
variant="bare"
|
||||
onclick={ontoggle}
|
||||
/>
|
||||
<Segmented
|
||||
bind:value={lang}
|
||||
options={[
|
||||
{ value: "RU", label: "RU" },
|
||||
{ value: "EN", label: "EN" },
|
||||
]}
|
||||
/>
|
||||
<div class="lang" role="group" aria-label="Language">
|
||||
<button
|
||||
type="button"
|
||||
class="lang-btn"
|
||||
class:active={lang === "RU"}
|
||||
onclick={() => (lang = "RU")}>RU</button
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="lang-btn"
|
||||
class:active={lang === "EN"}
|
||||
onclick={() => (lang = "EN")}>EN</button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -55,6 +69,7 @@
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font: 600 14px var(--font-mono);
|
||||
color: var(--foreground);
|
||||
}
|
||||
.brand-mark {
|
||||
background: var(--blue);
|
||||
@@ -65,6 +80,11 @@
|
||||
display: grid;
|
||||
place-items: center;
|
||||
}
|
||||
.version {
|
||||
font: 10px var(--font-mono);
|
||||
letter-spacing: 0.12em;
|
||||
color: var(--blue);
|
||||
}
|
||||
.top-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -78,4 +98,26 @@
|
||||
font: 10px var(--font-mono);
|
||||
letter-spacing: 0.08em;
|
||||
}
|
||||
.lang {
|
||||
display: inline-flex;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
}
|
||||
.lang-btn {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
font: 10px var(--font-mono);
|
||||
letter-spacing: 0.06em;
|
||||
padding: 6px 9px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.lang-btn + .lang-btn {
|
||||
border-left: 1px solid var(--line);
|
||||
}
|
||||
.lang-btn.active {
|
||||
background: var(--foreground);
|
||||
color: var(--background);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { TOOL_ICONS } from '$lib/tools/tool-icons';
|
||||
import { TOOL_ICONS } from "$lib/tools/tool-icons";
|
||||
|
||||
interface Props {
|
||||
toolId: string;
|
||||
@@ -18,7 +18,7 @@
|
||||
selected = false,
|
||||
href,
|
||||
onActivate,
|
||||
onHover
|
||||
onHover,
|
||||
}: Props = $props();
|
||||
|
||||
const Icon = $derived(TOOL_ICONS[toolId]);
|
||||
@@ -35,12 +35,7 @@
|
||||
{/snippet}
|
||||
|
||||
{#if href}
|
||||
<a
|
||||
{href}
|
||||
class="card"
|
||||
class:selected
|
||||
onmousemove={onHover}
|
||||
>
|
||||
<a {href} class="card" class:selected onmousemove={onHover}>
|
||||
{@render content()}
|
||||
</a>
|
||||
{:else}
|
||||
@@ -53,7 +48,7 @@
|
||||
onclick={onActivate}
|
||||
onmousemove={onHover}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter') onActivate?.();
|
||||
if (e.key === "Enter") onActivate?.();
|
||||
}}
|
||||
>
|
||||
{@render content()}
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
<script lang="ts">
|
||||
import { isChainable, TOOLS } from '$lib/registry';
|
||||
import { LOCALE_TAGS } from '$lib/i18n/dict';
|
||||
import { getLocale } from '$lib/i18n/locale.svelte';
|
||||
import { normalizeForSearch, scoreDoc } from '$lib/i18n/matching';
|
||||
import { t } from '$lib/i18n/t';
|
||||
import { toolDescription, toolSearchDoc, toolTitle } from '$lib/i18n/tool-strings';
|
||||
import ToolCard from './ToolCard.svelte';
|
||||
import { isChainable, TOOLS } from "$lib/registry";
|
||||
import { LOCALE_TAGS } from "$lib/i18n/dict";
|
||||
import { getLocale } from "$lib/i18n/locale.svelte";
|
||||
import { normalizeForSearch, scoreDoc } from "$lib/i18n/matching";
|
||||
import { t } from "$lib/i18n/t";
|
||||
import {
|
||||
toolDescription,
|
||||
toolSearchDoc,
|
||||
toolTitle,
|
||||
} from "$lib/i18n/tool-strings";
|
||||
import ToolCard from "./ToolCard.svelte";
|
||||
|
||||
interface Props {
|
||||
onSelect: (toolId: string) => void;
|
||||
@@ -15,9 +19,11 @@
|
||||
|
||||
let { onSelect, chainableOnly = false }: Props = $props();
|
||||
|
||||
const candidates = $derived(chainableOnly ? TOOLS.filter(isChainable) : TOOLS);
|
||||
const candidates = $derived(
|
||||
chainableOnly ? TOOLS.filter(isChainable) : TOOLS,
|
||||
);
|
||||
|
||||
let query = $state('');
|
||||
let query = $state("");
|
||||
let activeIndex = $state(0);
|
||||
let listOpen = $state(false);
|
||||
|
||||
@@ -40,7 +46,7 @@
|
||||
title: toolTitle(tool),
|
||||
description: toolDescription(tool),
|
||||
popularity: tool.popularity ?? 50,
|
||||
score: s
|
||||
score: s,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -49,31 +55,31 @@
|
||||
(a, b) =>
|
||||
b.score - a.score ||
|
||||
b.popularity - a.popularity ||
|
||||
collator.compare(a.title, b.title)
|
||||
collator.compare(a.title, b.title),
|
||||
);
|
||||
return found.slice(0, 12);
|
||||
});
|
||||
|
||||
function choose(id: string) {
|
||||
listOpen = false;
|
||||
query = '';
|
||||
query = "";
|
||||
activeIndex = 0;
|
||||
onSelect(id);
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent) {
|
||||
if (!listOpen || matches.length === 0) return;
|
||||
if (event.key === 'ArrowDown') {
|
||||
if (event.key === "ArrowDown") {
|
||||
event.preventDefault();
|
||||
activeIndex = (activeIndex + 1) % matches.length;
|
||||
} else if (event.key === 'ArrowUp') {
|
||||
} else if (event.key === "ArrowUp") {
|
||||
event.preventDefault();
|
||||
activeIndex = (activeIndex - 1 + matches.length) % matches.length;
|
||||
} else if (event.key === 'Enter') {
|
||||
} else if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
const match = matches[Math.min(activeIndex, matches.length - 1)];
|
||||
if (match) choose(match.id);
|
||||
} else if (event.key === 'Escape') {
|
||||
} else if (event.key === "Escape") {
|
||||
listOpen = false;
|
||||
}
|
||||
}
|
||||
@@ -89,14 +95,14 @@
|
||||
activeIndex = 0;
|
||||
}}
|
||||
onkeydown={onKeydown}
|
||||
placeholder={t('search.placeholder')}
|
||||
aria-label={t('search.aria')}
|
||||
placeholder={t("search.placeholder")}
|
||||
aria-label={t("search.aria")}
|
||||
role="combobox"
|
||||
aria-expanded={listOpen}
|
||||
aria-controls="tool-search-list"
|
||||
/>
|
||||
{#if listOpen && query.trim().length > 0 && matches.length === 0}
|
||||
<p class="none text-muted">{t('search.nothingFound')}</p>
|
||||
<p class="none text-muted">{t("search.nothingFound")}</p>
|
||||
{:else if listOpen && matches.length > 0}
|
||||
<div id="tool-search-list" class="cards" role="listbox">
|
||||
{#each matches as match, index (match.id)}
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
import { outputOf, sanitizeParams, type ToolEntry } from '$lib/registry';
|
||||
import type { ImageInfo } from '$lib/core/analyze';
|
||||
import type { PixelImage } from '$lib/core/types';
|
||||
import { t } from '$lib/i18n/t';
|
||||
import { toolTitle } from '$lib/i18n/tool-strings';
|
||||
import { TOOL_ICONS } from '$lib/tools/tool-icons';
|
||||
import DownloadButton from '../DownloadButton.svelte';
|
||||
import Button from '../ui/Button.svelte';
|
||||
import EmptyState from '../ui/EmptyState.svelte';
|
||||
import OverlayCard from '../tool/OverlayCard.svelte';
|
||||
import ParamsCard from '../tool/ParamsCard.svelte';
|
||||
import ResultCard from '../tool/ResultCard.svelte';
|
||||
import SourceCard from '../tool/SourceCard.svelte';
|
||||
import TextInputCard from '../tool/TextInputCard.svelte';
|
||||
import Preview from '../Preview.svelte';
|
||||
import type { StageStatus } from './stage-props';
|
||||
import type { Snippet } from "svelte";
|
||||
import { outputOf, sanitizeParams, type ToolEntry } from "$lib/registry";
|
||||
import type { ImageInfo } from "$lib/core/analyze";
|
||||
import type { PixelImage } from "$lib/core/types";
|
||||
import { t } from "$lib/i18n/t";
|
||||
import { toolTitle } from "$lib/i18n/tool-strings";
|
||||
import { TOOL_ICONS } from "$lib/tools/tool-icons";
|
||||
import DownloadButton from "../DownloadButton.svelte";
|
||||
import Button from "../ui/Button.svelte";
|
||||
import EmptyState from "../ui/EmptyState.svelte";
|
||||
import OverlayCard from "../tool/OverlayCard.svelte";
|
||||
import ParamsCard from "../tool/ParamsCard.svelte";
|
||||
import ResultCard from "../tool/ResultCard.svelte";
|
||||
import SourceCard from "../tool/SourceCard.svelte";
|
||||
import TextInputCard from "../tool/TextInputCard.svelte";
|
||||
import Preview from "../Preview.svelte";
|
||||
import type { StageStatus } from "./stage-props";
|
||||
|
||||
interface Props {
|
||||
mode: 'base' | 'chain';
|
||||
mode: "base" | "chain";
|
||||
header?: Snippet;
|
||||
tool: ToolEntry;
|
||||
source?: PixelImage | null;
|
||||
@@ -66,7 +66,7 @@
|
||||
source = null,
|
||||
displayImage = null,
|
||||
info = null,
|
||||
status = 'idle',
|
||||
status = "idle",
|
||||
isInfo = false,
|
||||
isSourceless = false,
|
||||
isTextSource = false,
|
||||
@@ -98,43 +98,59 @@
|
||||
onRemove,
|
||||
onError,
|
||||
onAddStep,
|
||||
onRemoveChain
|
||||
onRemoveChain,
|
||||
}: Props = $props();
|
||||
|
||||
const isChain = $derived(mode === 'chain');
|
||||
const isChain = $derived(mode === "chain");
|
||||
const format = $derived(outputOf(tool));
|
||||
const safeParams = $derived(sanitizeParams(tool, values ?? {}));
|
||||
const StepIcon = $derived(TOOL_ICONS[tool.id]);
|
||||
const showParams = $derived(
|
||||
mode === 'chain'
|
||||
mode === "chain"
|
||||
? tool.params.length > 0
|
||||
: (source !== null || isSourceless) &&
|
||||
!isInfo &&
|
||||
(tool.params.length > 0 || hasMask)
|
||||
(tool.params.length > 0 || hasMask),
|
||||
);
|
||||
|
||||
const leftLegend = $derived(isChain ? t('chain.inputLegend') : t('toolPage.legendSource'));
|
||||
const midLegend = $derived(isChain ? t('chain.paramsLegend') : t('toolPage.legendParams'));
|
||||
const leftLegend = $derived(
|
||||
isChain ? t("chain.inputLegend") : t("toolPage.legendSource"),
|
||||
);
|
||||
const midLegend = $derived(
|
||||
isChain ? t("chain.paramsLegend") : t("toolPage.legendParams"),
|
||||
);
|
||||
const rightLegend = $derived(
|
||||
isChain ? t('chain.resultLegend') : isInfo ? t('toolPage.legendSummary') : t('toolPage.legendResult')
|
||||
isChain
|
||||
? t("chain.resultLegend")
|
||||
: isInfo
|
||||
? t("toolPage.legendSummary")
|
||||
: t("toolPage.legendResult"),
|
||||
);
|
||||
</script>
|
||||
|
||||
<div class="panel stage-grid" class:no-params={!showParams} class:single={!isChain && !!isSourceless}>
|
||||
<div
|
||||
class="panel stage-grid"
|
||||
class:no-params={!showParams}
|
||||
class:single={!isChain && !!isSourceless}
|
||||
>
|
||||
{#if header}
|
||||
{@render header()}
|
||||
{/if}
|
||||
|
||||
{#if isChain}
|
||||
<section class="pane">
|
||||
<span class="edge-legend pane-legend" aria-hidden="true">{leftLegend}</span>
|
||||
<span class="edge-legend pane-legend" aria-hidden="true"
|
||||
>{leftLegend}</span
|
||||
>
|
||||
<div class="pane-body">
|
||||
<Preview image={input} />
|
||||
</div>
|
||||
</section>
|
||||
{:else if !isSourceless}
|
||||
<section class="pane">
|
||||
<span class="edge-legend pane-legend" aria-hidden="true">{leftLegend}</span>
|
||||
<span class="edge-legend pane-legend" aria-hidden="true"
|
||||
>{leftLegend}</span
|
||||
>
|
||||
<div class="pane-body">
|
||||
{#if isTextSource && !source}
|
||||
<TextInputCard onSubmit={(text) => onTextSubmit?.(text)} />
|
||||
@@ -162,34 +178,50 @@
|
||||
|
||||
{#if showParams}
|
||||
<section class="pane pane-params">
|
||||
<span class="edge-legend pane-legend" aria-hidden="true">{midLegend}</span>
|
||||
<span class="edge-legend pane-legend" aria-hidden="true">{midLegend}</span
|
||||
>
|
||||
<div class="pane-body">
|
||||
<ParamsCard {tool} params={tool.params} bind:values {pipetteTargetId} onPipetteToggle={(id) => handlePipetteToggle?.(id)} {hasMask} bind:showMask />
|
||||
<ParamsCard
|
||||
{tool}
|
||||
params={tool.params}
|
||||
bind:values
|
||||
{pipetteTargetId}
|
||||
onPipetteToggle={(id) => handlePipetteToggle?.(id)}
|
||||
{hasMask}
|
||||
bind:showMask
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<section class="pane">
|
||||
<span class="edge-legend pane-legend" aria-hidden="true">{rightLegend}</span>
|
||||
<span class="edge-legend pane-legend" aria-hidden="true">{rightLegend}</span
|
||||
>
|
||||
<div class="pane-body">
|
||||
{#if isChain}
|
||||
{#if busy && !result}
|
||||
<EmptyState title={t('chain.busyTitle')} hint={t('chain.busyHint')} />
|
||||
<EmptyState title={t("chain.busyTitle")} hint={t("chain.busyHint")} />
|
||||
{:else}
|
||||
<Preview image={result} />
|
||||
{#if busy}
|
||||
<span class="recalc" aria-live="polite">{t('resultCard.recalc')}</span>
|
||||
<span class="recalc" aria-live="polite"
|
||||
>{t("resultCard.recalc")}</span
|
||||
>
|
||||
{/if}
|
||||
<div class="actions-row">
|
||||
<DownloadButton
|
||||
image={result}
|
||||
format={format}
|
||||
{format}
|
||||
baseName="{index + 2}-{tool.id}"
|
||||
params={safeParams}
|
||||
onError={(e) => showError?.(e)}
|
||||
/>
|
||||
<Button variant="secondary" fullWidth onclick={isLast ? onAddStep : onRemoveChain}>
|
||||
{isLast ? t('resultCard.nextTool') : t('resultCard.breakChain')}
|
||||
<Button
|
||||
variant="secondary"
|
||||
fullWidth
|
||||
onclick={isLast ? onAddStep : onRemoveChain}
|
||||
>
|
||||
{isLast ? t("resultCard.nextTool") : t("resultCard.breakChain")}
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -199,11 +231,11 @@
|
||||
sourceLoaded={isSourceless ? true : !!source}
|
||||
{status}
|
||||
{result}
|
||||
displayImage={displayImage}
|
||||
{displayImage}
|
||||
{info}
|
||||
{isInfo}
|
||||
params={sanitized}
|
||||
textResult={textResult}
|
||||
{textResult}
|
||||
onChainToggle={canChainBase ? toggleChain : undefined}
|
||||
{hasChain}
|
||||
onDownloadError={(e) => showError?.(e)}
|
||||
@@ -276,7 +308,7 @@
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.pane-params :global(input[type='range']) {
|
||||
.pane-params :global(input[type="range"]) {
|
||||
order: -1;
|
||||
flex: 1 1 100%;
|
||||
min-width: 0;
|
||||
@@ -306,7 +338,10 @@
|
||||
|
||||
@media (min-width: 75rem) {
|
||||
.stage-grid:not(.no-params):not(.single) {
|
||||
grid-template-columns: minmax(0, 1fr) clamp(13rem, 17vw, 18rem) minmax(0, 1fr);
|
||||
grid-template-columns: minmax(0, 1fr) clamp(13rem, 17vw, 18rem) minmax(
|
||||
0,
|
||||
1fr
|
||||
);
|
||||
}
|
||||
|
||||
.stage-grid.no-params:not(.single),
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
<script lang="ts">
|
||||
import { t } from '$lib/i18n/t';
|
||||
import ParamsCard from '../tool/ParamsCard.svelte';
|
||||
import ResultCard from '../tool/ResultCard.svelte';
|
||||
import SourceCard from '../tool/SourceCard.svelte';
|
||||
import TextInputCard from '../tool/TextInputCard.svelte';
|
||||
import type { StageProps } from './stage-props';
|
||||
import { t } from "$lib/i18n/t";
|
||||
import ParamsCard from "../tool/ParamsCard.svelte";
|
||||
import ResultCard from "../tool/ResultCard.svelte";
|
||||
import SourceCard from "../tool/SourceCard.svelte";
|
||||
import TextInputCard from "../tool/TextInputCard.svelte";
|
||||
import type { StageProps } from "./stage-props";
|
||||
|
||||
let {
|
||||
tool,
|
||||
@@ -32,14 +32,16 @@
|
||||
handlePipetteToggle,
|
||||
handlePickColor,
|
||||
showError,
|
||||
errorMessage
|
||||
errorMessage,
|
||||
}: StageProps = $props();
|
||||
</script>
|
||||
|
||||
<div class="panel tool-block">
|
||||
<div class="tool-stage" class:single={isSourceless}>
|
||||
{#if !isSourceless}
|
||||
<span class="edge-legend source-legend" aria-hidden="true">{t('toolPage.legendSource')}</span>
|
||||
<span class="edge-legend source-legend" aria-hidden="true"
|
||||
>{t("toolPage.legendSource")}</span
|
||||
>
|
||||
<div class="cell">
|
||||
{#if isTextSource && !source}
|
||||
<TextInputCard onSubmit={onTextSubmit} />
|
||||
@@ -56,7 +58,7 @@
|
||||
</div>
|
||||
{/if}
|
||||
<span class="edge-legend result-legend" aria-hidden="true">
|
||||
{isInfo ? t('toolPage.legendSummary') : t('toolPage.legendResult')}
|
||||
{isInfo ? t("toolPage.legendSummary") : t("toolPage.legendResult")}
|
||||
</span>
|
||||
<div class="cell">
|
||||
<ResultCard
|
||||
@@ -64,11 +66,11 @@
|
||||
sourceLoaded={isSourceless ? true : !!source}
|
||||
{status}
|
||||
{result}
|
||||
displayImage={displayImage}
|
||||
{displayImage}
|
||||
{info}
|
||||
{isInfo}
|
||||
params={sanitized}
|
||||
textResult={textResult}
|
||||
{textResult}
|
||||
onChainToggle={canChainBase ? toggleChain : undefined}
|
||||
{hasChain}
|
||||
onDownloadError={showError}
|
||||
@@ -78,7 +80,9 @@
|
||||
|
||||
{#if (source || isSourceless) && !isInfo && (tool.params.length > 0 || hasMask)}
|
||||
<div class="params-sep">
|
||||
<span class="edge-legend" aria-hidden="true">{t('toolPage.legendParams')}</span>
|
||||
<span class="edge-legend" aria-hidden="true"
|
||||
>{t("toolPage.legendParams")}</span
|
||||
>
|
||||
</div>
|
||||
<ParamsCard
|
||||
{tool}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { ImageInfo } from '$lib/core/analyze';
|
||||
import type { PixelImage } from '$lib/core/types';
|
||||
import type { ToolEntry } from '$lib/registry';
|
||||
import type { ImageInfo } from "$lib/core/analyze";
|
||||
import type { PixelImage } from "$lib/core/types";
|
||||
import type { ToolEntry } from "$lib/registry";
|
||||
|
||||
export type StageStatus = 'idle' | 'loaded' | 'processing' | 'error';
|
||||
export type StageStatus = "idle" | "loaded" | "processing" | "error";
|
||||
|
||||
export interface StageProps {
|
||||
tool: ToolEntry;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<script lang="ts">
|
||||
import { t } from '$lib/i18n/t';
|
||||
import type { PixelImage } from '$lib/core/types';
|
||||
import DropZone from '../DropZone.svelte';
|
||||
import Preview from '../Preview.svelte';
|
||||
import Button from '../ui/Button.svelte';
|
||||
import { t } from "$lib/i18n/t";
|
||||
import type { PixelImage } from "$lib/core/types";
|
||||
import DropZone from "../DropZone.svelte";
|
||||
import Preview from "../Preview.svelte";
|
||||
import Button from "../ui/Button.svelte";
|
||||
|
||||
interface Props {
|
||||
overlay: PixelImage | null;
|
||||
@@ -16,13 +16,17 @@
|
||||
</script>
|
||||
|
||||
<div class="overlay-card">
|
||||
<span class="edge-legend overlay-legend" aria-hidden="true">{t('ui.overlayTitle')}</span>
|
||||
<span class="edge-legend overlay-legend" aria-hidden="true"
|
||||
>{t("ui.overlayTitle")}</span
|
||||
>
|
||||
{#if !overlay}
|
||||
<DropZone {onFile} {onError} label={t('ui.overlayDrop')} />
|
||||
<DropZone {onFile} {onError} label={t("ui.overlayDrop")} />
|
||||
{:else}
|
||||
<div class="preview-wrap">
|
||||
<Preview image={overlay} />
|
||||
<Button variant="secondary" onclick={onClear}>{t('ui.overlayRemove')}</Button>
|
||||
<Button variant="secondary" onclick={onClear}
|
||||
>{t("ui.overlayRemove")}</Button
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import ParamForm from '../ParamForm.svelte';
|
||||
import type { ParamDef, ToolEntry } from '$lib/registry';
|
||||
import { t } from '$lib/i18n/t';
|
||||
import ParamForm from "../ParamForm.svelte";
|
||||
import type { ParamDef, ToolEntry } from "$lib/registry";
|
||||
import { t } from "$lib/i18n/t";
|
||||
|
||||
interface Props {
|
||||
tool: ToolEntry;
|
||||
@@ -20,7 +20,7 @@
|
||||
pipetteTargetId = null,
|
||||
onPipetteToggle,
|
||||
hasMask = false,
|
||||
showMask = $bindable(false)
|
||||
showMask = $bindable(false),
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
@@ -36,7 +36,7 @@
|
||||
bind:showMask
|
||||
/>
|
||||
{:else}
|
||||
<p class="hint text-caption text-muted">{t('paramsCard.noParams')}</p>
|
||||
<p class="hint text-caption text-muted">{t("paramsCard.noParams")}</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import type { PixelImage } from '$lib/core/types';
|
||||
import type { PixelImage } from "$lib/core/types";
|
||||
|
||||
interface Props {
|
||||
image: PixelImage;
|
||||
@@ -25,10 +25,16 @@
|
||||
|
||||
function ensureSource(): HTMLCanvasElement | null {
|
||||
if (!srcCanvas || srcKey !== image) {
|
||||
srcCanvas = document.createElement('canvas');
|
||||
srcCanvas = document.createElement("canvas");
|
||||
srcCanvas.width = image.width;
|
||||
srcCanvas.height = image.height;
|
||||
srcCanvas.getContext('2d')?.putImageData(new ImageData(image.data, image.width, image.height), 0, 0);
|
||||
srcCanvas
|
||||
.getContext("2d")
|
||||
?.putImageData(
|
||||
new ImageData(image.data, image.width, image.height),
|
||||
0,
|
||||
0,
|
||||
);
|
||||
srcKey = image;
|
||||
}
|
||||
return srcCanvas;
|
||||
@@ -38,8 +44,12 @@
|
||||
return Math.min(max, Math.max(min, v));
|
||||
}
|
||||
|
||||
const blockX = $derived(clamp(px - HALF, 0, Math.max(0, image.width - BLOCK)));
|
||||
const blockY = $derived(clamp(py - HALF, 0, Math.max(0, image.height - BLOCK)));
|
||||
const blockX = $derived(
|
||||
clamp(px - HALF, 0, Math.max(0, image.width - BLOCK)),
|
||||
);
|
||||
const blockY = $derived(
|
||||
clamp(py - HALF, 0, Math.max(0, image.height - BLOCK)),
|
||||
);
|
||||
const flipBelow = $derived(clientY < SIZE + 24);
|
||||
|
||||
$effect(() => {
|
||||
@@ -47,12 +57,12 @@
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
loupeCanvas.width = SIZE * dpr;
|
||||
loupeCanvas.height = SIZE * dpr;
|
||||
const ctx = loupeCanvas.getContext('2d');
|
||||
const ctx = loupeCanvas.getContext("2d");
|
||||
const src = ensureSource();
|
||||
if (!ctx || !src) return;
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
ctx.imageSmoothingEnabled = false;
|
||||
ctx.fillStyle = '#111318';
|
||||
ctx.fillStyle = "#111318";
|
||||
ctx.fillRect(0, 0, SIZE, SIZE);
|
||||
ctx.drawImage(
|
||||
src,
|
||||
@@ -63,11 +73,16 @@
|
||||
CENTER + (blockX - px) * ZOOM,
|
||||
CENTER + (blockY - py) * ZOOM,
|
||||
BLOCK * ZOOM,
|
||||
BLOCK * ZOOM
|
||||
BLOCK * ZOOM,
|
||||
);
|
||||
ctx.strokeStyle = 'rgba(255,255,255,0.9)';
|
||||
ctx.strokeStyle = "rgba(255,255,255,0.9)";
|
||||
ctx.lineWidth = 1;
|
||||
ctx.strokeRect(CENTER - ZOOM / 2 + 0.5, CENTER - ZOOM / 2 + 0.5, ZOOM, ZOOM);
|
||||
ctx.strokeRect(
|
||||
CENTER - ZOOM / 2 + 0.5,
|
||||
CENTER - ZOOM / 2 + 0.5,
|
||||
ZOOM,
|
||||
ZOOM,
|
||||
);
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -77,7 +92,8 @@
|
||||
style="left:{clientX}px;top:{clientY}px"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<canvas bind:this={loupeCanvas} style="width:{SIZE}px;height:{SIZE}px"></canvas>
|
||||
<canvas bind:this={loupeCanvas} style="width:{SIZE}px;height:{SIZE}px"
|
||||
></canvas>
|
||||
<p class="hex">{hex}</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
<script lang="ts">
|
||||
import Button from '../ui/Button.svelte';
|
||||
import DownloadButton from '../DownloadButton.svelte';
|
||||
import EmptyState from '../ui/EmptyState.svelte';
|
||||
import InfoPanel from '../InfoPanel.svelte';
|
||||
import Preview from '../Preview.svelte';
|
||||
import TextResult from './TextResult.svelte';
|
||||
import type { ImageInfo } from '$lib/core/analyze';
|
||||
import type { PixelImage } from '$lib/core/types';
|
||||
import { outputOf, type ToolEntry } from '$lib/registry';
|
||||
import { t } from '$lib/i18n/t';
|
||||
import Button from "../ui/Button.svelte";
|
||||
import DownloadButton from "../DownloadButton.svelte";
|
||||
import EmptyState from "../ui/EmptyState.svelte";
|
||||
import InfoPanel from "../InfoPanel.svelte";
|
||||
import Preview from "../Preview.svelte";
|
||||
import TextResult from "./TextResult.svelte";
|
||||
import type { ImageInfo } from "$lib/core/analyze";
|
||||
import type { PixelImage } from "$lib/core/types";
|
||||
import { outputOf, type ToolEntry } from "$lib/registry";
|
||||
import { t } from "$lib/i18n/t";
|
||||
|
||||
type Status = 'idle' | 'loaded' | 'processing' | 'error';
|
||||
type Status = "idle" | "loaded" | "processing" | "error";
|
||||
|
||||
interface Props {
|
||||
tool: ToolEntry;
|
||||
@@ -39,20 +39,23 @@
|
||||
textResult,
|
||||
onChainToggle,
|
||||
hasChain = false,
|
||||
onDownloadError
|
||||
onDownloadError,
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
<div class="container">
|
||||
{#if !sourceLoaded}
|
||||
<div class="media">
|
||||
<EmptyState title={t('resultCard.emptyTitle')} hint={t('resultCard.emptyHint')} />
|
||||
<EmptyState
|
||||
title={t("resultCard.emptyTitle")}
|
||||
hint={t("resultCard.emptyHint")}
|
||||
/>
|
||||
</div>
|
||||
{:else if !isInfo && status === 'processing' && !result}
|
||||
{:else if !isInfo && status === "processing" && !result}
|
||||
<div class="media">
|
||||
<EmptyState
|
||||
title={t('resultCard.processingTitle')}
|
||||
hint={t('resultCard.processingHint')}
|
||||
title={t("resultCard.processingTitle")}
|
||||
hint={t("resultCard.processingHint")}
|
||||
/>
|
||||
</div>
|
||||
{:else if isInfo}
|
||||
@@ -61,7 +64,7 @@
|
||||
<InfoPanel {info} />
|
||||
{/if}
|
||||
</div>
|
||||
{:else if tool.resultType === 'text'}
|
||||
{:else if tool.resultType === "text"}
|
||||
<div class="media">
|
||||
{#if textResult !== null}
|
||||
<TextResult text={textResult} filename={tool.id} toolId={tool.id} />
|
||||
@@ -70,8 +73,8 @@
|
||||
{:else}
|
||||
<div class="media">
|
||||
<Preview image={displayImage} />
|
||||
{#if status === 'processing'}
|
||||
<span class="recalc" aria-live="polite">{t('resultCard.recalc')}</span>
|
||||
{#if status === "processing"}
|
||||
<span class="recalc" aria-live="polite">{t("resultCard.recalc")}</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="actions-row">
|
||||
@@ -84,7 +87,7 @@
|
||||
/>
|
||||
{#if onChainToggle}
|
||||
<Button variant="secondary" fullWidth onclick={onChainToggle}>
|
||||
{hasChain ? t('resultCard.breakChain') : t('resultCard.nextTool')}
|
||||
{hasChain ? t("resultCard.breakChain") : t("resultCard.nextTool")}
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
<script lang="ts">
|
||||
import type { PixelImage } from '$lib/core/types';
|
||||
import { t } from '$lib/i18n/t';
|
||||
import DropOverlay from '../DropOverlay.svelte';
|
||||
import DropZone from '../DropZone.svelte';
|
||||
import Preview from '../Preview.svelte';
|
||||
import Button from '../ui/Button.svelte';
|
||||
import type { PixelImage } from "$lib/core/types";
|
||||
import { t } from "$lib/i18n/t";
|
||||
import DropOverlay from "../DropOverlay.svelte";
|
||||
import DropZone from "../DropZone.svelte";
|
||||
import Preview from "../Preview.svelte";
|
||||
import Button from "../ui/Button.svelte";
|
||||
|
||||
interface Props {
|
||||
source: PixelImage | null;
|
||||
@@ -15,7 +15,14 @@
|
||||
onPickColor?: (hex: string) => void;
|
||||
}
|
||||
|
||||
let { source, onFile, onError, onReset, pipetteActive = false, onPickColor }: Props = $props();
|
||||
let {
|
||||
source,
|
||||
onFile,
|
||||
onError,
|
||||
onReset,
|
||||
pipetteActive = false,
|
||||
onPickColor,
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
<div class="container">
|
||||
@@ -24,9 +31,11 @@
|
||||
{:else}
|
||||
<DropOverlay {onFile} {onError}>
|
||||
<div class="media">
|
||||
<Preview image={source} pipetteActive={pipetteActive} onPickColor={onPickColor} />
|
||||
<Preview image={source} {pipetteActive} {onPickColor} />
|
||||
</div>
|
||||
<Button variant="secondary" onclick={onReset}>{t('sourceCard.replaceImage')}</Button>
|
||||
<Button variant="secondary" onclick={onReset}
|
||||
>{t("sourceCard.replaceImage")}</Button
|
||||
>
|
||||
</DropOverlay>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import Button from '../ui/Button.svelte';
|
||||
import { t } from '$lib/i18n/t';
|
||||
import Button from "../ui/Button.svelte";
|
||||
import { t } from "$lib/i18n/t";
|
||||
|
||||
interface Props {
|
||||
onSubmit: (text: string) => void;
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
let { onSubmit }: Props = $props();
|
||||
|
||||
let text = $state('');
|
||||
let text = $state("");
|
||||
|
||||
function submit() {
|
||||
if (text.trim().length === 0) return;
|
||||
@@ -17,16 +17,19 @@
|
||||
</script>
|
||||
|
||||
<div class="container">
|
||||
<h2 class="heading-section">{t('textInput.heading')}</h2>
|
||||
<h2 class="heading-section">{t("textInput.heading")}</h2>
|
||||
<textarea
|
||||
class="input"
|
||||
rows="8"
|
||||
bind:value={text}
|
||||
placeholder={t('textInput.placeholder')}
|
||||
aria-label={t('textInput.aria')}
|
||||
></textarea>
|
||||
<Button variant="secondary" onclick={submit} disabled={text.trim().length === 0}>
|
||||
{t('textInput.decode')}
|
||||
placeholder={t("textInput.placeholder")}
|
||||
aria-label={t("textInput.aria")}></textarea>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onclick={submit}
|
||||
disabled={text.trim().length === 0}
|
||||
>
|
||||
{t("textInput.decode")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { downloadBlob } from '$lib/core/io';
|
||||
import { t } from '$lib/i18n/t';
|
||||
import { getMergedDict } from '$lib/i18n/locale.svelte';
|
||||
import { downloadBlob } from "$lib/core/io";
|
||||
import { t } from "$lib/i18n/t";
|
||||
import { getMergedDict } from "$lib/i18n/locale.svelte";
|
||||
|
||||
interface Props {
|
||||
text: string;
|
||||
@@ -12,7 +12,7 @@
|
||||
let { text, filename, toolId }: Props = $props();
|
||||
|
||||
const shown = $derived(
|
||||
toolId ? (getMergedDict().tools[toolId]?.results?.[text] ?? text) : text
|
||||
toolId ? (getMergedDict().tools[toolId]?.results?.[text] ?? text) : text,
|
||||
);
|
||||
|
||||
let copied = $state(false);
|
||||
@@ -24,17 +24,24 @@
|
||||
}
|
||||
|
||||
function download() {
|
||||
downloadBlob(new Blob([shown], { type: 'text/plain' }), `${filename}.txt`);
|
||||
downloadBlob(new Blob([shown], { type: "text/plain" }), `${filename}.txt`);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="panel text-result">
|
||||
<textarea class="output" rows="10" readonly value={shown} aria-label={t('textResult.outputAria')}></textarea>
|
||||
<textarea
|
||||
class="output"
|
||||
rows="10"
|
||||
readonly
|
||||
value={shown}
|
||||
aria-label={t("textResult.outputAria")}></textarea>
|
||||
<div class="actions">
|
||||
<button type="button" class="secondary" onclick={copy}>
|
||||
{copied ? t('textResult.copied') : t('textResult.copy')}
|
||||
{copied ? t("textResult.copied") : t("textResult.copy")}
|
||||
</button>
|
||||
<button type="button" class="primary" onclick={download}>{t('textResult.downloadTxt')}</button>
|
||||
<button type="button" class="primary" onclick={download}
|
||||
>{t("textResult.downloadTxt")}</button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
import type { Snippet } from "svelte";
|
||||
|
||||
interface Props {
|
||||
variant?: 'primary' | 'secondary';
|
||||
type?: 'button' | 'submit';
|
||||
variant?: "primary" | "secondary";
|
||||
type?: "button" | "submit";
|
||||
disabled?: boolean;
|
||||
busy?: boolean;
|
||||
busyText?: string;
|
||||
@@ -13,14 +13,14 @@
|
||||
}
|
||||
|
||||
let {
|
||||
variant = 'primary',
|
||||
type = 'button',
|
||||
variant = "primary",
|
||||
type = "button",
|
||||
disabled = false,
|
||||
busy = false,
|
||||
busyText = '',
|
||||
busyText = "",
|
||||
fullWidth = false,
|
||||
onclick,
|
||||
children
|
||||
children,
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
class={fullWidth ? `${variant} fullwidth` : variant}
|
||||
aria-busy={busy}
|
||||
disabled={disabled || busy}
|
||||
onclick={onclick}
|
||||
{onclick}
|
||||
>
|
||||
{#if busy && busyText}
|
||||
{busyText}
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
<div class="checkbox-row">
|
||||
<label class="checkbox" for={id}>
|
||||
<input id={id} type="checkbox" bind:checked />
|
||||
<input {id} type="checkbox" bind:checked />
|
||||
{label}
|
||||
</label>
|
||||
{#if hint}
|
||||
@@ -38,7 +38,7 @@
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
input[type='checkbox'] {
|
||||
input[type="checkbox"] {
|
||||
width: 1rem;
|
||||
height: 1rem;
|
||||
cursor: pointer;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import Field from './Field.svelte';
|
||||
import { t } from '$lib/i18n/t';
|
||||
import Field from "./Field.svelte";
|
||||
import { t } from "$lib/i18n/t";
|
||||
|
||||
interface Props {
|
||||
id: string;
|
||||
@@ -11,20 +11,26 @@
|
||||
onPipetteToggle?: () => void;
|
||||
}
|
||||
|
||||
let { id, label, value = $bindable('#000000'), hint, pipetteActive = false, onPipetteToggle }:
|
||||
Props = $props();
|
||||
let {
|
||||
id,
|
||||
label,
|
||||
value = $bindable("#000000"),
|
||||
hint,
|
||||
pipetteActive = false,
|
||||
onPipetteToggle,
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
<Field {id} {label} {hint}>
|
||||
<div class="row">
|
||||
<input id={id} class="control swatch" type="color" bind:value />
|
||||
<input {id} class="control swatch" type="color" bind:value />
|
||||
{#if onPipetteToggle}
|
||||
<button
|
||||
type="button"
|
||||
class="pipette"
|
||||
aria-label={t('ui.pipette')}
|
||||
aria-label={t("ui.pipette")}
|
||||
aria-pressed={pipetteActive}
|
||||
title={t('ui.pipette')}
|
||||
title={t("ui.pipette")}
|
||||
onclick={onPipetteToggle}
|
||||
>
|
||||
◎
|
||||
@@ -73,7 +79,7 @@
|
||||
color: var(--link);
|
||||
}
|
||||
|
||||
.pipette[aria-pressed='true'] {
|
||||
.pipette[aria-pressed="true"] {
|
||||
border-color: var(--link);
|
||||
color: var(--link);
|
||||
background: color-mix(in srgb, var(--accent) 10%, var(--surface));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
import type { Snippet } from "svelte";
|
||||
|
||||
interface Props {
|
||||
title: string;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
import type { Snippet } from "svelte";
|
||||
|
||||
interface Props {
|
||||
id: string;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import Field from './Field.svelte';
|
||||
import Field from "./Field.svelte";
|
||||
|
||||
interface Props {
|
||||
id: string;
|
||||
@@ -9,11 +9,11 @@
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
let { id, label, value = $bindable(''), options, hint }: Props = $props();
|
||||
let { id, label, value = $bindable(""), options, hint }: Props = $props();
|
||||
</script>
|
||||
|
||||
<Field {id} {label} {hint}>
|
||||
<select id={id} class="control" bind:value>
|
||||
<select {id} class="control" bind:value>
|
||||
{#each options as option (option.value)}
|
||||
<option value={option.value}>{option.label}</option>
|
||||
{/each}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import Field from './Field.svelte';
|
||||
import { t } from '$lib/i18n/t';
|
||||
import Field from "./Field.svelte";
|
||||
import { t } from "$lib/i18n/t";
|
||||
|
||||
interface Props {
|
||||
id: string;
|
||||
@@ -21,7 +21,7 @@
|
||||
max,
|
||||
step,
|
||||
default: defaultValue,
|
||||
hint
|
||||
hint,
|
||||
}: Props = $props();
|
||||
|
||||
function decrement() {
|
||||
@@ -38,18 +38,30 @@
|
||||
if (defaultValue !== undefined) value = defaultValue;
|
||||
}
|
||||
|
||||
const resetDisabled = $derived(defaultValue === undefined || value === defaultValue);
|
||||
const resetDisabled = $derived(
|
||||
defaultValue === undefined || value === defaultValue,
|
||||
);
|
||||
</script>
|
||||
|
||||
<Field {id} {label} {hint}>
|
||||
<div class="row">
|
||||
<button type="button" class="step" aria-label={t('ui.decrease')} onclick={decrement}>−</button>
|
||||
<input id={id} type="range" min={min} max={max} step={step} bind:value />
|
||||
<button type="button" class="step" aria-label={t('ui.increase')} onclick={increment}>+</button>
|
||||
<button
|
||||
type="button"
|
||||
class="step"
|
||||
aria-label={t('ui.reset')}
|
||||
aria-label={t("ui.decrease")}
|
||||
onclick={decrement}>−</button
|
||||
>
|
||||
<input {id} type="range" {min} {max} {step} bind:value />
|
||||
<button
|
||||
type="button"
|
||||
class="step"
|
||||
aria-label={t("ui.increase")}
|
||||
onclick={increment}>+</button
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="step"
|
||||
aria-label={t("ui.reset")}
|
||||
disabled={resetDisabled}
|
||||
onclick={reset}
|
||||
>
|
||||
@@ -68,7 +80,7 @@
|
||||
max-width: 22rem;
|
||||
}
|
||||
|
||||
input[type='range'] {
|
||||
input[type="range"] {
|
||||
flex: 1;
|
||||
min-width: 3rem;
|
||||
accent-color: var(--link);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
<script lang="ts">
|
||||
import Field from './Field.svelte';
|
||||
import Field from "./Field.svelte";
|
||||
|
||||
interface Props {
|
||||
id: string;
|
||||
label: string;
|
||||
value?: string | number;
|
||||
type?: 'number' | 'text';
|
||||
type?: "number" | "text";
|
||||
min?: number;
|
||||
max?: number;
|
||||
step?: number;
|
||||
@@ -13,12 +13,30 @@
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
let { id, label, value = $bindable(''), type = 'text', min, max, step, hint, placeholder }: Props =
|
||||
$props();
|
||||
let {
|
||||
id,
|
||||
label,
|
||||
value = $bindable(""),
|
||||
type = "text",
|
||||
min,
|
||||
max,
|
||||
step,
|
||||
hint,
|
||||
placeholder,
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
<Field {id} {label} {hint}>
|
||||
<input class="control" {id} {type} min={min} max={max} step={step} {placeholder} bind:value />
|
||||
<input
|
||||
class="control"
|
||||
{id}
|
||||
{type}
|
||||
{min}
|
||||
{max}
|
||||
{step}
|
||||
{placeholder}
|
||||
bind:value
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<style>
|
||||
|
||||
@@ -1,39 +1,53 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { rotate90, sampleBilinear } from './geometry';
|
||||
import { rotateFreeImage, skewImage, transformImage, zoomImage } from './affine';
|
||||
import { makeImage } from './test-helpers';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { rotate90, sampleBilinear } from "./geometry";
|
||||
import {
|
||||
rotateFreeImage,
|
||||
skewImage,
|
||||
transformImage,
|
||||
zoomImage,
|
||||
} from "./affine";
|
||||
import { makeImage } from "./test-helpers";
|
||||
|
||||
describe('sampleBilinear', () => {
|
||||
it('целые координаты возвращают точный пиксель', () => {
|
||||
describe("sampleBilinear", () => {
|
||||
it("целые координаты возвращают точный пиксель", () => {
|
||||
const img = makeImage(2, 1, [
|
||||
[255, 0, 0, 255],
|
||||
[0, 0, 255, 255]
|
||||
[0, 0, 255, 255],
|
||||
]);
|
||||
expect(sampleBilinear(img, 0, 0)).toEqual([255, 0, 0, 255]);
|
||||
expect(sampleBilinear(img, 1, 0)).toEqual([0, 0, 255, 255]);
|
||||
});
|
||||
|
||||
it('дробная координата интерполирует', () => {
|
||||
it("дробная координата интерполирует", () => {
|
||||
const img = makeImage(2, 1, [
|
||||
[0, 0, 0, 255],
|
||||
[200, 200, 200, 255]
|
||||
[200, 200, 200, 255],
|
||||
]);
|
||||
const [r] = sampleBilinear(img, 0.5, 0);
|
||||
expect(r).toBeCloseTo(100, 0);
|
||||
});
|
||||
|
||||
it('координаты за краем клампятся', () => {
|
||||
it("координаты за краем клампятся", () => {
|
||||
const img = makeImage(1, 1, [[7, 7, 7, 255]]);
|
||||
expect(sampleBilinear(img, -10, -10)).toEqual([7, 7, 7, 255]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rotateFreeImage', () => {
|
||||
it('поворот на 180° даёт размеры не меньше исходных и непустой результат', () => {
|
||||
describe("rotateFreeImage", () => {
|
||||
it("поворот на 180° даёт размеры не меньше исходных и непустой результат", () => {
|
||||
const img = makeImage(4, 3, [
|
||||
[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 0, 255],
|
||||
[128, 128, 128, 255], [64, 64, 64, 255], [32, 32, 32, 255], [200, 200, 200, 255],
|
||||
[10, 20, 30, 255], [40, 50, 60, 255], [70, 80, 90, 255], [100, 100, 100, 255]
|
||||
[255, 0, 0, 255],
|
||||
[0, 255, 0, 255],
|
||||
[0, 0, 255, 255],
|
||||
[255, 255, 0, 255],
|
||||
[128, 128, 128, 255],
|
||||
[64, 64, 64, 255],
|
||||
[32, 32, 32, 255],
|
||||
[200, 200, 200, 255],
|
||||
[10, 20, 30, 255],
|
||||
[40, 50, 60, 255],
|
||||
[70, 80, 90, 255],
|
||||
[100, 100, 100, 255],
|
||||
]);
|
||||
const out = rotateFreeImage(img, 180);
|
||||
expect(out.width).toBeGreaterThanOrEqual(img.width);
|
||||
@@ -46,12 +60,8 @@ describe('rotateFreeImage', () => {
|
||||
expect(opaque / total).toBeGreaterThan(0.8);
|
||||
});
|
||||
|
||||
it('поворот квадрата на 360° близок к оригиналу', () => {
|
||||
const img = makeImage(
|
||||
5,
|
||||
5,
|
||||
new Array(25).fill([200, 100, 50, 255])
|
||||
);
|
||||
it("поворот квадрата на 360° близок к оригиналу", () => {
|
||||
const img = makeImage(5, 5, new Array(25).fill([200, 100, 50, 255]));
|
||||
const out = rotateFreeImage(img, 360);
|
||||
expect(out.width).toBeGreaterThanOrEqual(5);
|
||||
expect(out.height).toBeGreaterThanOrEqual(5);
|
||||
@@ -59,15 +69,17 @@ describe('rotateFreeImage', () => {
|
||||
for (let x = 0; x < 5; x++) {
|
||||
const di = (y * out.width + x) * 4;
|
||||
for (let ch = 0; ch < 4; ch++) {
|
||||
expect(Math.abs(out.data[di + ch] - img.data[(y * 5 + x) * 4 + ch])).toBeLessThanOrEqual(4);
|
||||
expect(
|
||||
Math.abs(out.data[di + ch] - img.data[(y * 5 + x) * 4 + ch]),
|
||||
).toBeLessThanOrEqual(4);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('skewImage', () => {
|
||||
it('наклон X=45° расширяет холст до w+h−1 и сдвигает строки вправо', () => {
|
||||
describe("skewImage", () => {
|
||||
it("наклон X=45° расширяет холст до w+h−1 и сдвигает строки вправо", () => {
|
||||
const img = makeImage(2, 2, new Array(4).fill([255, 0, 0, 255]));
|
||||
const out = skewImage(img, 45, 0);
|
||||
expect(out.width).toBe(3);
|
||||
@@ -76,16 +88,20 @@ describe('skewImage', () => {
|
||||
for (let i = 3; i < out.data.length; i += 4) {
|
||||
if (out.data[i] === 255) {
|
||||
opaque++;
|
||||
expect([out.data[i - 3], out.data[i - 2], out.data[i - 1]]).toEqual([255, 0, 0]);
|
||||
expect([out.data[i - 3], out.data[i - 2], out.data[i - 1]]).toEqual([
|
||||
255, 0, 0,
|
||||
]);
|
||||
}
|
||||
}
|
||||
expect(opaque).toBe(4);
|
||||
});
|
||||
|
||||
it('углы 0° — тождественное преобразование', () => {
|
||||
it("углы 0° — тождественное преобразование", () => {
|
||||
const img = makeImage(2, 2, [
|
||||
[255, 0, 0, 255], [0, 255, 0, 255],
|
||||
[0, 0, 255, 255], [128, 128, 128, 255]
|
||||
[255, 0, 0, 255],
|
||||
[0, 255, 0, 255],
|
||||
[0, 0, 255, 255],
|
||||
[128, 128, 128, 255],
|
||||
]);
|
||||
const out = skewImage(img, 0, 0);
|
||||
expect(out.width).toBe(2);
|
||||
@@ -93,22 +109,24 @@ describe('skewImage', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('transformImage — заливка фона', () => {
|
||||
it('сдвиг с белым фоном заполняет освободившийся край', () => {
|
||||
describe("transformImage — заливка фона", () => {
|
||||
it("сдвиг с белым фоном заполняет освободившийся край", () => {
|
||||
const img = makeImage(2, 2, [
|
||||
[255, 0, 0, 255], [0, 255, 0, 255],
|
||||
[0, 0, 255, 255], [128, 128, 128, 255]
|
||||
[255, 0, 0, 255],
|
||||
[0, 255, 0, 255],
|
||||
[0, 0, 255, 255],
|
||||
[128, 128, 128, 255],
|
||||
]);
|
||||
const out = transformImage(img, [1, 0, 0, 1, -1, 0], 2, 2, '#ffffff');
|
||||
const out = transformImage(img, [1, 0, 0, 1, -1, 0], 2, 2, "#ffffff");
|
||||
expect(out.width).toBe(2);
|
||||
expect(out.height).toBe(2);
|
||||
for (let y = 0; y < 2; y++) {
|
||||
const di = (y * 2) * 4;
|
||||
const di = y * 2 * 4;
|
||||
expect([...out.data.slice(di, di + 4)]).toEqual([255, 255, 255, 255]);
|
||||
}
|
||||
});
|
||||
|
||||
it('без фона освободившийся край остаётся прозрачным', () => {
|
||||
it("без фона освободившийся край остаётся прозрачным", () => {
|
||||
const img = makeImage(2, 2, new Array(4).fill([10, 20, 30, 255]));
|
||||
const out = transformImage(img, [1, 0, 0, 1, -1, 0], 2, 2);
|
||||
expect(out.data[3]).toBe(0);
|
||||
|
||||
+25
-11
@@ -1,14 +1,14 @@
|
||||
import { parseHex } from './alpha';
|
||||
import { ToolError } from './errors';
|
||||
import { clonePixelImage, createPixelImage, type PixelImage } from './types';
|
||||
import { sampleBilinear } from './geometry';
|
||||
import { parseHex } from "./alpha";
|
||||
import { ToolError } from "./errors";
|
||||
import { clonePixelImage, createPixelImage, type PixelImage } from "./types";
|
||||
import { sampleBilinear } from "./geometry";
|
||||
|
||||
export type AffineMatrix = [number, number, number, number, number, number];
|
||||
|
||||
export function invertAffine([a, b, c, d, e, f]: AffineMatrix): AffineMatrix {
|
||||
const det = a * d - b * c;
|
||||
if (Math.abs(det) < 1e-12) {
|
||||
throw new ToolError('errors.badTransform');
|
||||
throw new ToolError("errors.badTransform");
|
||||
}
|
||||
const ia = d / det;
|
||||
const ib = -b / det;
|
||||
@@ -24,7 +24,7 @@ export function transformImage(
|
||||
dstToSrc: AffineMatrix,
|
||||
outWidth: number,
|
||||
outHeight: number,
|
||||
bgHex?: string
|
||||
bgHex?: string,
|
||||
): PixelImage {
|
||||
const [a, b, c, d, e, f] = dstToSrc;
|
||||
const out = createPixelImage(outWidth, outHeight);
|
||||
@@ -34,7 +34,12 @@ export function transformImage(
|
||||
const sx = a * x + c * y + e;
|
||||
const sy = b * x + d * y + f;
|
||||
const di = (y * outWidth + x) * 4;
|
||||
if (sx < -EPS || sy < -EPS || sx > img.width - 1 + EPS || sy > img.height - 1 + EPS) {
|
||||
if (
|
||||
sx < -EPS ||
|
||||
sy < -EPS ||
|
||||
sx > img.width - 1 + EPS ||
|
||||
sy > img.height - 1 + EPS
|
||||
) {
|
||||
if (bg) {
|
||||
out.data[di] = bg[0];
|
||||
out.data[di + 1] = bg[1];
|
||||
@@ -72,7 +77,7 @@ function centeredTransform(img: PixelImage, forward: AffineMatrix): PixelImage {
|
||||
[0.5, 0.5],
|
||||
[img.width - 0.5, 0.5],
|
||||
[0.5, img.height - 0.5],
|
||||
[img.width - 0.5, img.height - 0.5]
|
||||
[img.width - 0.5, img.height - 0.5],
|
||||
]) {
|
||||
const qx = forward[0] * px + forward[2] * py + forward[4];
|
||||
const qy = forward[1] * px + forward[3] * py + forward[5];
|
||||
@@ -85,14 +90,23 @@ function centeredTransform(img: PixelImage, forward: AffineMatrix): PixelImage {
|
||||
const outH = Math.round(maxY - minY) + 1;
|
||||
const tx = inv[0] * minX + inv[2] * minY - 0.5;
|
||||
const ty = inv[1] * minX + inv[3] * minY - 0.5;
|
||||
return transformImage(img, [inv[0], inv[1], inv[2], inv[3], tx, ty], outW, outH);
|
||||
return transformImage(
|
||||
img,
|
||||
[inv[0], inv[1], inv[2], inv[3], tx, ty],
|
||||
outW,
|
||||
outH,
|
||||
);
|
||||
}
|
||||
|
||||
export function skewImage(img: PixelImage, degX: number, degY: number): PixelImage {
|
||||
export function skewImage(
|
||||
img: PixelImage,
|
||||
degX: number,
|
||||
degY: number,
|
||||
): PixelImage {
|
||||
const kx = Math.tan((degX * Math.PI) / 180);
|
||||
const ky = Math.tan((degY * Math.PI) / 180);
|
||||
if (!Number.isFinite(kx) || !Number.isFinite(ky)) {
|
||||
throw new ToolError('errors.skewAngle');
|
||||
throw new ToolError("errors.skewAngle");
|
||||
}
|
||||
return centeredTransform(img, [1, ky, kx, 1, 0, 0]);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
colorMask,
|
||||
extractAlphaMask,
|
||||
@@ -8,53 +8,52 @@ import {
|
||||
parseHex,
|
||||
removeColorToAlpha,
|
||||
roundCorners,
|
||||
setAlphaChannel
|
||||
} from './alpha';
|
||||
import { makeImage } from './test-helpers';
|
||||
setAlphaChannel,
|
||||
} from "./alpha";
|
||||
import { makeImage } from "./test-helpers";
|
||||
|
||||
describe('hardenAlpha', () => {
|
||||
it('бинаризует альфу по порогу, RGB не трогает', () => {
|
||||
describe("hardenAlpha", () => {
|
||||
it("бинаризует альфу по порогу, RGB не трогает", () => {
|
||||
const out = hardenAlpha(
|
||||
makeImage(2, 1, [
|
||||
[10, 20, 30, 100],
|
||||
[40, 50, 60, 200]
|
||||
[40, 50, 60, 200],
|
||||
]),
|
||||
50
|
||||
50,
|
||||
);
|
||||
expect([...out.data]).toEqual([
|
||||
10, 20, 30, 0,
|
||||
40, 50, 60, 255
|
||||
]);
|
||||
expect([...out.data]).toEqual([10, 20, 30, 0, 40, 50, 60, 255]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('setAlphaChannel', () => {
|
||||
it('задаёт константную альфу', () => {
|
||||
const out = setAlphaChannel(makeImage(2, 1, [
|
||||
describe("setAlphaChannel", () => {
|
||||
it("задаёт константную альфу", () => {
|
||||
const out = setAlphaChannel(
|
||||
makeImage(2, 1, [
|
||||
[1, 2, 3, 255],
|
||||
[4, 5, 6, 0]
|
||||
]), 50);
|
||||
[4, 5, 6, 0],
|
||||
]),
|
||||
50,
|
||||
);
|
||||
expect(out.data[3]).toBe(128);
|
||||
expect(out.data[7]).toBe(128);
|
||||
expect(out.data[0]).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('extractAlphaMask', () => {
|
||||
it('переводит альфу в чёрно-белую непрозрачную маску', () => {
|
||||
const out = extractAlphaMask(makeImage(2, 1, [
|
||||
describe("extractAlphaMask", () => {
|
||||
it("переводит альфу в чёрно-белую непрозрачную маску", () => {
|
||||
const out = extractAlphaMask(
|
||||
makeImage(2, 1, [
|
||||
[10, 20, 30, 255],
|
||||
[40, 50, 60, 0]
|
||||
]));
|
||||
expect([...out.data]).toEqual([
|
||||
255, 255, 255, 255,
|
||||
0, 0, 0, 255
|
||||
]);
|
||||
[40, 50, 60, 0],
|
||||
]),
|
||||
);
|
||||
expect([...out.data]).toEqual([255, 255, 255, 255, 0, 0, 0, 255]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('roundCorners', () => {
|
||||
it('срезает углы, центр и середины сторон остаются', () => {
|
||||
describe("roundCorners", () => {
|
||||
it("срезает углы, центр и середины сторон остаются", () => {
|
||||
const img = makeImage(11, 11, new Array(121).fill([100, 100, 100, 255]));
|
||||
const out = roundCorners(img, 40);
|
||||
expect(out.data[(0 * 11 + 0) * 4 + 3]).toBe(0);
|
||||
@@ -62,125 +61,125 @@ describe('roundCorners', () => {
|
||||
expect(out.data[(5 * 11 + 0) * 4 + 3]).toBe(255);
|
||||
});
|
||||
|
||||
it('нулевой радиус ничего не меняет', () => {
|
||||
it("нулевой радиус ничего не меняет", () => {
|
||||
const img = makeImage(2, 2, new Array(4).fill([1, 2, 3, 255]));
|
||||
expect([...roundCorners(img, 0).data]).toEqual([...img.data]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('invertAlpha', () => {
|
||||
it('обращает альфу, RGB не трогает', () => {
|
||||
describe("invertAlpha", () => {
|
||||
it("обращает альфу, RGB не трогает", () => {
|
||||
const out = invertAlpha(makeImage(1, 1, [[10, 20, 30, 128]]));
|
||||
expect([...out.data]).toEqual([10, 20, 30, 127]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('removeColorToAlpha', () => {
|
||||
describe("removeColorToAlpha", () => {
|
||||
const fixture = () =>
|
||||
makeImage(2, 1, [
|
||||
[255, 255, 255, 255],
|
||||
[255, 0, 0, 255]
|
||||
[255, 0, 0, 255],
|
||||
]);
|
||||
|
||||
it('обнуляет альфу только у точного совпадения при tolerance=0', () => {
|
||||
const out = removeColorToAlpha(fixture(), '#ff0000', 0);
|
||||
it("обнуляет альфу только у точного совпадения при tolerance=0", () => {
|
||||
const out = removeColorToAlpha(fixture(), "#ff0000", 0);
|
||||
expect(out.data[3]).toBe(255);
|
||||
expect(out.data[7]).toBe(0);
|
||||
expect(out.data[4]).toBe(255);
|
||||
expect(out.data[5]).toBe(0);
|
||||
});
|
||||
|
||||
it('поддерживает короткую форму и регистр hex', () => {
|
||||
expect([...removeColorToAlpha(fixture(), '#f00', 0).data.slice(4)]).toEqual([
|
||||
255, 0, 0, 0
|
||||
]);
|
||||
expect([...removeColorToAlpha(fixture(), '#FF0000', 0).data.slice(4)]).toEqual([
|
||||
255, 0, 0, 0
|
||||
]);
|
||||
it("поддерживает короткую форму и регистр hex", () => {
|
||||
expect([...removeColorToAlpha(fixture(), "#f00", 0).data.slice(4)]).toEqual(
|
||||
[255, 0, 0, 0],
|
||||
);
|
||||
expect([
|
||||
...removeColorToAlpha(fixture(), "#FF0000", 0).data.slice(4),
|
||||
]).toEqual([255, 0, 0, 0]);
|
||||
});
|
||||
|
||||
it('tolerance 100% удаляет весь диапазон расстояний', () => {
|
||||
const out = removeColorToAlpha(fixture(), '#000000', 100);
|
||||
it("tolerance 100% удаляет весь диапазон расстояний", () => {
|
||||
const out = removeColorToAlpha(fixture(), "#000000", 100);
|
||||
expect(out.data[3]).toBe(0);
|
||||
expect(out.data[7]).toBe(0);
|
||||
});
|
||||
|
||||
it('промежуточный tolerance различает близкие и далёкие цвета', () => {
|
||||
it("промежуточный tolerance различает близкие и далёкие цвета", () => {
|
||||
const img = makeImage(2, 1, [
|
||||
[0, 0, 0, 255],
|
||||
[128, 128, 128, 255]
|
||||
[128, 128, 128, 255],
|
||||
]);
|
||||
const kept = removeColorToAlpha(img, '#000000', 40);
|
||||
const removed = removeColorToAlpha(img, '#000000', 60);
|
||||
const kept = removeColorToAlpha(img, "#000000", 40);
|
||||
const removed = removeColorToAlpha(img, "#000000", 60);
|
||||
expect(kept.data[3]).toBe(0);
|
||||
expect(kept.data[7]).toBe(255);
|
||||
expect(removed.data[3]).toBe(0);
|
||||
expect(removed.data[7]).toBe(0);
|
||||
});
|
||||
|
||||
it('не мутирует вход', () => {
|
||||
it("не мутирует вход", () => {
|
||||
const img = fixture();
|
||||
removeColorToAlpha(img, '#ffffff', 100);
|
||||
expect([...img.data]).toEqual([
|
||||
255, 255, 255, 255,
|
||||
255, 0, 0, 255
|
||||
]);
|
||||
removeColorToAlpha(img, "#ffffff", 100);
|
||||
expect([...img.data]).toEqual([255, 255, 255, 255, 255, 0, 0, 255]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('colorMask', () => {
|
||||
it('удаляемые пиксели белые, остальные чёрные, маска непрозрачная', () => {
|
||||
describe("colorMask", () => {
|
||||
it("удаляемые пиксели белые, остальные чёрные, маска непрозрачная", () => {
|
||||
const out = colorMask(
|
||||
makeImage(2, 1, [
|
||||
[255, 0, 0, 255],
|
||||
[0, 255, 0, 255]
|
||||
[0, 255, 0, 255],
|
||||
]),
|
||||
'#ff0000',
|
||||
0
|
||||
"#ff0000",
|
||||
0,
|
||||
);
|
||||
expect([...out.data]).toEqual([
|
||||
255, 255, 255, 255,
|
||||
0, 0, 0, 255
|
||||
]);
|
||||
expect([...out.data]).toEqual([255, 255, 255, 255, 0, 0, 0, 255]);
|
||||
});
|
||||
|
||||
it('порог совпадает с removeColorToAlpha', () => {
|
||||
it("порог совпадает с removeColorToAlpha", () => {
|
||||
const img = makeImage(2, 1, [
|
||||
[0, 0, 0, 255],
|
||||
[128, 128, 128, 255]
|
||||
[128, 128, 128, 255],
|
||||
]);
|
||||
const kept = colorMask(img, '#000000', 40);
|
||||
const removed = colorMask(img, '#000000', 60);
|
||||
const kept = colorMask(img, "#000000", 40);
|
||||
const removed = colorMask(img, "#000000", 60);
|
||||
expect(kept.data[4]).toBe(0);
|
||||
expect(removed.data[4]).toBe(255);
|
||||
});
|
||||
});
|
||||
|
||||
describe('flattenOntoColor', () => {
|
||||
it('непрозрачный пиксель не меняется, альфа становится 255', () => {
|
||||
const out = flattenOntoColor(makeImage(1, 1, [[10, 20, 30, 255]]), '#ffffff');
|
||||
describe("flattenOntoColor", () => {
|
||||
it("непрозрачный пиксель не меняется, альфа становится 255", () => {
|
||||
const out = flattenOntoColor(
|
||||
makeImage(1, 1, [[10, 20, 30, 255]]),
|
||||
"#ffffff",
|
||||
);
|
||||
expect([...out.data]).toEqual([10, 20, 30, 255]);
|
||||
});
|
||||
|
||||
it('полностью прозрачный пиксель становится цветом подложки', () => {
|
||||
const out = flattenOntoColor(makeImage(1, 1, [[99, 99, 99, 0]]), '#ff8040');
|
||||
it("полностью прозрачный пиксель становится цветом подложки", () => {
|
||||
const out = flattenOntoColor(makeImage(1, 1, [[99, 99, 99, 0]]), "#ff8040");
|
||||
expect([...out.data]).toEqual([255, 128, 64, 255]);
|
||||
});
|
||||
|
||||
it('полупрозрачный пиксель смешивается с подложкой', () => {
|
||||
const out = flattenOntoColor(makeImage(1, 1, [[10, 20, 30, 128]]), '#ffffff');
|
||||
it("полупрозрачный пиксель смешивается с подложкой", () => {
|
||||
const out = flattenOntoColor(
|
||||
makeImage(1, 1, [[10, 20, 30, 128]]),
|
||||
"#ffffff",
|
||||
);
|
||||
expect([...out.data]).toEqual([132, 137, 142, 255]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseHex', () => {
|
||||
it('разбирает #rrggbb, rrggbb, #rgb', () => {
|
||||
expect(parseHex('#ff8040')).toEqual([255, 128, 64]);
|
||||
expect(parseHex('ff8040')).toEqual([255, 128, 64]);
|
||||
expect(parseHex('#F80')).toEqual([255, 136, 0]);
|
||||
describe("parseHex", () => {
|
||||
it("разбирает #rrggbb, rrggbb, #rgb", () => {
|
||||
expect(parseHex("#ff8040")).toEqual([255, 128, 64]);
|
||||
expect(parseHex("ff8040")).toEqual([255, 128, 64]);
|
||||
expect(parseHex("#F80")).toEqual([255, 136, 0]);
|
||||
});
|
||||
|
||||
it.each(['zzz', '12345', '##ff', ''])('бросает ошибку на "%s"', (bad) => {
|
||||
it.each(["zzz", "12345", "##ff", ""])('бросает ошибку на "%s"', (bad) => {
|
||||
expect(() => parseHex(bad)).toThrow(/errors\.badHex/);
|
||||
});
|
||||
});
|
||||
|
||||
+42
-16
@@ -1,17 +1,22 @@
|
||||
import { createPixelImage, type PixelImage } from './types';
|
||||
import { ToolError } from './errors';
|
||||
import { createPixelImage, type PixelImage } from "./types";
|
||||
import { ToolError } from "./errors";
|
||||
|
||||
const MAX_COLOR_DISTANCE = Math.sqrt(3 * 255 * 255);
|
||||
|
||||
export function removeColorToAlpha(
|
||||
img: PixelImage,
|
||||
hex: string,
|
||||
tolerancePercent = 0
|
||||
tolerancePercent = 0,
|
||||
): PixelImage {
|
||||
const [targetR, targetG, targetB] = parseHex(hex);
|
||||
const tolerance = (clamp(tolerancePercent, 0, 100) / 100) * MAX_COLOR_DISTANCE;
|
||||
const tolerance =
|
||||
(clamp(tolerancePercent, 0, 100) / 100) * MAX_COLOR_DISTANCE;
|
||||
const thresholdSq = tolerance * tolerance;
|
||||
const out: PixelImage = { width: img.width, height: img.height, data: img.data.slice() };
|
||||
const out: PixelImage = {
|
||||
width: img.width,
|
||||
height: img.height,
|
||||
data: img.data.slice(),
|
||||
};
|
||||
for (let i = 0; i < out.data.length; i += 4) {
|
||||
const dr = out.data[i] - targetR;
|
||||
const dg = out.data[i + 1] - targetG;
|
||||
@@ -25,7 +30,11 @@ export function removeColorToAlpha(
|
||||
|
||||
export function setAlphaChannel(img: PixelImage, percent: number): PixelImage {
|
||||
const alpha = Math.round((clamp(percent, 0, 100) / 100) * 255);
|
||||
const out: PixelImage = { width: img.width, height: img.height, data: img.data.slice() };
|
||||
const out: PixelImage = {
|
||||
width: img.width,
|
||||
height: img.height,
|
||||
data: img.data.slice(),
|
||||
};
|
||||
for (let i = 3; i < out.data.length; i += 4) {
|
||||
out.data[i] = alpha;
|
||||
}
|
||||
@@ -44,10 +53,19 @@ export function extractAlphaMask(img: PixelImage): PixelImage {
|
||||
return out;
|
||||
}
|
||||
|
||||
export function roundCorners(img: PixelImage, radiusPercent: number): PixelImage {
|
||||
const radius = (clamp(radiusPercent, 0, 50) / 100) * (Math.min(img.width, img.height) / 2);
|
||||
if (radius < 1) return { width: img.width, height: img.height, data: img.data.slice() };
|
||||
const out: PixelImage = { width: img.width, height: img.height, data: img.data.slice() };
|
||||
export function roundCorners(
|
||||
img: PixelImage,
|
||||
radiusPercent: number,
|
||||
): PixelImage {
|
||||
const radius =
|
||||
(clamp(radiusPercent, 0, 50) / 100) * (Math.min(img.width, img.height) / 2);
|
||||
if (radius < 1)
|
||||
return { width: img.width, height: img.height, data: img.data.slice() };
|
||||
const out: PixelImage = {
|
||||
width: img.width,
|
||||
height: img.height,
|
||||
data: img.data.slice(),
|
||||
};
|
||||
const r2 = radius * radius;
|
||||
for (let y = 0; y < out.height; y++) {
|
||||
for (let x = 0; x < out.width; x++) {
|
||||
@@ -74,7 +92,10 @@ export function invertAlpha(img: PixelImage): PixelImage {
|
||||
return out;
|
||||
}
|
||||
|
||||
export function hardenAlpha(img: PixelImage, thresholdPercent: number): PixelImage {
|
||||
export function hardenAlpha(
|
||||
img: PixelImage,
|
||||
thresholdPercent: number,
|
||||
): PixelImage {
|
||||
const threshold = (clamp(thresholdPercent, 0, 100) / 100) * 255;
|
||||
const out = createPixelImage(img.width, img.height);
|
||||
for (let i = 0; i < out.data.length; i += 4) {
|
||||
@@ -86,9 +107,14 @@ export function hardenAlpha(img: PixelImage, thresholdPercent: number): PixelIma
|
||||
return out;
|
||||
}
|
||||
|
||||
export function colorMask(img: PixelImage, hex: string, tolerancePercent = 0): PixelImage {
|
||||
export function colorMask(
|
||||
img: PixelImage,
|
||||
hex: string,
|
||||
tolerancePercent = 0,
|
||||
): PixelImage {
|
||||
const [targetR, targetG, targetB] = parseHex(hex);
|
||||
const tolerance = (clamp(tolerancePercent, 0, 100) / 100) * MAX_COLOR_DISTANCE;
|
||||
const tolerance =
|
||||
(clamp(tolerancePercent, 0, 100) / 100) * MAX_COLOR_DISTANCE;
|
||||
const thresholdSq = tolerance * tolerance;
|
||||
const out = createPixelImage(img.width, img.height);
|
||||
for (let i = 0; i < out.data.length; i += 4) {
|
||||
@@ -121,20 +147,20 @@ export function flattenOntoColor(img: PixelImage, hex: string): PixelImage {
|
||||
export function parseHex(hex: string): [number, number, number] {
|
||||
const match = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(hex.trim());
|
||||
if (!match) {
|
||||
throw new ToolError('errors.badHex', { value: hex });
|
||||
throw new ToolError("errors.badHex", { value: hex });
|
||||
}
|
||||
const digits = match[1];
|
||||
if (digits.length === 3) {
|
||||
return [
|
||||
parseInt(digits[0] + digits[0], 16),
|
||||
parseInt(digits[1] + digits[1], 16),
|
||||
parseInt(digits[2] + digits[2], 16)
|
||||
parseInt(digits[2] + digits[2], 16),
|
||||
];
|
||||
}
|
||||
return [
|
||||
parseInt(digits.slice(0, 2), 16),
|
||||
parseInt(digits.slice(2, 4), 16),
|
||||
parseInt(digits.slice(4, 6), 16)
|
||||
parseInt(digits.slice(4, 6), 16),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -1,76 +1,87 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
hasTransparency,
|
||||
imageInfo,
|
||||
isGrayscale,
|
||||
orientationOf
|
||||
} from './analyze';
|
||||
import { makeImage } from './test-helpers';
|
||||
orientationOf,
|
||||
} from "./analyze";
|
||||
import { makeImage } from "./test-helpers";
|
||||
|
||||
describe('imageInfo', () => {
|
||||
it('находит полупрозрачные пиксели и считает уникальные RGBA-цвета', () => {
|
||||
describe("imageInfo", () => {
|
||||
it("находит полупрозрачные пиксели и считает уникальные RGBA-цвета", () => {
|
||||
const info = imageInfo(
|
||||
makeImage(2, 2, [
|
||||
[0, 0, 0, 255],
|
||||
[0, 0, 0, 255],
|
||||
[255, 0, 0, 128],
|
||||
[255, 0, 0, 128]
|
||||
])
|
||||
[255, 0, 0, 128],
|
||||
]),
|
||||
);
|
||||
expect(info).toEqual({ width: 2, height: 2, hasAlpha: true, colorCount: 2 });
|
||||
expect(info).toEqual({
|
||||
width: 2,
|
||||
height: 2,
|
||||
hasAlpha: true,
|
||||
colorCount: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it('полностью непрозрачное изображение — hasAlpha false', () => {
|
||||
it("полностью непрозрачное изображение — hasAlpha false", () => {
|
||||
const info = imageInfo(
|
||||
makeImage(2, 1, [
|
||||
[10, 20, 30, 255],
|
||||
[40, 50, 60, 255]
|
||||
])
|
||||
[40, 50, 60, 255],
|
||||
]),
|
||||
);
|
||||
expect(info.hasAlpha).toBe(false);
|
||||
expect(info.colorCount).toBe(2);
|
||||
});
|
||||
|
||||
it('разная альфа означает разные цвета', () => {
|
||||
it("разная альфа означает разные цвета", () => {
|
||||
const info = imageInfo(
|
||||
makeImage(2, 1, [
|
||||
[255, 0, 0, 255],
|
||||
[255, 0, 0, 128]
|
||||
])
|
||||
[255, 0, 0, 128],
|
||||
]),
|
||||
);
|
||||
expect(info.hasAlpha).toBe(true);
|
||||
expect(info.colorCount).toBe(2);
|
||||
});
|
||||
|
||||
it('возвращает корректные размеры неквадрата', () => {
|
||||
it("возвращает корректные размеры неквадрата", () => {
|
||||
const info = imageInfo(makeImage(5, 3, new Array(15).fill([1, 2, 3, 4])));
|
||||
expect(info.width).toBe(5);
|
||||
expect(info.height).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isGrayscale', () => {
|
||||
it('серые пиксели — монохром', () => {
|
||||
describe("isGrayscale", () => {
|
||||
it("серые пиксели — монохром", () => {
|
||||
expect(isGrayscale(makeImage(1, 1, [[10, 10, 10, 255]]))).toBe(true);
|
||||
});
|
||||
it('цветной пиксель ломает монохром', () => {
|
||||
it("цветной пиксель ломает монохром", () => {
|
||||
expect(isGrayscale(makeImage(1, 1, [[10, 11, 10, 255]]))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasTransparency', () => {
|
||||
it('альфа ниже 255 — прозрачность есть', () => {
|
||||
describe("hasTransparency", () => {
|
||||
it("альфа ниже 255 — прозрачность есть", () => {
|
||||
expect(hasTransparency(makeImage(1, 1, [[0, 0, 0, 254]]))).toBe(true);
|
||||
});
|
||||
it('все пиксели непрозрачны', () => {
|
||||
it("все пиксели непрозрачны", () => {
|
||||
expect(hasTransparency(makeImage(1, 1, [[0, 0, 0, 255]]))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('orientationOf', () => {
|
||||
it('определяет ориентацию', () => {
|
||||
expect(orientationOf(makeImage(2, 3, new Array(6).fill([1, 1, 1, 1])))).toBe('portrait');
|
||||
expect(orientationOf(makeImage(3, 2, new Array(6).fill([1, 1, 1, 1])))).toBe('landscape');
|
||||
expect(orientationOf(makeImage(2, 2, new Array(4).fill([1, 1, 1, 1])))).toBe('square');
|
||||
describe("orientationOf", () => {
|
||||
it("определяет ориентацию", () => {
|
||||
expect(
|
||||
orientationOf(makeImage(2, 3, new Array(6).fill([1, 1, 1, 1]))),
|
||||
).toBe("portrait");
|
||||
expect(
|
||||
orientationOf(makeImage(3, 2, new Array(6).fill([1, 1, 1, 1]))),
|
||||
).toBe("landscape");
|
||||
expect(
|
||||
orientationOf(makeImage(2, 2, new Array(4).fill([1, 1, 1, 1]))),
|
||||
).toBe("square");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { PixelImage } from './types';
|
||||
import type { PixelImage } from "./types";
|
||||
|
||||
export type ImageInfo = {
|
||||
width: number;
|
||||
@@ -22,12 +22,20 @@ export function imageInfo(img: PixelImage): ImageInfo {
|
||||
0;
|
||||
seen.add(key);
|
||||
}
|
||||
return { width: img.width, height: img.height, hasAlpha, colorCount: seen.size };
|
||||
return {
|
||||
width: img.width,
|
||||
height: img.height,
|
||||
hasAlpha,
|
||||
colorCount: seen.size,
|
||||
};
|
||||
}
|
||||
|
||||
export function isGrayscale(img: PixelImage): boolean {
|
||||
for (let i = 0; i < img.data.length; i += 4) {
|
||||
if (img.data[i] !== img.data[i + 1] || img.data[i + 1] !== img.data[i + 2]) {
|
||||
if (
|
||||
img.data[i] !== img.data[i + 1] ||
|
||||
img.data[i + 1] !== img.data[i + 2]
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -41,10 +49,10 @@ export function hasTransparency(img: PixelImage): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
export type Orientation = 'portrait' | 'landscape' | 'square';
|
||||
export type Orientation = "portrait" | "landscape" | "square";
|
||||
|
||||
export function orientationOf(img: PixelImage): Orientation {
|
||||
if (img.height > img.width) return 'portrait';
|
||||
if (img.width > img.height) return 'landscape';
|
||||
return 'square';
|
||||
if (img.height > img.width) return "portrait";
|
||||
if (img.width > img.height) return "landscape";
|
||||
return "square";
|
||||
}
|
||||
|
||||
@@ -1,108 +1,119 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
backgroundMaskPreview,
|
||||
backgroundRemovalMask,
|
||||
removeBackground
|
||||
} from './background';
|
||||
import { makeImage } from './test-helpers';
|
||||
removeBackground,
|
||||
} from "./background";
|
||||
import { makeImage } from "./test-helpers";
|
||||
|
||||
const GREEN = [0, 255, 0, 255];
|
||||
const RED = [255, 0, 0, 255];
|
||||
|
||||
describe('backgroundRemovalMask', () => {
|
||||
it('глобальный режим удаляет все совпадающие пиксели', () => {
|
||||
const mask = backgroundRemovalMask(
|
||||
makeImage(2, 1, [GREEN, RED]),
|
||||
{ color: '#00ff00', tolerancePercent: 0, outerOnly: false, smoothPasses: 0 }
|
||||
);
|
||||
describe("backgroundRemovalMask", () => {
|
||||
it("глобальный режим удаляет все совпадающие пиксели", () => {
|
||||
const mask = backgroundRemovalMask(makeImage(2, 1, [GREEN, RED]), {
|
||||
color: "#00ff00",
|
||||
tolerancePercent: 0,
|
||||
outerOnly: false,
|
||||
smoothPasses: 0,
|
||||
});
|
||||
expect([...mask]).toEqual([1, 0]);
|
||||
});
|
||||
|
||||
describe('режим внешних областей', () => {
|
||||
const ringRedCenterGreen = [
|
||||
RED, RED, RED,
|
||||
RED, GREEN, RED,
|
||||
RED, RED, RED
|
||||
];
|
||||
describe("режим внешних областей", () => {
|
||||
const ringRedCenterGreen = [RED, RED, RED, RED, GREEN, RED, RED, RED, RED];
|
||||
|
||||
it('заливка от краёв не достаёт до изолированного совпадающего острова', () => {
|
||||
const mask = backgroundRemovalMask(
|
||||
makeImage(3, 3, ringRedCenterGreen),
|
||||
{ color: '#00ff00', tolerancePercent: 0, outerOnly: true, smoothPasses: 0 }
|
||||
);
|
||||
it("заливка от краёв не достаёт до изолированного совпадающего острова", () => {
|
||||
const mask = backgroundRemovalMask(makeImage(3, 3, ringRedCenterGreen), {
|
||||
color: "#00ff00",
|
||||
tolerancePercent: 0,
|
||||
outerOnly: true,
|
||||
smoothPasses: 0,
|
||||
});
|
||||
expect(mask[4]).toBe(0);
|
||||
});
|
||||
|
||||
it('глобальный режим удаляет и изолированный остров', () => {
|
||||
const mask = backgroundRemovalMask(
|
||||
makeImage(3, 3, ringRedCenterGreen),
|
||||
{ color: '#00ff00', tolerancePercent: 0, outerOnly: false, smoothPasses: 0 }
|
||||
);
|
||||
it("глобальный режим удаляет и изолированный остров", () => {
|
||||
const mask = backgroundRemovalMask(makeImage(3, 3, ringRedCenterGreen), {
|
||||
color: "#00ff00",
|
||||
tolerancePercent: 0,
|
||||
outerOnly: false,
|
||||
smoothPasses: 0,
|
||||
});
|
||||
expect(mask[4]).toBe(1);
|
||||
expect(mask[0]).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('допуск расширяет захват по цветовому расстоянию', () => {
|
||||
it("допуск расширяет захват по цветовому расстоянию", () => {
|
||||
const img = makeImage(2, 1, [
|
||||
[10, 10, 10, 255],
|
||||
[128, 128, 128, 255]
|
||||
[128, 128, 128, 255],
|
||||
]);
|
||||
const tight = backgroundRemovalMask(img, {
|
||||
color: '#000000', tolerancePercent: 40, outerOnly: false, smoothPasses: 0
|
||||
color: "#000000",
|
||||
tolerancePercent: 40,
|
||||
outerOnly: false,
|
||||
smoothPasses: 0,
|
||||
});
|
||||
const wide = backgroundRemovalMask(img, {
|
||||
color: '#000000', tolerancePercent: 60, outerOnly: false, smoothPasses: 0
|
||||
color: "#000000",
|
||||
tolerancePercent: 60,
|
||||
outerOnly: false,
|
||||
smoothPasses: 0,
|
||||
});
|
||||
expect(tight[1]).toBe(0);
|
||||
expect(wide[1]).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('smoothMask-поведение через backgroundRemovalMask', () => {
|
||||
const ringRedCenterGreen = [
|
||||
RED, RED, RED,
|
||||
RED, GREEN, RED,
|
||||
RED, RED, RED
|
||||
];
|
||||
const opts = { color: '#00ff00', tolerancePercent: 0, outerOnly: false };
|
||||
describe("smoothMask-поведение через backgroundRemovalMask", () => {
|
||||
const ringRedCenterGreen = [RED, RED, RED, RED, GREEN, RED, RED, RED, RED];
|
||||
const opts = { color: "#00ff00", tolerancePercent: 0, outerOnly: false };
|
||||
|
||||
const alphaAtCenter = (img: { data: Uint8ClampedArray }) => img.data[19];
|
||||
|
||||
it('без сглаживания центр удалён', () => {
|
||||
const img = removeBackground(makeImage(3, 3, ringRedCenterGreen), { ...opts, smoothPasses: 0 });
|
||||
it("без сглаживания центр удалён", () => {
|
||||
const img = removeBackground(makeImage(3, 3, ringRedCenterGreen), {
|
||||
...opts,
|
||||
smoothPasses: 0,
|
||||
});
|
||||
expect(alphaAtCenter(img)).toBe(0);
|
||||
});
|
||||
|
||||
it('два прохода мажоритарного фильтра возвращают изолированный пиксель', () => {
|
||||
const img = removeBackground(makeImage(3, 3, ringRedCenterGreen), { ...opts, smoothPasses: 2 });
|
||||
it("два прохода мажоритарного фильтра возвращают изолированный пиксель", () => {
|
||||
const img = removeBackground(makeImage(3, 3, ringRedCenterGreen), {
|
||||
...opts,
|
||||
smoothPasses: 2,
|
||||
});
|
||||
expect(alphaAtCenter(img)).toBe(255);
|
||||
});
|
||||
});
|
||||
|
||||
describe('removeBackground', () => {
|
||||
it('обнуляет альфу удалённых, сохраняет RGB остальных', () => {
|
||||
const out = removeBackground(
|
||||
makeImage(2, 1, [GREEN, [5, 6, 7, 200]]),
|
||||
{ color: '#00ff00', tolerancePercent: 0, outerOnly: false, smoothPasses: 0 }
|
||||
);
|
||||
describe("removeBackground", () => {
|
||||
it("обнуляет альфу удалённых, сохраняет RGB остальных", () => {
|
||||
const out = removeBackground(makeImage(2, 1, [GREEN, [5, 6, 7, 200]]), {
|
||||
color: "#00ff00",
|
||||
tolerancePercent: 0,
|
||||
outerOnly: false,
|
||||
smoothPasses: 0,
|
||||
});
|
||||
expect(out.data[3]).toBe(0);
|
||||
expect([...out.data.slice(4, 8)]).toEqual([5, 6, 7, 200]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('backgroundMaskPreview', () => {
|
||||
it('белое там, где удаление, чёрное — где остаёмся, всё непрозрачно', () => {
|
||||
describe("backgroundMaskPreview", () => {
|
||||
it("белое там, где удаление, чёрное — где остаёмся, всё непрозрачно", () => {
|
||||
const preview = backgroundMaskPreview(
|
||||
makeImage(2, 1, [
|
||||
GREEN,
|
||||
[9, 9, 9, 60]
|
||||
]),
|
||||
{ color: '#00ff00', tolerancePercent: 0, outerOnly: false, smoothPasses: 0 }
|
||||
makeImage(2, 1, [GREEN, [9, 9, 9, 60]]),
|
||||
{
|
||||
color: "#00ff00",
|
||||
tolerancePercent: 0,
|
||||
outerOnly: false,
|
||||
smoothPasses: 0,
|
||||
},
|
||||
);
|
||||
expect([...preview.data]).toEqual([
|
||||
255, 255, 255, 255,
|
||||
0, 0, 0, 255
|
||||
]);
|
||||
expect([...preview.data]).toEqual([255, 255, 255, 255, 0, 0, 0, 255]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { parseHex } from './alpha';
|
||||
import { createPixelImage, type PixelImage } from './types';
|
||||
import { parseHex } from "./alpha";
|
||||
import { createPixelImage, type PixelImage } from "./types";
|
||||
|
||||
export type BackgroundOptions = {
|
||||
color: string;
|
||||
@@ -13,9 +13,10 @@ function buildRawMask(
|
||||
targetR: number,
|
||||
targetG: number,
|
||||
targetB: number,
|
||||
tolerancePercent: number
|
||||
tolerancePercent: number,
|
||||
): Uint8Array {
|
||||
const tolerance = (clamp(tolerancePercent, 0, 100) / 100) * Math.sqrt(3 * 255 * 255);
|
||||
const tolerance =
|
||||
(clamp(tolerancePercent, 0, 100) / 100) * Math.sqrt(3 * 255 * 255);
|
||||
const thresholdSq = tolerance * tolerance;
|
||||
const mask = new Uint8Array(img.width * img.height);
|
||||
for (let i = 0; i < mask.length; i++) {
|
||||
@@ -61,7 +62,7 @@ export function smoothMask(
|
||||
mask: Uint8Array,
|
||||
w: number,
|
||||
h: number,
|
||||
passes: number
|
||||
passes: number,
|
||||
): Uint8Array {
|
||||
let current = mask;
|
||||
const count = clamp(Math.trunc(passes), 0, 8);
|
||||
@@ -89,7 +90,7 @@ export function smoothMask(
|
||||
|
||||
export function backgroundRemovalMask(
|
||||
img: PixelImage,
|
||||
options: BackgroundOptions
|
||||
options: BackgroundOptions,
|
||||
): Uint8Array {
|
||||
const [tr, tg, tb] = parseHex(options.color);
|
||||
const mask = buildRawMask(img, tr, tg, tb, options.tolerancePercent);
|
||||
@@ -99,7 +100,10 @@ export function backgroundRemovalMask(
|
||||
return smoothMask(mask, img.width, img.height, options.smoothPasses);
|
||||
}
|
||||
|
||||
export function removeBackground(img: PixelImage, options: BackgroundOptions): PixelImage {
|
||||
export function removeBackground(
|
||||
img: PixelImage,
|
||||
options: BackgroundOptions,
|
||||
): PixelImage {
|
||||
const mask = backgroundRemovalMask(img, options);
|
||||
const out = createPixelImage(img.width, img.height);
|
||||
for (let i = 0; i < mask.length; i++) {
|
||||
@@ -112,7 +116,10 @@ export function removeBackground(img: PixelImage, options: BackgroundOptions): P
|
||||
return out;
|
||||
}
|
||||
|
||||
export function backgroundMaskPreview(img: PixelImage, options: BackgroundOptions): PixelImage {
|
||||
export function backgroundMaskPreview(
|
||||
img: PixelImage,
|
||||
options: BackgroundOptions,
|
||||
): PixelImage {
|
||||
const mask = backgroundRemovalMask(img, options);
|
||||
const out = createPixelImage(img.width, img.height);
|
||||
for (let i = 0; i < mask.length; i++) {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { encodeBmpBytes } from './bmp';
|
||||
import { makeImage } from './test-helpers';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { encodeBmpBytes } from "./bmp";
|
||||
import { makeImage } from "./test-helpers";
|
||||
|
||||
describe('encodeBmpBytes', () => {
|
||||
it('пишет заголовки BM и размеры для 2x1 без паддинга-неопределённости', () => {
|
||||
describe("encodeBmpBytes", () => {
|
||||
it("пишет заголовки BM и размеры для 2x1 без паддинга-неопределённости", () => {
|
||||
const bytes = encodeBmpBytes(
|
||||
makeImage(2, 1, [
|
||||
[255, 0, 0, 255],
|
||||
[0, 255, 0, 255]
|
||||
])
|
||||
[0, 255, 0, 255],
|
||||
]),
|
||||
);
|
||||
expect([bytes[0], bytes[1]]).toEqual([0x42, 0x4d]);
|
||||
const view = new DataView(bytes.buffer);
|
||||
@@ -18,22 +18,19 @@ describe('encodeBmpBytes', () => {
|
||||
expect(view.getUint16(28, true)).toBe(24);
|
||||
});
|
||||
|
||||
it('хранит пиксели в BGR снизу-вверх с паддингом строки', () => {
|
||||
it("хранит пиксели в BGR снизу-вверх с паддингом строки", () => {
|
||||
const bytes = encodeBmpBytes(
|
||||
makeImage(2, 1, [
|
||||
[255, 0, 0, 255],
|
||||
[0, 255, 0, 255]
|
||||
])
|
||||
[0, 255, 0, 255],
|
||||
]),
|
||||
);
|
||||
expect([...bytes.slice(54, 60)]).toEqual([
|
||||
0, 0, 255,
|
||||
0, 255, 0
|
||||
]);
|
||||
expect([...bytes.slice(54, 60)]).toEqual([0, 0, 255, 0, 255, 0]);
|
||||
expect(bytes[60]).toBe(0);
|
||||
expect(bytes[61]).toBe(0);
|
||||
});
|
||||
|
||||
it('нижняя строка изображения идёт первой в файле', () => {
|
||||
it("нижняя строка изображения идёт первой в файле", () => {
|
||||
const bytes = encodeBmpBytes(
|
||||
makeImage(4, 2, [
|
||||
[10, 10, 10, 255],
|
||||
@@ -43,8 +40,8 @@ describe('encodeBmpBytes', () => {
|
||||
[50, 50, 50, 255],
|
||||
[60, 60, 60, 255],
|
||||
[70, 70, 70, 255],
|
||||
[80, 80, 80, 255]
|
||||
])
|
||||
[80, 80, 80, 255],
|
||||
]),
|
||||
);
|
||||
expect(bytes[54]).toBe(50);
|
||||
expect(bytes[54 + 12]).toBe(10);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { PixelImage } from './types';
|
||||
import type { PixelImage } from "./types";
|
||||
|
||||
export function encodeBmpBytes(img: PixelImage): Uint8Array<ArrayBuffer> {
|
||||
const rowSize = Math.ceil((img.width * 3) / 4) * 4;
|
||||
|
||||
@@ -1,41 +1,41 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { hexToRgb } from './palette';
|
||||
import { renderSpace, SPACES } from './channels';
|
||||
import { makeImage } from './test-helpers';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { hexToRgb } from "./palette";
|
||||
import { renderSpace, SPACES } from "./channels";
|
||||
import { makeImage } from "./test-helpers";
|
||||
|
||||
describe('преобразования пространств', () => {
|
||||
it('hsl красного: h=0, s=1, l=0.5', () => {
|
||||
const [h, s, l] = SPACES.hsl.convert(hexToRgb('#ff0000'));
|
||||
describe("преобразования пространств", () => {
|
||||
it("hsl красного: h=0, s=1, l=0.5", () => {
|
||||
const [h, s, l] = SPACES.hsl.convert(hexToRgb("#ff0000"));
|
||||
expect(h).toBeCloseTo(0);
|
||||
expect(s).toBeCloseTo(1);
|
||||
expect(l).toBeCloseTo(0.5);
|
||||
});
|
||||
|
||||
it('hsv белого: v=1, чёрного: v=0', () => {
|
||||
it("hsv белого: v=1, чёрного: v=0", () => {
|
||||
expect(SPACES.hsv.convert({ r: 255, g: 255, b: 255 })[2]).toBeCloseTo(1);
|
||||
expect(SPACES.hsv.convert({ r: 0, g: 0, b: 0 })[2]).toBe(0);
|
||||
});
|
||||
|
||||
it('hsi серого: s=0', () => {
|
||||
it("hsi серого: s=0", () => {
|
||||
const [, s] = SPACES.hsi.convert({ r: 128, g: 128, b: 128 });
|
||||
expect(s).toBeCloseTo(0);
|
||||
});
|
||||
|
||||
it('cmyk: белый — 0,0,0,0; чёрный — 0,0,0,1', () => {
|
||||
it("cmyk: белый — 0,0,0,0; чёрный — 0,0,0,1", () => {
|
||||
const w = SPACES.cmyk.convert({ r: 255, g: 255, b: 255 });
|
||||
const b = SPACES.cmyk.convert({ r: 0, g: 0, b: 0 });
|
||||
expect(w.every((v) => Math.abs(v) < 1e-9)).toBe(true);
|
||||
expect(b[3]).toBeCloseTo(1);
|
||||
});
|
||||
|
||||
it('ycbcr белого: y≈1, cb≈cr≈0.5', () => {
|
||||
it("ycbcr белого: y≈1, cb≈cr≈0.5", () => {
|
||||
const [y, cb, cr] = SPACES.ycbcr.convert({ r: 255, g: 255, b: 255 });
|
||||
expect(y).toBeCloseTo(1);
|
||||
expect(cb).toBeCloseTo(0.5, 2);
|
||||
expect(cr).toBeCloseTo(0.5, 2);
|
||||
});
|
||||
|
||||
it('lab белого: l≈1, a≈b≈0.5 (центр)', () => {
|
||||
it("lab белого: l≈1, a≈b≈0.5 (центр)", () => {
|
||||
const [l, a, bb] = SPACES.lab.convert({ r: 255, g: 255, b: 255 });
|
||||
expect(l).toBeCloseTo(1, 2);
|
||||
expect(a).toBeCloseTo(0.5, 2);
|
||||
@@ -43,23 +43,25 @@ describe('преобразования пространств', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderSpace', () => {
|
||||
describe("renderSpace", () => {
|
||||
const red = makeImage(1, 1, [[255, 0, 0, 255]]);
|
||||
|
||||
it('gray-режим: компонент y (жёлтый) чистого красного = белый', () => {
|
||||
const out = renderSpace(red, 'cmyk', 'y', 'gray');
|
||||
it("gray-режим: компонент y (жёлтый) чистого красного = белый", () => {
|
||||
const out = renderSpace(red, "cmyk", "y", "gray");
|
||||
expect([...out.data]).toEqual([255, 255, 255, 255]);
|
||||
});
|
||||
|
||||
it('color-режим hsl красного: каналы = тон/насыщенность/светлота', () => {
|
||||
const out = renderSpace(red, 'hsl', 's', 'color');
|
||||
it("color-режим hsl красного: каналы = тон/насыщенность/светлота", () => {
|
||||
const out = renderSpace(red, "hsl", "s", "color");
|
||||
expect(out.data[0]).toBe(0);
|
||||
expect(out.data[1]).toBe(255);
|
||||
expect(out.data[2]).toBeGreaterThanOrEqual(127);
|
||||
});
|
||||
|
||||
it('неизвестное пространство или компонент дают прозрачную заглушку', () => {
|
||||
it("неизвестное пространство или компонент дают прозрачную заглушку", () => {
|
||||
const junk = makeImage(1, 1, [[10, 20, 30, 255]]);
|
||||
expect(renderSpace(junk, 'cmyk' as never, 'zz' as never, 'gray').data[3]).toBe(0);
|
||||
expect(
|
||||
renderSpace(junk, "cmyk" as never, "zz" as never, "gray").data[3],
|
||||
).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import type { PixelImage } from './types';
|
||||
import { createPixelImage } from './types';
|
||||
import { rgbToHsl } from './palette';
|
||||
import type { Rgb } from './palette';
|
||||
import type { PixelImage } from "./types";
|
||||
import { createPixelImage } from "./types";
|
||||
import { rgbToHsl } from "./palette";
|
||||
import type { Rgb } from "./palette";
|
||||
|
||||
/** Все компоненты нормализованы в 0..1 в порядке объявления. */
|
||||
export type SpaceComponents = number[];
|
||||
|
||||
export type SpaceId = 'hsl' | 'hsv' | 'hsi' | 'cmyk' | 'ycbcr' | 'lab';
|
||||
export type SpaceId = "hsl" | "hsv" | "hsi" | "cmyk" | "ycbcr" | "lab";
|
||||
|
||||
function hueOf({ r, g, b }: Rgb): number {
|
||||
const max = Math.max(r, g, b);
|
||||
@@ -47,7 +47,12 @@ function rgbToCmyk({ r, g, b }: Rgb): [number, number, number, number] {
|
||||
const bn = b / 255;
|
||||
const k = 1 - Math.max(rn, gn, bn);
|
||||
if (k === 1) return [0, 0, 0, 1];
|
||||
return [(1 - rn - k) / (1 - k), (1 - gn - k) / (1 - k), (1 - bn - k) / (1 - k), k];
|
||||
return [
|
||||
(1 - rn - k) / (1 - k),
|
||||
(1 - gn - k) / (1 - k),
|
||||
(1 - bn - k) / (1 - k),
|
||||
k,
|
||||
];
|
||||
}
|
||||
|
||||
function rgbToYcbcr({ r, g, b }: Rgb): [number, number, number] {
|
||||
@@ -71,27 +76,34 @@ function rgbToLab({ r, g, b }: Rgb): [number, number, number] {
|
||||
const fy = f(y);
|
||||
const fz = f(z);
|
||||
// L нормирован 0..1; a/b центрированы на 0.5 с размахом ±0.5
|
||||
return [(116 * fy - 16) / 100, (500 * (fx - fy)) / 250 + 0.5, (200 * (fy - fz)) / 250 + 0.5];
|
||||
return [
|
||||
(116 * fy - 16) / 100,
|
||||
(500 * (fx - fy)) / 250 + 0.5,
|
||||
(200 * (fy - fz)) / 250 + 0.5,
|
||||
];
|
||||
}
|
||||
|
||||
type SpaceDef = { components: string[]; convert: (rgb: Rgb) => SpaceComponents };
|
||||
type SpaceDef = {
|
||||
components: string[];
|
||||
convert: (rgb: Rgb) => SpaceComponents;
|
||||
};
|
||||
|
||||
export const SPACES: Record<SpaceId, SpaceDef> = {
|
||||
hsl: {
|
||||
components: ['h', 's', 'l'],
|
||||
components: ["h", "s", "l"],
|
||||
convert: ({ r, g, b }) => {
|
||||
const { h, s, l } = rgbToHsl({ r, g, b });
|
||||
return [h / 360, s, l];
|
||||
}
|
||||
},
|
||||
hsv: { components: ['h', 's', 'v'], convert: rgbToHsv },
|
||||
hsi: { components: ['h', 's', 'i'], convert: rgbToHsi },
|
||||
cmyk: { components: ['c', 'm', 'y', 'k'], convert: rgbToCmyk },
|
||||
ycbcr: { components: ['y', 'cb', 'cr'], convert: rgbToYcbcr },
|
||||
lab: { components: ['l', 'a', 'b'], convert: rgbToLab }
|
||||
},
|
||||
hsv: { components: ["h", "s", "v"], convert: rgbToHsv },
|
||||
hsi: { components: ["h", "s", "i"], convert: rgbToHsi },
|
||||
cmyk: { components: ["c", "m", "y", "k"], convert: rgbToCmyk },
|
||||
ycbcr: { components: ["y", "cb", "cr"], convert: rgbToYcbcr },
|
||||
lab: { components: ["l", "a", "b"], convert: rgbToLab },
|
||||
};
|
||||
|
||||
export type ChannelDisplay = 'gray' | 'color';
|
||||
export type ChannelDisplay = "gray" | "color";
|
||||
|
||||
/**
|
||||
* Визуализация выбранного пространства: каждый компонент пространства
|
||||
@@ -102,7 +114,7 @@ export function renderSpace(
|
||||
img: PixelImage,
|
||||
space: SpaceId,
|
||||
component: string,
|
||||
display: ChannelDisplay
|
||||
display: ChannelDisplay,
|
||||
): PixelImage {
|
||||
const def = SPACES[space];
|
||||
if (!def) return createPixelImage(img.width, img.height);
|
||||
@@ -110,10 +122,14 @@ export function renderSpace(
|
||||
if (idx < 0) return createPixelImage(img.width, img.height);
|
||||
const out = createPixelImage(img.width, img.height);
|
||||
for (let i = 0; i < img.data.length; i += 4) {
|
||||
const comps = def.convert({ r: img.data[i], g: img.data[i + 1], b: img.data[i + 2] });
|
||||
const comps = def.convert({
|
||||
r: img.data[i],
|
||||
g: img.data[i + 1],
|
||||
b: img.data[i + 2],
|
||||
});
|
||||
const di = i;
|
||||
out.data[di + 3] = img.data[i + 3];
|
||||
if (display === 'gray') {
|
||||
if (display === "gray") {
|
||||
const v = comps[idx] * 255;
|
||||
out.data[di] = v;
|
||||
out.data[di + 1] = v;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
autoContrast,
|
||||
brightnessContrast,
|
||||
@@ -15,39 +15,43 @@ import {
|
||||
temperature,
|
||||
tint,
|
||||
thresholdBlackWhite,
|
||||
twoColors
|
||||
} from './color';
|
||||
import { makeImage } from './test-helpers';
|
||||
twoColors,
|
||||
} from "./color";
|
||||
import { makeImage } from "./test-helpers";
|
||||
|
||||
describe('rgbToHex', () => {
|
||||
it('форматирует базовые цвета', () => {
|
||||
expect(rgbToHex(255, 0, 0)).toBe('#ff0000');
|
||||
expect(rgbToHex(1, 2, 3)).toBe('#010203');
|
||||
describe("rgbToHex", () => {
|
||||
it("форматирует базовые цвета", () => {
|
||||
expect(rgbToHex(255, 0, 0)).toBe("#ff0000");
|
||||
expect(rgbToHex(1, 2, 3)).toBe("#010203");
|
||||
});
|
||||
|
||||
it('округляет дробные значения и клампит диапазон', () => {
|
||||
expect(rgbToHex(127.6, -5, 300)).toBe('#8000ff');
|
||||
it("округляет дробные значения и клампит диапазон", () => {
|
||||
expect(rgbToHex(127.6, -5, 300)).toBe("#8000ff");
|
||||
});
|
||||
});
|
||||
|
||||
describe('setOpacity', () => {
|
||||
it('умножает альфу на процент, RGB не трогает', () => {
|
||||
describe("setOpacity", () => {
|
||||
it("умножает альфу на процент, RGB не трогает", () => {
|
||||
const out = setOpacity(makeImage(1, 1, [[10, 20, 30, 128]]), 50);
|
||||
expect([...out.data]).toEqual([10, 20, 30, 64]);
|
||||
});
|
||||
|
||||
it('100% не меняет, 0% делает полностью прозрачным', () => {
|
||||
expect(setOpacity(makeImage(1, 1, [[1, 2, 3, 200]]), 100).data[3]).toBe(200);
|
||||
it("100% не меняет, 0% делает полностью прозрачным", () => {
|
||||
expect(setOpacity(makeImage(1, 1, [[1, 2, 3, 200]]), 100).data[3]).toBe(
|
||||
200,
|
||||
);
|
||||
expect(setOpacity(makeImage(1, 1, [[1, 2, 3, 200]]), 0).data[3]).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sepia', () => {
|
||||
it('применяет классическую матрицу с клампом', () => {
|
||||
const out = sepia(makeImage(2, 1, [
|
||||
describe("sepia", () => {
|
||||
it("применяет классическую матрицу с клампом", () => {
|
||||
const out = sepia(
|
||||
makeImage(2, 1, [
|
||||
[255, 0, 0, 255],
|
||||
[255, 255, 255, 255]
|
||||
]));
|
||||
[255, 255, 255, 255],
|
||||
]),
|
||||
);
|
||||
const px = (n: number) => [...out.data.slice(n * 4, n * 4 + 4)];
|
||||
expect(px(0)).toEqual([100, 89, 69, 255]);
|
||||
expect(px(1)[0]).toBe(255);
|
||||
@@ -55,81 +59,85 @@ describe('sepia', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('changeHue', () => {
|
||||
it('чистый красный при +120° становится чистым зелёным', () => {
|
||||
describe("changeHue", () => {
|
||||
it("чистый красный при +120° становится чистым зелёным", () => {
|
||||
const out = changeHue(makeImage(1, 1, [[255, 0, 0, 255]]), 120);
|
||||
expect([...out.data]).toEqual([0, 255, 0, 255]);
|
||||
});
|
||||
|
||||
it('сдвиг 360° возвращает исходные цвета', () => {
|
||||
it("сдвиг 360° возвращает исходные цвета", () => {
|
||||
const img = makeImage(1, 1, [[90, 140, 210, 255]]);
|
||||
expect([...changeHue(img, 360).data]).toEqual([...img.data]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('extractChannel', () => {
|
||||
it('выдаёт выбранный канал оттенками серого', () => {
|
||||
const out = extractChannel(makeImage(1, 1, [[10, 20, 30, 40]]), 'green');
|
||||
describe("extractChannel", () => {
|
||||
it("выдаёт выбранный канал оттенками серого", () => {
|
||||
const out = extractChannel(makeImage(1, 1, [[10, 20, 30, 40]]), "green");
|
||||
expect([...out.data]).toEqual([20, 20, 20, 40]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('swapChannels', () => {
|
||||
it('переставляет каналы парами', () => {
|
||||
expect([...swapChannels(makeImage(1, 1, [[10, 20, 30, 40]]), 'r-b').data]).toEqual([
|
||||
30, 20, 10, 40
|
||||
]);
|
||||
expect([...swapChannels(makeImage(1, 1, [[10, 20, 30, 40]]), 'g-b').data]).toEqual([
|
||||
10, 30, 20, 40
|
||||
]);
|
||||
describe("swapChannels", () => {
|
||||
it("переставляет каналы парами", () => {
|
||||
expect([
|
||||
...swapChannels(makeImage(1, 1, [[10, 20, 30, 40]]), "r-b").data,
|
||||
]).toEqual([30, 20, 10, 40]);
|
||||
expect([
|
||||
...swapChannels(makeImage(1, 1, [[10, 20, 30, 40]]), "g-b").data,
|
||||
]).toEqual([10, 30, 20, 40]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('thresholdBlackWhite', () => {
|
||||
it('серый 128 относительно порога 50% — белый', () => {
|
||||
expect(thresholdBlackWhite(makeImage(1, 1, [[128, 128, 128, 255]]), 50).data[0]).toBe(255);
|
||||
expect(thresholdBlackWhite(makeImage(1, 1, [[128, 128, 128, 255]]), 60).data[0]).toBe(0);
|
||||
describe("thresholdBlackWhite", () => {
|
||||
it("серый 128 относительно порога 50% — белый", () => {
|
||||
expect(
|
||||
thresholdBlackWhite(makeImage(1, 1, [[128, 128, 128, 255]]), 50).data[0],
|
||||
).toBe(255);
|
||||
expect(
|
||||
thresholdBlackWhite(makeImage(1, 1, [[128, 128, 128, 255]]), 60).data[0],
|
||||
).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('posterize', () => {
|
||||
it('два уровня квантуют в чёрное и белое', () => {
|
||||
describe("posterize", () => {
|
||||
it("два уровня квантуют в чёрное и белое", () => {
|
||||
const out = posterize(
|
||||
makeImage(2, 1, [
|
||||
[100, 100, 100, 255],
|
||||
[200, 200, 200, 255]
|
||||
[200, 200, 200, 255],
|
||||
]),
|
||||
2
|
||||
2,
|
||||
);
|
||||
expect(out.data[0]).toBe(0);
|
||||
expect(out.data[4]).toBe(255);
|
||||
});
|
||||
});
|
||||
|
||||
describe('twoColors', () => {
|
||||
it('яркие пиксели получают светлый цвет, тёмные — тёмный', () => {
|
||||
describe("twoColors", () => {
|
||||
it("яркие пиксели получают светлый цвет, тёмные — тёмный", () => {
|
||||
const out = twoColors(
|
||||
makeImage(2, 1, [
|
||||
[250, 250, 250, 255],
|
||||
[10, 10, 10, 128]
|
||||
[10, 10, 10, 128],
|
||||
]),
|
||||
'#ff0000',
|
||||
'#00ff00',
|
||||
50
|
||||
"#ff0000",
|
||||
"#00ff00",
|
||||
50,
|
||||
);
|
||||
expect([...out.data.slice(0, 4)]).toEqual([255, 0, 0, 255]);
|
||||
expect([...out.data.slice(4, 8)]).toEqual([0, 255, 0, 128]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('grayscale', () => {
|
||||
it('считает luma по весам BT.601 с округлением', () => {
|
||||
describe("grayscale", () => {
|
||||
it("считает luma по весам BT.601 с округлением", () => {
|
||||
const out = grayscale(
|
||||
makeImage(3, 1, [
|
||||
[255, 0, 0, 255],
|
||||
[0, 255, 0, 255],
|
||||
[0, 0, 255, 255]
|
||||
])
|
||||
[0, 0, 255, 255],
|
||||
]),
|
||||
);
|
||||
const rgb = [...out.data].reduce<number[]>((acc, v, i) => {
|
||||
if (i % 4 === 0) acc.push(v);
|
||||
@@ -138,7 +146,7 @@ describe('grayscale', () => {
|
||||
expect(rgb).toEqual([76, 150, 29]);
|
||||
});
|
||||
|
||||
it('сохраняет альфу и не мутирует вход', () => {
|
||||
it("сохраняет альфу и не мутирует вход", () => {
|
||||
const img = makeImage(1, 1, [[10, 20, 30, 200]]);
|
||||
const out = grayscale(img);
|
||||
expect([...out.data]).toEqual([18, 18, 18, 200]);
|
||||
@@ -146,89 +154,91 @@ describe('grayscale', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('invert', () => {
|
||||
it('инвертирует RGB, не трогая альфу', () => {
|
||||
describe("invert", () => {
|
||||
it("инвертирует RGB, не трогая альфу", () => {
|
||||
const out = invert(makeImage(1, 1, [[10, 200, 30, 7]]));
|
||||
expect([...out.data]).toEqual([245, 55, 225, 7]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('brightnessContrast', () => {
|
||||
describe("brightnessContrast", () => {
|
||||
const pixel = (r: number) => makeImage(1, 1, [[r, r, r, 255]]);
|
||||
const red = (out: number[]) => [out[0], out[1], out[2]];
|
||||
|
||||
it('b=0, c=0 — тождественное преобразование', () => {
|
||||
it("b=0, c=0 — тождественное преобразование", () => {
|
||||
const out = brightnessContrast(pixel(77), 0, 0);
|
||||
expect(red([...out.data])).toEqual([77, 77, 77]);
|
||||
});
|
||||
|
||||
it('brightness +100 насыщает всё в белый', () => {
|
||||
it("brightness +100 насыщает всё в белый", () => {
|
||||
const out = brightnessContrast(pixel(10), 100, 0);
|
||||
expect(red([...out.data])).toEqual([255, 255, 255]);
|
||||
});
|
||||
|
||||
it('brightness -100 заливает чёрным', () => {
|
||||
it("brightness -100 заливает чёрным", () => {
|
||||
const out = brightnessContrast(pixel(240), -100, 0);
|
||||
expect(red([...out.data])).toEqual([0, 0, 0]);
|
||||
});
|
||||
|
||||
it('contrast -100 сводит всё к серому 128', () => {
|
||||
it("contrast -100 сводит всё к серому 128", () => {
|
||||
const out = brightnessContrast(pixel(30), 0, -100);
|
||||
expect(red([...out.data])).toEqual([128, 128, 128]);
|
||||
});
|
||||
|
||||
it('параметры вне диапазона клампятся', () => {
|
||||
it("параметры вне диапазона клампятся", () => {
|
||||
const out = brightnessContrast(pixel(10), 150, 0);
|
||||
expect(red([...out.data])).toEqual([255, 255, 255]);
|
||||
});
|
||||
|
||||
it('альфа не меняется', () => {
|
||||
it("альфа не меняется", () => {
|
||||
const out = brightnessContrast(makeImage(1, 1, [[10, 20, 30, 64]]), 50, 50);
|
||||
expect(out.data[3]).toBe(64);
|
||||
});
|
||||
});
|
||||
|
||||
describe('gammaCorrection', () => {
|
||||
it('гамма 1 — идентичность', () => {
|
||||
describe("gammaCorrection", () => {
|
||||
it("гамма 1 — идентичность", () => {
|
||||
const img = makeImage(1, 1, [[64, 128, 192, 255]]);
|
||||
expect([...gammaCorrection(img, 1).data]).toEqual([64, 128, 192, 255]);
|
||||
});
|
||||
it('гамма 2 удваивает яркость (64 → 128)', () => {
|
||||
it("гамма 2 удваивает яркость (64 → 128)", () => {
|
||||
const out = gammaCorrection(makeImage(1, 1, [[64, 64, 64, 255]]), 2);
|
||||
expect(out.data[0]).toBe(128);
|
||||
});
|
||||
});
|
||||
|
||||
describe('autoContrast', () => {
|
||||
it('растягивает диапазон [10..200] до [0..255]', () => {
|
||||
const out = autoContrast(makeImage(2, 1, [
|
||||
describe("autoContrast", () => {
|
||||
it("растягивает диапазон [10..200] до [0..255]", () => {
|
||||
const out = autoContrast(
|
||||
makeImage(2, 1, [
|
||||
[10, 10, 10, 255],
|
||||
[200, 200, 200, 255]
|
||||
]));
|
||||
[200, 200, 200, 255],
|
||||
]),
|
||||
);
|
||||
expect(out.data[0]).toBe(0);
|
||||
expect(out.data[4]).toBe(255);
|
||||
});
|
||||
});
|
||||
|
||||
describe('temperature', () => {
|
||||
it('положительная — теплее (красный ↑, синий ↓)', () => {
|
||||
describe("temperature", () => {
|
||||
it("положительная — теплее (красный ↑, синий ↓)", () => {
|
||||
const out = temperature(makeImage(1, 1, [[128, 128, 128, 255]]), 50);
|
||||
expect(out.data[0]).toBeGreaterThan(128);
|
||||
expect(out.data[2]).toBeLessThan(128);
|
||||
});
|
||||
it('нулевая температура не меняет', () => {
|
||||
it("нулевая температура не меняет", () => {
|
||||
const img = makeImage(1, 1, [[128, 128, 128, 255]]);
|
||||
expect([...temperature(img, 0).data]).toEqual([...img.data]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tint', () => {
|
||||
it('сила 100 на белом даёт чистый цвет', () => {
|
||||
const out = tint(makeImage(1, 1, [[255, 255, 255, 255]]), '#ff0000', 100);
|
||||
describe("tint", () => {
|
||||
it("сила 100 на белом даёт чистый цвет", () => {
|
||||
const out = tint(makeImage(1, 1, [[255, 255, 255, 255]]), "#ff0000", 100);
|
||||
expect([...out.data]).toEqual([255, 0, 0, 255]);
|
||||
});
|
||||
it('сила 0 — идентичность', () => {
|
||||
it("сила 0 — идентичность", () => {
|
||||
const img = makeImage(1, 1, [[100, 150, 200, 255]]);
|
||||
expect([...tint(img, '#ff0000', 0).data]).toEqual([...img.data]);
|
||||
expect([...tint(img, "#ff0000", 0).data]).toEqual([...img.data]);
|
||||
});
|
||||
});
|
||||
|
||||
+36
-21
@@ -1,9 +1,9 @@
|
||||
import { clonePixelImage, createPixelImage, type PixelImage } from './types';
|
||||
import { ToolError } from './errors';
|
||||
import { clonePixelImage, createPixelImage, type PixelImage } from "./types";
|
||||
import { ToolError } from "./errors";
|
||||
|
||||
export type RgbChannel = 'red' | 'green' | 'blue';
|
||||
export type RgbChannel = "red" | "green" | "blue";
|
||||
|
||||
export type ChannelSwapPair = 'r-g' | 'r-b' | 'g-b';
|
||||
export type ChannelSwapPair = "r-g" | "r-b" | "g-b";
|
||||
|
||||
export function setOpacity(img: PixelImage, percent: number): PixelImage {
|
||||
const factor = clamp(percent, 0, 100) / 100;
|
||||
@@ -74,7 +74,10 @@ function hueComponent(p: number, q: number, t: number): number {
|
||||
|
||||
const CHANNEL_INDEX: Record<RgbChannel, number> = { red: 0, green: 1, blue: 2 };
|
||||
|
||||
export function extractChannel(img: PixelImage, channel: RgbChannel): PixelImage {
|
||||
export function extractChannel(
|
||||
img: PixelImage,
|
||||
channel: RgbChannel,
|
||||
): PixelImage {
|
||||
const index = CHANNEL_INDEX[channel];
|
||||
const out = createPixelImage(img.width, img.height);
|
||||
for (let i = 0; i < out.data.length; i += 4) {
|
||||
@@ -88,12 +91,15 @@ export function extractChannel(img: PixelImage, channel: RgbChannel): PixelImage
|
||||
}
|
||||
|
||||
const SWAP_INDEX: Record<ChannelSwapPair, [number, number]> = {
|
||||
'r-g': [0, 1],
|
||||
'r-b': [0, 2],
|
||||
'g-b': [1, 2]
|
||||
"r-g": [0, 1],
|
||||
"r-b": [0, 2],
|
||||
"g-b": [1, 2],
|
||||
};
|
||||
|
||||
export function swapChannels(img: PixelImage, pair: ChannelSwapPair): PixelImage {
|
||||
export function swapChannels(
|
||||
img: PixelImage,
|
||||
pair: ChannelSwapPair,
|
||||
): PixelImage {
|
||||
const [a, b] = SWAP_INDEX[pair];
|
||||
const out = createPixelImage(img.width, img.height);
|
||||
for (let i = 0; i < out.data.length; i += 4) {
|
||||
@@ -108,11 +114,15 @@ export function swapChannels(img: PixelImage, pair: ChannelSwapPair): PixelImage
|
||||
return out;
|
||||
}
|
||||
|
||||
export function thresholdBlackWhite(img: PixelImage, thresholdPercent: number): PixelImage {
|
||||
export function thresholdBlackWhite(
|
||||
img: PixelImage,
|
||||
thresholdPercent: number,
|
||||
): PixelImage {
|
||||
const threshold = (clamp(thresholdPercent, 0, 100) / 100) * 255;
|
||||
const out = createPixelImage(img.width, img.height);
|
||||
for (let i = 0; i < out.data.length; i += 4) {
|
||||
const luma = 0.299 * img.data[i] + 0.587 * img.data[i + 1] + 0.114 * img.data[i + 2];
|
||||
const luma =
|
||||
0.299 * img.data[i] + 0.587 * img.data[i + 1] + 0.114 * img.data[i + 2];
|
||||
const v = luma >= threshold ? 255 : 0;
|
||||
out.data[i] = v;
|
||||
out.data[i + 1] = v;
|
||||
@@ -128,7 +138,9 @@ export function posterize(img: PixelImage, levels: number): PixelImage {
|
||||
const out = createPixelImage(img.width, img.height);
|
||||
for (let i = 0; i < out.data.length; i += 4) {
|
||||
for (let ch = 0; ch < 3; ch++) {
|
||||
out.data[i + ch] = Math.round(Math.round(img.data[i + ch] / stepSize) * stepSize);
|
||||
out.data[i + ch] = Math.round(
|
||||
Math.round(img.data[i + ch] / stepSize) * stepSize,
|
||||
);
|
||||
}
|
||||
out.data[i + 3] = img.data[i + 3];
|
||||
}
|
||||
@@ -139,14 +151,15 @@ export function twoColors(
|
||||
img: PixelImage,
|
||||
lightHex: string,
|
||||
darkHex: string,
|
||||
thresholdPercent: number
|
||||
thresholdPercent: number,
|
||||
): PixelImage {
|
||||
const [lr, lg, lb] = parseColor(lightHex);
|
||||
const [dr, dg, db] = parseColor(darkHex);
|
||||
const threshold = (clamp(thresholdPercent, 0, 100) / 100) * 255;
|
||||
const out = createPixelImage(img.width, img.height);
|
||||
for (let i = 0; i < out.data.length; i += 4) {
|
||||
const luma = 0.299 * img.data[i] + 0.587 * img.data[i + 1] + 0.114 * img.data[i + 2];
|
||||
const luma =
|
||||
0.299 * img.data[i] + 0.587 * img.data[i + 1] + 0.114 * img.data[i + 2];
|
||||
if (luma >= threshold) {
|
||||
out.data[i] = lr;
|
||||
out.data[i + 1] = lg;
|
||||
@@ -164,20 +177,21 @@ export function twoColors(
|
||||
function parseColor(hex: string): [number, number, number] {
|
||||
const match = /^#([0-9a-f]{6})$/i.exec(hex.trim());
|
||||
if (!match) {
|
||||
throw new ToolError('errors.badHex', { value: hex });
|
||||
throw new ToolError("errors.badHex", { value: hex });
|
||||
}
|
||||
const digits = match[1];
|
||||
return [
|
||||
parseInt(digits.slice(0, 2), 16),
|
||||
parseInt(digits.slice(2, 4), 16),
|
||||
parseInt(digits.slice(4, 6), 16)
|
||||
parseInt(digits.slice(4, 6), 16),
|
||||
];
|
||||
}
|
||||
|
||||
export function grayscale(img: PixelImage): PixelImage {
|
||||
const out = createPixelImage(img.width, img.height);
|
||||
for (let i = 0; i < img.data.length; i += 4) {
|
||||
const luma = 0.299 * img.data[i] + 0.587 * img.data[i + 1] + 0.114 * img.data[i + 2];
|
||||
const luma =
|
||||
0.299 * img.data[i] + 0.587 * img.data[i + 1] + 0.114 * img.data[i + 2];
|
||||
out.data[i] = luma;
|
||||
out.data[i + 1] = luma;
|
||||
out.data[i + 2] = luma;
|
||||
@@ -200,7 +214,7 @@ export function invert(img: PixelImage): PixelImage {
|
||||
export function brightnessContrast(
|
||||
img: PixelImage,
|
||||
brightness: number,
|
||||
contrast: number
|
||||
contrast: number,
|
||||
): PixelImage {
|
||||
const offset = (clamp(brightness, -100, 100) / 100) * 255;
|
||||
const c = (clamp(contrast, -100, 100) / 100) * 255;
|
||||
@@ -217,7 +231,8 @@ export function brightnessContrast(
|
||||
}
|
||||
|
||||
export function rgbToHex(r: number, g: number, b: number): string {
|
||||
const byte = (v: number) => clamp(Math.round(v), 0, 255).toString(16).padStart(2, '0');
|
||||
const byte = (v: number) =>
|
||||
clamp(Math.round(v), 0, 255).toString(16).padStart(2, "0");
|
||||
return `#${byte(r)}${byte(g)}${byte(b)}`;
|
||||
}
|
||||
|
||||
@@ -286,11 +301,11 @@ export function temperature(img: PixelImage, percent: number): PixelImage {
|
||||
export function tint(
|
||||
img: PixelImage,
|
||||
colorHex: string,
|
||||
strengthPercent: number
|
||||
strengthPercent: number,
|
||||
): PixelImage {
|
||||
const s = clamp(strengthPercent, 0, 100) / 100;
|
||||
const match = /^#([0-9a-f]{6})$/i.exec(colorHex.trim());
|
||||
if (!match) throw new ToolError('errors.badHex', { value: colorHex });
|
||||
if (!match) throw new ToolError("errors.badHex", { value: colorHex });
|
||||
const d = match[1];
|
||||
const tr = parseInt(d.slice(0, 2), 16) / 255;
|
||||
const tg = parseInt(d.slice(2, 4), 16) / 255;
|
||||
|
||||
@@ -1,34 +1,35 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { COMPRESSION_LEVELS, findMaxColorsWithin } from './compress';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { COMPRESSION_LEVELS, findMaxColorsWithin } from "./compress";
|
||||
|
||||
describe('COMPRESSION_LEVELS', () => {
|
||||
it('пресеты упорядочены по убыванию цветов', () => {
|
||||
describe("COMPRESSION_LEVELS", () => {
|
||||
it("пресеты упорядочены по убыванию цветов", () => {
|
||||
const values = Object.values(COMPRESSION_LEVELS);
|
||||
for (let i = 1; i < values.length; i++) expect(values[i - 1]).toBeGreaterThan(values[i]);
|
||||
for (let i = 1; i < values.length; i++)
|
||||
expect(values[i - 1]).toBeGreaterThan(values[i]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findMaxColorsWithin', () => {
|
||||
describe("findMaxColorsWithin", () => {
|
||||
const sizeOf = (k: number) => 1000 + k * 100; // размер растёт с k
|
||||
|
||||
it('подбирает максимум k, укладывающийся в цель', async () => {
|
||||
it("подбирает максимум k, укладывающийся в цель", async () => {
|
||||
// target 5200 → подходит k≤42 → ожидаем 42 при maxK≥42
|
||||
const k = await findMaxColorsWithin(5200, 256, async (kk) => sizeOf(kk));
|
||||
expect(k).toBeGreaterThanOrEqual(40);
|
||||
expect(sizeOf(k)).toBeLessThanOrEqual(5200);
|
||||
});
|
||||
|
||||
it('цель достигается даже на минимуме — возвращает 2', async () => {
|
||||
it("цель достигается даже на минимуме — возвращает 2", async () => {
|
||||
const k = await findMaxColorsWithin(50, 256, async (kk) => sizeOf(kk));
|
||||
expect(k).toBe(2);
|
||||
});
|
||||
|
||||
it('encodeSize null трактуется как провал', async () => {
|
||||
it("encodeSize null трактуется как провал", async () => {
|
||||
const k = await findMaxColorsWithin(999999, 16, async () => null);
|
||||
expect(k).toBe(2);
|
||||
});
|
||||
|
||||
it('бинарный поиск сходится быстрее полного перебора', async () => {
|
||||
it("бинарный поиск сходится быстрее полного перебора", async () => {
|
||||
let calls = 0;
|
||||
await findMaxColorsWithin(30000, 256, async (kk) => {
|
||||
calls++;
|
||||
|
||||
@@ -3,7 +3,7 @@ export const COMPRESSION_LEVELS = {
|
||||
light: 192,
|
||||
balanced: 96,
|
||||
strong: 44,
|
||||
extreme: 16
|
||||
extreme: 16,
|
||||
} as const;
|
||||
|
||||
export type CompressionLevel = keyof typeof COMPRESSION_LEVELS;
|
||||
@@ -16,7 +16,7 @@ export type CompressionLevel = keyof typeof COMPRESSION_LEVELS;
|
||||
export async function findMaxColorsWithin(
|
||||
targetBytes: number,
|
||||
maxK: number,
|
||||
encodeSize: (k: number) => Promise<number | null>
|
||||
encodeSize: (k: number) => Promise<number | null>,
|
||||
): Promise<number> {
|
||||
const hi = Math.max(2, Math.round(maxK));
|
||||
let ok = 2;
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { convolve, gaussianBlur, sharpen } from './convolution';
|
||||
import { makeImage } from './test-helpers';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { convolve, gaussianBlur, sharpen } from "./convolution";
|
||||
import { makeImage } from "./test-helpers";
|
||||
|
||||
const SHARPEN_KERNEL = [0, -1, 0, -1, 5, -1, 0, -1, 0];
|
||||
|
||||
describe('convolve', () => {
|
||||
it('крестовое ядро резкости на полоске из трёх пикселей', () => {
|
||||
describe("convolve", () => {
|
||||
it("крестовое ядро резкости на полоске из трёх пикселей", () => {
|
||||
const out = convolve(
|
||||
makeImage(3, 1, [
|
||||
[0, 0, 0, 255],
|
||||
[100, 100, 100, 255],
|
||||
[0, 0, 0, 255]
|
||||
[0, 0, 0, 255],
|
||||
]),
|
||||
SHARPEN_KERNEL,
|
||||
3
|
||||
3,
|
||||
);
|
||||
expect([...out.data.slice(4, 8)]).toEqual([255, 255, 255, 255]);
|
||||
expect([...out.data.slice(0, 4)]).toEqual([0, 0, 0, 255]);
|
||||
@@ -23,39 +23,41 @@ describe('convolve', () => {
|
||||
it.each([
|
||||
[2, 3],
|
||||
[3.5, 3],
|
||||
[0, 3]
|
||||
])('бросает ошибку на некорректном размере ядра %i', (size) => {
|
||||
expect(() => convolve(makeImage(1, 1, [[0, 0, 0, 255]]), [1], size as number)).toThrow();
|
||||
[0, 3],
|
||||
])("бросает ошибку на некорректном размере ядра %i", (size) => {
|
||||
expect(() =>
|
||||
convolve(makeImage(1, 1, [[0, 0, 0, 255]]), [1], size as number),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('sharpen', () => {
|
||||
it('сила 0 возвращает копию', () => {
|
||||
describe("sharpen", () => {
|
||||
it("сила 0 возвращает копию", () => {
|
||||
const img = makeImage(2, 2, [
|
||||
[10, 20, 30, 255],
|
||||
[40, 50, 60, 128],
|
||||
[70, 80, 90, 255],
|
||||
[100, 110, 120, 200]
|
||||
[100, 110, 120, 200],
|
||||
]);
|
||||
expect([...sharpen(img, 0).data]).toEqual([...img.data]);
|
||||
});
|
||||
|
||||
it('сила 100 применяет чистое ядро резкости', () => {
|
||||
it("сила 100 применяет чистое ядро резкости", () => {
|
||||
const out = sharpen(
|
||||
makeImage(3, 1, [
|
||||
[0, 0, 0, 255],
|
||||
[100, 100, 100, 255],
|
||||
[0, 0, 0, 255]
|
||||
[0, 0, 0, 255],
|
||||
]),
|
||||
100
|
||||
100,
|
||||
);
|
||||
expect(out.data[4]).toBe(255);
|
||||
expect(out.data[0]).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('gaussianBlur', () => {
|
||||
it('постоянное изображение не меняется ни в RGB, ни в альфе', () => {
|
||||
describe("gaussianBlur", () => {
|
||||
it("постоянное изображение не меняется ни в RGB, ни в альфе", () => {
|
||||
const img = makeImage(3, 3, new Array(9).fill([40, 80, 120, 128]));
|
||||
const out = gaussianBlur(img, 16);
|
||||
for (let i = 0; i < out.data.length; i++) {
|
||||
@@ -63,13 +65,15 @@ describe('gaussianBlur', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('далёкие углы остаются прозрачными, цвет центра не искажается', () => {
|
||||
it("далёкие углы остаются прозрачными, цвет центра не искажается", () => {
|
||||
const size = 61;
|
||||
const pixels: number[][] = [];
|
||||
for (let y = 0; y < size; y++) {
|
||||
for (let x = 0; x < size; x++) {
|
||||
pixels.push(
|
||||
x >= 26 && x <= 34 && y >= 26 && y <= 34 ? [200, 50, 25, 255] : [0, 0, 0, 0]
|
||||
x >= 26 && x <= 34 && y >= 26 && y <= 34
|
||||
? [200, 50, 25, 255]
|
||||
: [0, 0, 0, 0],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -85,50 +89,50 @@ describe('gaussianBlur', () => {
|
||||
expect(out.data[center + 2]).toBe(25);
|
||||
});
|
||||
|
||||
it('симметричный вход даёт симметричный результат', () => {
|
||||
it("симметричный вход даёт симметричный результат", () => {
|
||||
const leftByRow = [
|
||||
[
|
||||
[255, 0, 0, 255],
|
||||
[10, 20, 30, 255],
|
||||
[64, 64, 64, 64],
|
||||
[5, 5, 5, 200]
|
||||
[5, 5, 5, 200],
|
||||
],
|
||||
[
|
||||
[10, 20, 30, 255],
|
||||
[200, 100, 50, 255],
|
||||
[1, 2, 3, 4],
|
||||
[90, 90, 90, 250]
|
||||
[90, 90, 90, 250],
|
||||
],
|
||||
[
|
||||
[64, 64, 64, 64],
|
||||
[1, 2, 3, 4],
|
||||
[128, 128, 128, 128],
|
||||
[40, 40, 40, 240]
|
||||
[40, 40, 40, 240],
|
||||
],
|
||||
[
|
||||
[200, 100, 50, 255],
|
||||
[90, 90, 90, 250],
|
||||
[40, 40, 40, 240],
|
||||
[7, 7, 7, 255]
|
||||
[7, 7, 7, 255],
|
||||
],
|
||||
[
|
||||
[10, 20, 30, 255],
|
||||
[1, 2, 3, 4],
|
||||
[64, 64, 64, 64],
|
||||
[90, 90, 90, 250]
|
||||
[90, 90, 90, 250],
|
||||
],
|
||||
[
|
||||
[64, 64, 64, 64],
|
||||
[200, 100, 50, 255],
|
||||
[5, 5, 5, 200],
|
||||
[1, 2, 3, 4]
|
||||
[1, 2, 3, 4],
|
||||
],
|
||||
[
|
||||
[5, 5, 5, 200],
|
||||
[40, 40, 40, 240],
|
||||
[90, 90, 90, 250],
|
||||
[128, 128, 128, 128]
|
||||
]
|
||||
[128, 128, 128, 128],
|
||||
],
|
||||
];
|
||||
const pixels: number[][] = [];
|
||||
for (let y = 0; y < 7; y++) {
|
||||
@@ -146,7 +150,7 @@ describe('gaussianBlur', () => {
|
||||
blurred.data[ri],
|
||||
blurred.data[ri + 1],
|
||||
blurred.data[ri + 2],
|
||||
blurred.data[ri + 3]
|
||||
blurred.data[ri + 3],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import { clonePixelImage, createPixelImage, type PixelImage } from './types';
|
||||
import { ToolError } from './errors';
|
||||
import { clonePixelImage, createPixelImage, type PixelImage } from "./types";
|
||||
import { ToolError } from "./errors";
|
||||
|
||||
type Plane = Float64Array;
|
||||
|
||||
export function convolve(
|
||||
img: PixelImage,
|
||||
kernel: readonly number[],
|
||||
size: number
|
||||
size: number,
|
||||
): PixelImage {
|
||||
if (!Number.isInteger(size) || size < 1 || size % 2 === 0) {
|
||||
throw new ToolError('errors.radiusInt');
|
||||
throw new ToolError("errors.radiusInt");
|
||||
}
|
||||
if (kernel.length !== size * size) {
|
||||
throw new ToolError('errors.kernelSize');
|
||||
throw new ToolError("errors.kernelSize");
|
||||
}
|
||||
const half = Math.floor(size / 2);
|
||||
const out = createPixelImage(img.width, img.height);
|
||||
@@ -24,12 +24,14 @@ export function convolve(
|
||||
const sy = clampInt(y + ky - half, 0, img.height - 1);
|
||||
for (let kx = 0; kx < size; kx++) {
|
||||
const sx = clampInt(x + kx - half, 0, img.width - 1);
|
||||
acc += img.data[(sy * img.width + sx) * 4 + ch] * kernel[ky * size + kx];
|
||||
acc +=
|
||||
img.data[(sy * img.width + sx) * 4 + ch] * kernel[ky * size + kx];
|
||||
}
|
||||
}
|
||||
out.data[(y * out.width + x) * 4 + ch] = acc;
|
||||
}
|
||||
out.data[(y * out.width + x) * 4 + 3] = img.data[(y * img.width + x) * 4 + 3];
|
||||
out.data[(y * out.width + x) * 4 + 3] =
|
||||
img.data[(y * img.width + x) * 4 + 3];
|
||||
}
|
||||
}
|
||||
return out;
|
||||
@@ -103,7 +105,13 @@ export function gaussianBlur(img: PixelImage, radiusPx: number): PixelImage {
|
||||
return out;
|
||||
}
|
||||
|
||||
function blurPlanePass(plane: Plane, tmp: Plane, w: number, h: number, r: number): void {
|
||||
function blurPlanePass(
|
||||
plane: Plane,
|
||||
tmp: Plane,
|
||||
w: number,
|
||||
h: number,
|
||||
r: number,
|
||||
): void {
|
||||
blurPlaneHorizontal(plane, tmp, w, h, r);
|
||||
blurPlaneVertical(tmp, plane, w, h, r);
|
||||
}
|
||||
@@ -113,7 +121,7 @@ function blurPlaneHorizontal(
|
||||
dst: Plane,
|
||||
w: number,
|
||||
h: number,
|
||||
r: number
|
||||
r: number,
|
||||
): void {
|
||||
const div = 2 * r + 1;
|
||||
const inv = 1 / div;
|
||||
@@ -137,7 +145,7 @@ function blurPlaneVertical(
|
||||
dst: Plane,
|
||||
w: number,
|
||||
h: number,
|
||||
r: number
|
||||
r: number,
|
||||
): void {
|
||||
const div = 2 * r + 1;
|
||||
const inv = 1 / div;
|
||||
@@ -160,7 +168,8 @@ function boxesForGauss(sigma: number, boxes: number): number[] {
|
||||
let wl = Math.floor(wIdeal);
|
||||
if (wl % 2 === 0) wl--;
|
||||
const wu = wl + 2;
|
||||
const mIdeal = (12 * sigma * sigma - boxes * wl * wl - boxes * wl - boxes) / (4 * wl + 4);
|
||||
const mIdeal =
|
||||
(12 * sigma * sigma - boxes * wl * wl - boxes * wl - boxes) / (4 * wl + 4);
|
||||
const m = Math.round(mIdeal);
|
||||
const sizes: number[] = [];
|
||||
for (let i = 0; i < boxes; i++) {
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { formatStamp } from './datefmt';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { formatStamp } from "./datefmt";
|
||||
|
||||
const d = new Date(2026, 7, 25, 9, 5, 3);
|
||||
|
||||
describe('formatStamp', () => {
|
||||
it('разворачивает все базовые токены', () => {
|
||||
expect(formatStamp(d, 'YYYY-MM-DD hh:mm:ss')).toBe('2026-08-25 09:05:03');
|
||||
describe("formatStamp", () => {
|
||||
it("разворачивает все базовые токены", () => {
|
||||
expect(formatStamp(d, "YYYY-MM-DD hh:mm:ss")).toBe("2026-08-25 09:05:03");
|
||||
});
|
||||
|
||||
it('произвольный текст между токенами сохраняется', () => {
|
||||
expect(formatStamp(d, 'DD.MM.YYYY')).toBe('25.08.2026');
|
||||
expect(formatStamp(d, 'YYYY год, MM месяц')).toBe('2026 год, 08 месяц');
|
||||
it("произвольный текст между токенами сохраняется", () => {
|
||||
expect(formatStamp(d, "DD.MM.YYYY")).toBe("25.08.2026");
|
||||
expect(formatStamp(d, "YYYY год, MM месяц")).toBe("2026 год, 08 месяц");
|
||||
});
|
||||
|
||||
it('неизвестные последовательности не трогаются', () => {
|
||||
expect(formatStamp(d, 'YYYYYY MMМ')).toBe('2026YY 08М');
|
||||
it("неизвестные последовательности не трогаются", () => {
|
||||
expect(formatStamp(d, "YYYYYY MMМ")).toBe("2026YY 08М");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
const PAD2 = (n: number) => String(n).padStart(2, '0');
|
||||
const PAD2 = (n: number) => String(n).padStart(2, "0");
|
||||
|
||||
/**
|
||||
* Мини-форматтер штампа даты: токены YYYY MM DD hh mm ss заменяются
|
||||
@@ -7,17 +7,17 @@ const PAD2 = (n: number) => String(n).padStart(2, '0');
|
||||
export function formatStamp(date: Date, pattern: string): string {
|
||||
return pattern.replace(/YYYY|MM|DD|hh|mm|ss/g, (token) => {
|
||||
switch (token) {
|
||||
case 'YYYY':
|
||||
case "YYYY":
|
||||
return String(date.getFullYear());
|
||||
case 'MM':
|
||||
case "MM":
|
||||
return PAD2(date.getMonth() + 1);
|
||||
case 'DD':
|
||||
case "DD":
|
||||
return PAD2(date.getDate());
|
||||
case 'hh':
|
||||
case "hh":
|
||||
return PAD2(date.getHours());
|
||||
case 'mm':
|
||||
case "mm":
|
||||
return PAD2(date.getMinutes());
|
||||
case 'ss':
|
||||
case "ss":
|
||||
return PAD2(date.getSeconds());
|
||||
default:
|
||||
return token;
|
||||
|
||||
+94
-33
@@ -1,33 +1,44 @@
|
||||
import { ToolError } from './errors';
|
||||
import type { PixelImage } from './types';
|
||||
import { anchorOrigin, tileGrid, wrapText, type Position9 } from './textdraw';
|
||||
import { ToolError } from "./errors";
|
||||
import type { PixelImage } from "./types";
|
||||
import { anchorOrigin, tileGrid, wrapText, type Position9 } from "./textdraw";
|
||||
|
||||
export type TextFont = 'sans' | 'serif' | 'mono';
|
||||
export type TextFont = "sans" | "serif" | "mono";
|
||||
|
||||
const FONT_STACKS: Record<TextFont, string> = {
|
||||
sans: 'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',
|
||||
serif: 'Georgia, "Times New Roman", serif',
|
||||
mono: 'ui-monospace, "Cascadia Code", Consolas, monospace'
|
||||
mono: 'ui-monospace, "Cascadia Code", Consolas, monospace',
|
||||
};
|
||||
|
||||
function ctx2d(w: number, h: number): { canvas: HTMLCanvasElement; ctx: CanvasRenderingContext2D } {
|
||||
const canvas = document.createElement('canvas');
|
||||
function ctx2d(
|
||||
w: number,
|
||||
h: number,
|
||||
): { canvas: HTMLCanvasElement; ctx: CanvasRenderingContext2D } {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||
if (!ctx) throw new ToolError('errors.noCanvasCtx');
|
||||
const ctx = canvas.getContext("2d", { willReadFrequently: true });
|
||||
if (!ctx) throw new ToolError("errors.noCanvasCtx");
|
||||
return { canvas, ctx };
|
||||
}
|
||||
|
||||
function toPixelImage(canvas: HTMLCanvasElement): PixelImage {
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) throw new ToolError('errors.noCanvasCtx');
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) throw new ToolError("errors.noCanvasCtx");
|
||||
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||
return { width: imageData.width, height: imageData.height, data: imageData.data };
|
||||
return {
|
||||
width: imageData.width,
|
||||
height: imageData.height,
|
||||
data: imageData.data,
|
||||
};
|
||||
}
|
||||
|
||||
export function fontString(size: number, font: TextFont, bold: boolean): string {
|
||||
return `${bold ? '700 ' : '400 '}${size}px ${FONT_STACKS[font]}`;
|
||||
export function fontString(
|
||||
size: number,
|
||||
font: TextFont,
|
||||
bold: boolean,
|
||||
): string {
|
||||
return `${bold ? "700 " : "400 "}${size}px ${FONT_STACKS[font]}`;
|
||||
}
|
||||
|
||||
export interface TextBlockOptions {
|
||||
@@ -46,9 +57,16 @@ export interface TextBlockOptions {
|
||||
}
|
||||
|
||||
/** Одна надпись (с автопереносом и опциональной плашкой) поверх изображения. */
|
||||
export function drawTextBlock(img: PixelImage, o: TextBlockOptions): PixelImage {
|
||||
export function drawTextBlock(
|
||||
img: PixelImage,
|
||||
o: TextBlockOptions,
|
||||
): PixelImage {
|
||||
const { canvas, ctx } = ctx2d(img.width, img.height);
|
||||
ctx.putImageData(new ImageData(new Uint8ClampedArray(img.data), img.width, img.height), 0, 0);
|
||||
ctx.putImageData(
|
||||
new ImageData(new Uint8ClampedArray(img.data), img.width, img.height),
|
||||
0,
|
||||
0,
|
||||
);
|
||||
|
||||
ctx.font = fontString(o.fontSize, o.font, o.bold);
|
||||
const maxWidth = ((o.maxWidthPercent ?? 90) / 100) * img.width;
|
||||
@@ -57,11 +75,18 @@ export function drawTextBlock(img: PixelImage, o: TextBlockOptions): PixelImage
|
||||
const ascent = o.fontSize * 0.8;
|
||||
const blockW = Math.min(
|
||||
maxWidth,
|
||||
lines.reduce((max, s) => Math.max(max, ctx.measureText(s).width), 0)
|
||||
lines.reduce((max, s) => Math.max(max, ctx.measureText(s).width), 0),
|
||||
);
|
||||
const blockH = lines.length * lineH;
|
||||
|
||||
const origin = anchorOrigin(o.position, blockW, blockH, img.width, img.height, o.margin);
|
||||
const origin = anchorOrigin(
|
||||
o.position,
|
||||
blockW,
|
||||
blockH,
|
||||
img.width,
|
||||
img.height,
|
||||
o.margin,
|
||||
);
|
||||
|
||||
ctx.save();
|
||||
ctx.globalAlpha = o.opacityPercent / 100;
|
||||
@@ -77,7 +102,7 @@ export function drawTextBlock(img: PixelImage, o: TextBlockOptions): PixelImage
|
||||
ctx.globalAlpha = o.opacityPercent / 100;
|
||||
}
|
||||
ctx.fillStyle = o.color;
|
||||
ctx.textBaseline = 'alphabetic';
|
||||
ctx.textBaseline = "alphabetic";
|
||||
lines.forEach((line, i) => {
|
||||
ctx.fillText(line, origin.x, origin.y + ascent + i * lineH);
|
||||
});
|
||||
@@ -86,7 +111,10 @@ export function drawTextBlock(img: PixelImage, o: TextBlockOptions): PixelImage
|
||||
return toPixelImage(canvas);
|
||||
}
|
||||
|
||||
export interface TileTextOptions extends Omit<TextBlockOptions, 'position' | 'margin' | 'angleDeg'> {
|
||||
export interface TileTextOptions extends Omit<
|
||||
TextBlockOptions,
|
||||
"position" | "margin" | "angleDeg"
|
||||
> {
|
||||
stepX: number;
|
||||
stepY: number;
|
||||
angleDeg: number;
|
||||
@@ -110,7 +138,10 @@ export function renderTextToImage(o: TextToImageOptions): PixelImage {
|
||||
measure.font = fontString(o.fontSize, o.font, o.bold);
|
||||
const maxWidth = o.maxTextWidth ?? 4000;
|
||||
const lines = [o.text];
|
||||
const textW = Math.min(maxWidth, Math.max(measure.measureText(o.text).width, 1));
|
||||
const textW = Math.min(
|
||||
maxWidth,
|
||||
Math.max(measure.measureText(o.text).width, 1),
|
||||
);
|
||||
const lineH = o.fontSize * 1.25;
|
||||
|
||||
const w = Math.max(1, Math.ceil(textW + o.padding * 2));
|
||||
@@ -123,7 +154,7 @@ export function renderTextToImage(o: TextToImageOptions): PixelImage {
|
||||
}
|
||||
ctx.font = fontString(o.fontSize, o.font, o.bold);
|
||||
ctx.fillStyle = o.color;
|
||||
ctx.textBaseline = 'top';
|
||||
ctx.textBaseline = "top";
|
||||
lines.forEach((line) => ctx.fillText(line, o.padding, o.padding));
|
||||
return toPixelImage(canvas);
|
||||
}
|
||||
@@ -132,8 +163,8 @@ export function renderTextToImage(o: TextToImageOptions): PixelImage {
|
||||
export function renderEmoji(symbol: string, size: number): PixelImage {
|
||||
const { canvas, ctx } = ctx2d(size, size);
|
||||
ctx.font = `${Math.round(size * 0.72)}px "Apple Color Emoji","Segoe UI Emoji","Noto Color Emoji",sans-serif`;
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.textAlign = "center";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillText(symbol, size / 2, size / 2 + size * 0.04);
|
||||
return toPixelImage(canvas);
|
||||
}
|
||||
@@ -147,19 +178,37 @@ export interface ImageWatermarkOptions {
|
||||
}
|
||||
|
||||
/** Картинка-знак поверх изображения: масштаб от ширины холста, позиция 3×3. */
|
||||
export function drawImageWatermark(img: PixelImage, o: ImageWatermarkOptions): PixelImage {
|
||||
export function drawImageWatermark(
|
||||
img: PixelImage,
|
||||
o: ImageWatermarkOptions,
|
||||
): PixelImage {
|
||||
const { canvas, ctx } = ctx2d(img.width, img.height);
|
||||
ctx.putImageData(new ImageData(new Uint8ClampedArray(img.data), img.width, img.height), 0, 0);
|
||||
ctx.putImageData(
|
||||
new ImageData(new Uint8ClampedArray(img.data), img.width, img.height),
|
||||
0,
|
||||
0,
|
||||
);
|
||||
|
||||
const w = Math.max(1, Math.round((img.width * o.scalePercent) / 100));
|
||||
const h = Math.max(1, Math.round((w * o.mark.height) / o.mark.width));
|
||||
const origin = anchorOrigin(o.position, w, h, img.width, img.height, o.margin);
|
||||
const origin = anchorOrigin(
|
||||
o.position,
|
||||
w,
|
||||
h,
|
||||
img.width,
|
||||
img.height,
|
||||
o.margin,
|
||||
);
|
||||
|
||||
const markCanvas = ctx2d(o.mark.width, o.mark.height);
|
||||
markCanvas.ctx.putImageData(
|
||||
new ImageData(new Uint8ClampedArray(o.mark.data), o.mark.width, o.mark.height),
|
||||
new ImageData(
|
||||
new Uint8ClampedArray(o.mark.data),
|
||||
o.mark.width,
|
||||
o.mark.height,
|
||||
),
|
||||
0,
|
||||
0,
|
||||
0
|
||||
);
|
||||
|
||||
ctx.save();
|
||||
@@ -173,21 +222,33 @@ export function drawImageWatermark(img: PixelImage, o: ImageWatermarkOptions): P
|
||||
/** Повторяющаяся диагональная плитка текста на весь холст. */
|
||||
export function drawTextTile(img: PixelImage, o: TileTextOptions): PixelImage {
|
||||
const { canvas, ctx } = ctx2d(img.width, img.height);
|
||||
ctx.putImageData(new ImageData(new Uint8ClampedArray(img.data), img.width, img.height), 0, 0);
|
||||
ctx.putImageData(
|
||||
new ImageData(new Uint8ClampedArray(img.data), img.width, img.height),
|
||||
0,
|
||||
0,
|
||||
);
|
||||
|
||||
ctx.font = fontString(o.fontSize, o.font, o.bold);
|
||||
const sample = o.text.length > 0 ? o.text : ' ';
|
||||
const sample = o.text.length > 0 ? o.text : " ";
|
||||
const blockW = ctx.measureText(sample).width;
|
||||
const blockH = o.fontSize * 1.4;
|
||||
|
||||
const points = tileGrid(img.width, img.height, o.angleDeg, o.stepX, o.stepY, blockW, blockH);
|
||||
const points = tileGrid(
|
||||
img.width,
|
||||
img.height,
|
||||
o.angleDeg,
|
||||
o.stepX,
|
||||
o.stepY,
|
||||
blockW,
|
||||
blockH,
|
||||
);
|
||||
|
||||
ctx.save();
|
||||
ctx.translate(img.width / 2, img.height / 2);
|
||||
ctx.rotate((o.angleDeg * Math.PI) / 180);
|
||||
ctx.globalAlpha = o.opacityPercent / 100;
|
||||
ctx.fillStyle = o.color;
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.textBaseline = "middle";
|
||||
for (const p of points) {
|
||||
ctx.fillText(sample, p.x - blockW / 2, p.y);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { vignette } from './effects';
|
||||
import { makeImage } from './test-helpers';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { vignette } from "./effects";
|
||||
import { makeImage } from "./test-helpers";
|
||||
|
||||
describe('vignette', () => {
|
||||
it('сила 0 — идентичное преобразование', () => {
|
||||
describe("vignette", () => {
|
||||
it("сила 0 — идентичное преобразование", () => {
|
||||
const img = makeImage(3, 3, new Array(9).fill([200, 100, 50, 255]));
|
||||
expect([...vignette(img, 0).data]).toEqual([...img.data]);
|
||||
});
|
||||
|
||||
it('углы темнее центра', () => {
|
||||
it("углы темнее центра", () => {
|
||||
const img = makeImage(7, 7, new Array(49).fill([200, 200, 200, 255]));
|
||||
const out = vignette(img, 80);
|
||||
const centerR = out.data[(3 * 7 + 3) * 4];
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { clonePixelImage, createPixelImage, type PixelImage } from './types';
|
||||
import { clonePixelImage, createPixelImage, type PixelImage } from "./types";
|
||||
|
||||
export function vignette(img: PixelImage, strengthPercent: number): PixelImage {
|
||||
const strength = Math.min(Math.max(strengthPercent, 0), 100) / 100;
|
||||
|
||||
@@ -11,7 +11,7 @@ export class ToolError extends Error {
|
||||
|
||||
constructor(key: string, vars?: ErrorVars) {
|
||||
super(key);
|
||||
this.name = 'ToolError';
|
||||
this.name = "ToolError";
|
||||
this.key = key;
|
||||
this.vars = vars;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
changeCanvasSize,
|
||||
contentBounds,
|
||||
@@ -6,9 +6,9 @@ import {
|
||||
forceOrientation,
|
||||
padToRatio,
|
||||
symmetricCopy,
|
||||
trimToContent
|
||||
} from './geometry';
|
||||
import { makeImage } from './test-helpers';
|
||||
trimToContent,
|
||||
} from "./geometry";
|
||||
import { makeImage } from "./test-helpers";
|
||||
|
||||
const bordered = () => {
|
||||
// 4×4: рамка из прозрачных пикселей вокруг красного центра 2×2
|
||||
@@ -23,12 +23,12 @@ const bordered = () => {
|
||||
return img;
|
||||
};
|
||||
|
||||
describe('contentBounds / trimToContent', () => {
|
||||
it('границы по порогу альфы', () => {
|
||||
describe("contentBounds / trimToContent", () => {
|
||||
it("границы по порогу альфы", () => {
|
||||
expect(contentBounds(bordered(), 0)).toEqual({ x: 1, y: 1, w: 2, h: 2 });
|
||||
});
|
||||
|
||||
it('trim обрезает поля и сохраняет содержимое', () => {
|
||||
it("trim обрезает поля и сохраняет содержимое", () => {
|
||||
const out = trimToContent(bordered(), 0);
|
||||
expect(out.width).toBe(2);
|
||||
expect(out.height).toBe(2);
|
||||
@@ -36,7 +36,7 @@ describe('contentBounds / trimToContent', () => {
|
||||
expect(out.data[3]).toBe(255);
|
||||
});
|
||||
|
||||
it('полностью прозрачное изображение → 1×1', () => {
|
||||
it("полностью прозрачное изображение → 1×1", () => {
|
||||
const empty = makeImage(3, 3, new Array(9).fill([0, 0, 0, 0]));
|
||||
const out = trimToContent(empty, 0);
|
||||
expect(out.width).toBe(1);
|
||||
@@ -44,43 +44,43 @@ describe('contentBounds / trimToContent', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('changeCanvasSize', () => {
|
||||
describe("changeCanvasSize", () => {
|
||||
const img = makeImage(2, 2, [
|
||||
[1, 1, 1, 255],
|
||||
[2, 2, 2, 255],
|
||||
[3, 3, 3, 255],
|
||||
[4, 4, 4, 255]
|
||||
[4, 4, 4, 255],
|
||||
]);
|
||||
|
||||
it('увеличение с якорем center — прозрачные поля со всех сторон', () => {
|
||||
const out = changeCanvasSize(img, 4, 4, 'center');
|
||||
it("увеличение с якорем center — прозрачные поля со всех сторон", () => {
|
||||
const out = changeCanvasSize(img, 4, 4, "center");
|
||||
expect(out.width).toBe(4);
|
||||
expect(out.data[3]).toBe(0);
|
||||
expect(out.data[(1 * 4 + 1) * 4 + 3]).toBe(255);
|
||||
});
|
||||
|
||||
it('увеличение с якорем top-left — контент прижат в угол', () => {
|
||||
const out = changeCanvasSize(img, 4, 4, 'top-left');
|
||||
it("увеличение с якорем top-left — контент прижат в угол", () => {
|
||||
const out = changeCanvasSize(img, 4, 4, "top-left");
|
||||
expect(out.data[3]).toBe(255);
|
||||
expect(out.data[(3 * 4 + 3) * 4 + 3]).toBe(0);
|
||||
});
|
||||
|
||||
it('уменьшение обрезает как кроп от якоря bottom-right', () => {
|
||||
const out = changeCanvasSize(img, 1, 1, 'bottom-right');
|
||||
it("уменьшение обрезает как кроп от якоря bottom-right", () => {
|
||||
const out = changeCanvasSize(img, 1, 1, "bottom-right");
|
||||
expect(out.data[0]).toBe(4);
|
||||
});
|
||||
});
|
||||
|
||||
describe('соотношение сторон', () => {
|
||||
describe("соотношение сторон", () => {
|
||||
const wide = makeImage(400, 200, new Array(80000).fill([9, 9, 9, 255]));
|
||||
|
||||
it('cropToRatio 1:1 из 2:1 → квадрат по высоте', () => {
|
||||
it("cropToRatio 1:1 из 2:1 → квадрат по высоте", () => {
|
||||
const out = cropToRatio(wide, 1);
|
||||
expect(out.width).toBe(200);
|
||||
expect(out.height).toBe(200);
|
||||
});
|
||||
|
||||
it('padToRatio 1:1 из 2:1 → квадрат с прозрачными полями', () => {
|
||||
it("padToRatio 1:1 из 2:1 → квадрат с прозрачными полями", () => {
|
||||
const out = padToRatio(wide, 1);
|
||||
expect(out.width).toBe(400);
|
||||
expect(out.height).toBe(400);
|
||||
@@ -89,39 +89,39 @@ describe('соотношение сторон', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('forceOrientation / symmetricCopy', () => {
|
||||
it('широкое становится высоким поворотом', () => {
|
||||
describe("forceOrientation / symmetricCopy", () => {
|
||||
it("широкое становится высоким поворотом", () => {
|
||||
const wide = makeImage(300, 100, new Array(30000).fill([5, 5, 5, 255]));
|
||||
const out = forceOrientation(wide, 'portrait');
|
||||
const out = forceOrientation(wide, "portrait");
|
||||
expect(out.width).toBe(100);
|
||||
expect(out.height).toBe(300);
|
||||
});
|
||||
|
||||
it('квадрат не поворачивается', () => {
|
||||
it("квадрат не поворачивается", () => {
|
||||
const sq = makeImage(50, 50, new Array(2500).fill([5, 5, 5, 255]));
|
||||
const out = forceOrientation(sq, 'portrait');
|
||||
const out = forceOrientation(sq, "portrait");
|
||||
expect(out.width).toBe(50);
|
||||
expect(out.height).toBe(50);
|
||||
});
|
||||
|
||||
it('симметричная копия удваивает ширину и зеркалит правую половину', () => {
|
||||
it("симметричная копия удваивает ширину и зеркалит правую половину", () => {
|
||||
const img = makeImage(2, 1, [
|
||||
[10, 0, 0, 255],
|
||||
[20, 0, 0, 255]
|
||||
[20, 0, 0, 255],
|
||||
]);
|
||||
const out = symmetricCopy(img, 'vertical', 'left');
|
||||
const out = symmetricCopy(img, "vertical", "left");
|
||||
expect(out.width).toBe(4);
|
||||
expect(out.data[0]).toBe(10);
|
||||
expect(out.data[8]).toBe(20); // пиксель 2 = зеркало начала
|
||||
expect(out.data[12]).toBe(10); // пиксель 3 = зеркало конца
|
||||
});
|
||||
|
||||
it('вертикальная ось удваивает высоту', () => {
|
||||
it("вертикальная ось удваивает высоту", () => {
|
||||
const img = makeImage(1, 2, [
|
||||
[10, 0, 0, 255],
|
||||
[30, 0, 0, 255]
|
||||
[30, 0, 0, 255],
|
||||
]);
|
||||
const out = symmetricCopy(img, 'horizontal', 'top');
|
||||
const out = symmetricCopy(img, "horizontal", "top");
|
||||
expect(out.height).toBe(4);
|
||||
expect(out.data[(2 * 1 + 0) * 4]).toBe(30); // строка 2 = зеркало строки 1
|
||||
expect(out.data[(3 * 1 + 0) * 4]).toBe(10); // строка 3 = зеркало строки 0
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { colorSpectrum, drawGrid, randomColorBlocks } from './gen-tools';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { colorSpectrum, drawGrid, randomColorBlocks } from "./gen-tools";
|
||||
|
||||
describe('colorSpectrum', () => {
|
||||
it('горизонтальный: левый край красный (hue 0)', () => {
|
||||
const img = colorSpectrum(100, 10, 'horizontal', 100, 50);
|
||||
describe("colorSpectrum", () => {
|
||||
it("горизонтальный: левый край красный (hue 0)", () => {
|
||||
const img = colorSpectrum(100, 10, "horizontal", 100, 50);
|
||||
expect(img.data[0]).toBeGreaterThan(200);
|
||||
expect(img.data[1]).toBeLessThan(60);
|
||||
});
|
||||
|
||||
it('вертикальный: зелёный максимум около hue 120°', () => {
|
||||
const img = colorSpectrum(10, 100, 'vertical', 100, 50);
|
||||
it("вертикальный: зелёный максимум около hue 120°", () => {
|
||||
const img = colorSpectrum(10, 100, "vertical", 100, 50);
|
||||
const rowHue120 = Math.round((120 / 360) * 99);
|
||||
const g = img.data[(rowHue120 * 10 + 5) * 4 + 1];
|
||||
expect(g).toBeGreaterThan(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('randomColorBlocks', () => {
|
||||
it('детерминирован по seed и блоки однотонные', () => {
|
||||
describe("randomColorBlocks", () => {
|
||||
it("детерминирован по seed и блоки однотонные", () => {
|
||||
const a = randomColorBlocks(64, 64, 16, 7);
|
||||
const b = randomColorBlocks(64, 64, 16, 7);
|
||||
expect([...a.data]).toEqual([...b.data]);
|
||||
@@ -27,18 +27,18 @@ describe('randomColorBlocks', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('drawGrid', () => {
|
||||
it('линии на пересечениях непрозрачны, фон прозрачен', () => {
|
||||
const out = drawGrid(100, 100, 4, 4, 2, '#000000', true);
|
||||
describe("drawGrid", () => {
|
||||
it("линии на пересечениях непрозрачны, фон прозрачен", () => {
|
||||
const out = drawGrid(100, 100, 4, 4, 2, "#000000", true);
|
||||
expect(out.data[0]).toBe(0);
|
||||
expect(out.data[3]).toBe(255); // (0,0) на линии
|
||||
const mid = ((53 * 100) + 53) * 4;
|
||||
const mid = (53 * 100 + 53) * 4;
|
||||
expect(out.data[mid + 3]).toBe(0); // между линиями прозрачн
|
||||
});
|
||||
|
||||
it('белый непрозрачный фон при transparentBg=false', () => {
|
||||
const out = drawGrid(20, 20, 2, 2, 1, '#000000', false);
|
||||
const mid = ((5 * 20) + 5) * 4;
|
||||
it("белый непрозрачный фон при transparentBg=false", () => {
|
||||
const out = drawGrid(20, 20, 2, 2, 1, "#000000", false);
|
||||
const mid = (5 * 20 + 5) * 4;
|
||||
expect(out.data[mid]).toBe(255);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,23 +1,26 @@
|
||||
import { createPixelImage, type PixelImage } from './types';
|
||||
import { hslToRgb } from './palette';
|
||||
import { mulberry32 } from './pixel-fx';
|
||||
import { createPixelImage, type PixelImage } from "./types";
|
||||
import { hslToRgb } from "./palette";
|
||||
import { mulberry32 } from "./pixel-fx";
|
||||
|
||||
/** Радужный спектр: оттенок 0..360 вдоль выбранной оси. */
|
||||
export function colorSpectrum(
|
||||
width: number,
|
||||
height: number,
|
||||
direction: 'horizontal' | 'vertical',
|
||||
direction: "horizontal" | "vertical",
|
||||
saturationPercent: number,
|
||||
lightnessPercent: number
|
||||
lightnessPercent: number,
|
||||
): PixelImage {
|
||||
const out = createPixelImage(width, height);
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
const t = direction === 'vertical' ? y / Math.max(1, height - 1) : x / Math.max(1, width - 1);
|
||||
const t =
|
||||
direction === "vertical"
|
||||
? y / Math.max(1, height - 1)
|
||||
: x / Math.max(1, width - 1);
|
||||
const { r, g, b } = hslToRgb({
|
||||
h: t * 360,
|
||||
s: saturationPercent / 100,
|
||||
l: lightnessPercent / 100
|
||||
l: lightnessPercent / 100,
|
||||
});
|
||||
const di = (y * width + x) * 4;
|
||||
out.data[di] = r;
|
||||
@@ -34,7 +37,7 @@ export function randomColorBlocks(
|
||||
width: number,
|
||||
height: number,
|
||||
blockSize: number,
|
||||
seed: number
|
||||
seed: number,
|
||||
): PixelImage {
|
||||
const bs = Math.max(1, Math.round(blockSize));
|
||||
const out = createPixelImage(width, height);
|
||||
@@ -44,7 +47,7 @@ export function randomColorBlocks(
|
||||
const { r, g, b } = hslToRgb({
|
||||
h: rng() * 360,
|
||||
s: 0.65 + rng() * 0.35,
|
||||
l: 0.45 + rng() * 0.25
|
||||
l: 0.45 + rng() * 0.25,
|
||||
});
|
||||
const yMax = Math.min(by + bs, height);
|
||||
const xMax = Math.min(bx + bs, width);
|
||||
@@ -62,7 +65,11 @@ export function randomColorBlocks(
|
||||
return out;
|
||||
}
|
||||
|
||||
function lineMask(length: number, divisions: number, lineWidth: number): Uint8Array {
|
||||
function lineMask(
|
||||
length: number,
|
||||
divisions: number,
|
||||
lineWidth: number,
|
||||
): Uint8Array {
|
||||
const mask = new Uint8Array(length);
|
||||
const lw = Math.max(1, Math.round(lineWidth));
|
||||
for (let i = 0; i <= divisions; i++) {
|
||||
@@ -80,7 +87,7 @@ export function drawGrid(
|
||||
rows: number,
|
||||
lineWidth: number,
|
||||
colorHex: string,
|
||||
transparentBg: boolean
|
||||
transparentBg: boolean,
|
||||
): PixelImage {
|
||||
const out = createPixelImage(width, height);
|
||||
if (!transparentBg) out.data.fill(255);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { gradientImage, noiseImage, solidImage } from './generate';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { gradientImage, noiseImage, solidImage } from "./generate";
|
||||
|
||||
describe('solidImage', () => {
|
||||
it('заливает весь холст заданным цветом', () => {
|
||||
describe("solidImage", () => {
|
||||
it("заливает весь холст заданным цветом", () => {
|
||||
const out = solidImage(2, 2, [10, 20, 30, 255]);
|
||||
expect(out.width).toBe(2);
|
||||
expect([...out.data]).toEqual(new Array(4).fill([10, 20, 30, 255]).flat());
|
||||
@@ -12,24 +12,26 @@ describe('solidImage', () => {
|
||||
[0, 10],
|
||||
[10, 0],
|
||||
[2.5, 10],
|
||||
[-1, 5]
|
||||
])('бросает ошибку на размерах %i x %i', (w, h) => {
|
||||
[-1, 5],
|
||||
])("бросает ошибку на размерах %i x %i", (w, h) => {
|
||||
expect(() => solidImage(w, h, [0, 0, 0, 255])).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('noiseImage', () => {
|
||||
it('детерминирован: одно зерно — одни байты', () => {
|
||||
expect([...noiseImage(4, 4, 42).data]).toEqual([...noiseImage(4, 4, 42).data]);
|
||||
describe("noiseImage", () => {
|
||||
it("детерминирован: одно зерно — одни байты", () => {
|
||||
expect([...noiseImage(4, 4, 42).data]).toEqual([
|
||||
...noiseImage(4, 4, 42).data,
|
||||
]);
|
||||
});
|
||||
|
||||
it('разные зерна дают разные данные', () => {
|
||||
it("разные зерна дают разные данные", () => {
|
||||
const a = [...noiseImage(8, 8, 1).data];
|
||||
const b = [...noiseImage(8, 8, 2).data];
|
||||
expect(a).not.toEqual(b);
|
||||
});
|
||||
|
||||
it('альфа всегда непрозрачная', () => {
|
||||
it("альфа всегда непрозрачная", () => {
|
||||
const data = noiseImage(3, 3, 7).data;
|
||||
for (let i = 3; i < data.length; i += 4) {
|
||||
expect(data[i]).toBe(255);
|
||||
@@ -37,14 +39,14 @@ describe('noiseImage', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('gradientImage', () => {
|
||||
it('горизонтальный градиент идёт от цвета A к цвету B', () => {
|
||||
describe("gradientImage", () => {
|
||||
it("горизонтальный градиент идёт от цвета A к цвету B", () => {
|
||||
const out = gradientImage(
|
||||
3,
|
||||
1,
|
||||
[0, 0, 0, 255],
|
||||
[255, 255, 255, 255],
|
||||
'horizontal'
|
||||
"horizontal",
|
||||
);
|
||||
const px = (x: number) => [...out.data.slice(x * 4, x * 4 + 4)];
|
||||
expect(px(0)).toEqual([0, 0, 0, 255]);
|
||||
@@ -52,13 +54,13 @@ describe('gradientImage', () => {
|
||||
expect(px(2)).toEqual([255, 255, 255, 255]);
|
||||
});
|
||||
|
||||
it('вертикальный градиент меняется по строкам', () => {
|
||||
it("вертикальный градиент меняется по строкам", () => {
|
||||
const out = gradientImage(
|
||||
1,
|
||||
2,
|
||||
[0, 0, 0, 255],
|
||||
[100, 100, 100, 255],
|
||||
'vertical'
|
||||
"vertical",
|
||||
);
|
||||
expect(out.data[0]).toBe(0);
|
||||
expect(out.data[4]).toBe(100);
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
import type { PixelImage } from './types';
|
||||
import { ToolError } from './errors';
|
||||
import type { PixelImage } from "./types";
|
||||
import { ToolError } from "./errors";
|
||||
|
||||
export function solidImage(
|
||||
width: number,
|
||||
height: number,
|
||||
rgba: [number, number, number, number]
|
||||
rgba: [number, number, number, number],
|
||||
): PixelImage {
|
||||
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) {
|
||||
throw new ToolError('errors.sizeInt');
|
||||
if (
|
||||
!Number.isInteger(width) ||
|
||||
!Number.isInteger(height) ||
|
||||
width < 1 ||
|
||||
height < 1
|
||||
) {
|
||||
throw new ToolError("errors.sizeInt");
|
||||
}
|
||||
const data = new Uint8ClampedArray(width * height * 4);
|
||||
for (let i = 0; i < data.length; i += 4) {
|
||||
@@ -19,9 +24,18 @@ export function solidImage(
|
||||
return { width, height, data };
|
||||
}
|
||||
|
||||
export function noiseImage(width: number, height: number, seed: number): PixelImage {
|
||||
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) {
|
||||
throw new ToolError('errors.sizeInt');
|
||||
export function noiseImage(
|
||||
width: number,
|
||||
height: number,
|
||||
seed: number,
|
||||
): PixelImage {
|
||||
if (
|
||||
!Number.isInteger(width) ||
|
||||
!Number.isInteger(height) ||
|
||||
width < 1 ||
|
||||
height < 1
|
||||
) {
|
||||
throw new ToolError("errors.sizeInt");
|
||||
}
|
||||
const random = mulberry32(seed);
|
||||
const data = new Uint8ClampedArray(width * height * 4);
|
||||
@@ -39,20 +53,25 @@ export function gradientImage(
|
||||
height: number,
|
||||
fromRgba: [number, number, number, number],
|
||||
toRgba: [number, number, number, number],
|
||||
direction: 'horizontal' | 'vertical'
|
||||
direction: "horizontal" | "vertical",
|
||||
): PixelImage {
|
||||
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) {
|
||||
throw new ToolError('errors.sizeInt');
|
||||
if (
|
||||
!Number.isInteger(width) ||
|
||||
!Number.isInteger(height) ||
|
||||
width < 1 ||
|
||||
height < 1
|
||||
) {
|
||||
throw new ToolError("errors.sizeInt");
|
||||
}
|
||||
const out: PixelImage = {
|
||||
width,
|
||||
height,
|
||||
data: new Uint8ClampedArray(width * height * 4)
|
||||
data: new Uint8ClampedArray(width * height * 4),
|
||||
};
|
||||
const steps = (direction === 'horizontal' ? width : height) - 1;
|
||||
const steps = (direction === "horizontal" ? width : height) - 1;
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
const t = steps === 0 ? 0 : (direction === 'horizontal' ? x : y) / steps;
|
||||
const t = steps === 0 ? 0 : (direction === "horizontal" ? x : y) / steps;
|
||||
const i = (y * width + x) * 4;
|
||||
out.data[i] = fromRgba[0] + (toRgba[0] - fromRgba[0]) * t;
|
||||
out.data[i + 1] = fromRgba[1] + (toRgba[1] - fromRgba[1]) * t;
|
||||
|
||||
@@ -1,94 +1,90 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { centerByAlpha, crop, expandCanvas, flip, resize, rotate90, tile } from './geometry';
|
||||
import { makeImage } from './test-helpers';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
centerByAlpha,
|
||||
crop,
|
||||
expandCanvas,
|
||||
flip,
|
||||
resize,
|
||||
rotate90,
|
||||
tile,
|
||||
} from "./geometry";
|
||||
import { makeImage } from "./test-helpers";
|
||||
|
||||
const square = () =>
|
||||
makeImage(2, 2, [
|
||||
[1, 1, 1, 1],
|
||||
[2, 2, 2, 2],
|
||||
[3, 3, 3, 3],
|
||||
[4, 4, 4, 4]
|
||||
[4, 4, 4, 4],
|
||||
]);
|
||||
|
||||
describe('flip', () => {
|
||||
it('отражает по горизонтали (зеркало слева-направо)', () => {
|
||||
const out = flip(square(), 'horizontal');
|
||||
describe("flip", () => {
|
||||
it("отражает по горизонтали (зеркало слева-направо)", () => {
|
||||
const out = flip(square(), "horizontal");
|
||||
expect(out.width).toBe(2);
|
||||
expect(out.height).toBe(2);
|
||||
expect([...out.data]).toEqual([
|
||||
2, 2, 2, 2,
|
||||
1, 1, 1, 1,
|
||||
4, 4, 4, 4,
|
||||
3, 3, 3, 3
|
||||
2, 2, 2, 2, 1, 1, 1, 1, 4, 4, 4, 4, 3, 3, 3, 3,
|
||||
]);
|
||||
});
|
||||
|
||||
it('отражает по вертикали (сверху-вниз)', () => {
|
||||
const out = flip(square(), 'vertical');
|
||||
it("отражает по вертикали (сверху-вниз)", () => {
|
||||
const out = flip(square(), "vertical");
|
||||
expect([...out.data]).toEqual([
|
||||
3, 3, 3, 3,
|
||||
4, 4, 4, 4,
|
||||
1, 1, 1, 1,
|
||||
2, 2, 2, 2
|
||||
3, 3, 3, 3, 4, 4, 4, 4, 1, 1, 1, 1, 2, 2, 2, 2,
|
||||
]);
|
||||
});
|
||||
|
||||
it('не мутирует вход', () => {
|
||||
it("не мутирует вход", () => {
|
||||
const img = square();
|
||||
flip(img, 'horizontal');
|
||||
expect([...img.data]).toEqual([1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]);
|
||||
flip(img, "horizontal");
|
||||
expect([...img.data]).toEqual([
|
||||
1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rotate90', () => {
|
||||
it('поворачивает неквадрат 2x3 на 90° по часовой', () => {
|
||||
describe("rotate90", () => {
|
||||
it("поворачивает неквадрат 2x3 на 90° по часовой", () => {
|
||||
const rect = makeImage(2, 3, [
|
||||
[1, 1, 1, 1],
|
||||
[2, 2, 2, 2],
|
||||
[3, 3, 3, 3],
|
||||
[4, 4, 4, 4],
|
||||
[5, 5, 5, 5],
|
||||
[6, 6, 6, 6]
|
||||
[6, 6, 6, 6],
|
||||
]);
|
||||
const out = rotate90(rect, 1);
|
||||
expect(out.width).toBe(3);
|
||||
expect(out.height).toBe(2);
|
||||
expect([...out.data]).toEqual([
|
||||
5, 5, 5, 5,
|
||||
3, 3, 3, 3,
|
||||
1, 1, 1, 1,
|
||||
6, 6, 6, 6,
|
||||
4, 4, 4, 4,
|
||||
2, 2, 2, 2
|
||||
5, 5, 5, 5, 3, 3, 3, 3, 1, 1, 1, 1, 6, 6, 6, 6, 4, 4, 4, 4, 2, 2, 2, 2,
|
||||
]);
|
||||
});
|
||||
|
||||
it('turns=0 возвращает копию без изменений', () => {
|
||||
it("turns=0 возвращает копию без изменений", () => {
|
||||
const img = square();
|
||||
const out = rotate90(img, 0);
|
||||
expect(out).not.toBe(img);
|
||||
expect([...out.data]).toEqual([...img.data]);
|
||||
});
|
||||
|
||||
it('нормализует turns: 5 ≡ 1, -3 ≡ 1, 4 ≡ 0', () => {
|
||||
it("нормализует turns: 5 ≡ 1, -3 ≡ 1, 4 ≡ 0", () => {
|
||||
const once = [...rotate90(square(), 1).data];
|
||||
expect([...rotate90(square(), 5).data]).toEqual(once);
|
||||
expect([...rotate90(square(), -3).data]).toEqual(once);
|
||||
expect([...rotate90(square(), 4).data]).toEqual([...square().data]);
|
||||
});
|
||||
|
||||
it('turns=2 на квадрате равно двойному отражению', () => {
|
||||
it("turns=2 на квадрате равно двойному отражению", () => {
|
||||
const out = rotate90(square(), 2);
|
||||
expect([...out.data]).toEqual([
|
||||
4, 4, 4, 4,
|
||||
3, 3, 3, 3,
|
||||
2, 2, 2, 2,
|
||||
1, 1, 1, 1
|
||||
4, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 2, 1, 1, 1, 1,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('crop', () => {
|
||||
describe("crop", () => {
|
||||
const grid = () =>
|
||||
makeImage(3, 3, [
|
||||
[1, 1, 1, 1],
|
||||
@@ -99,63 +95,64 @@ describe('crop', () => {
|
||||
[6, 6, 6, 6],
|
||||
[7, 7, 7, 7],
|
||||
[8, 8, 8, 8],
|
||||
[9, 9, 9, 9]
|
||||
[9, 9, 9, 9],
|
||||
]);
|
||||
|
||||
it('вырезает центральную область 2x2 из 3x3', () => {
|
||||
it("вырезает центральную область 2x2 из 3x3", () => {
|
||||
const out = crop(grid(), 1, 1, 2, 2);
|
||||
expect(out.width).toBe(2);
|
||||
expect(out.height).toBe(2);
|
||||
expect([...out.data]).toEqual([
|
||||
5, 5, 5, 5,
|
||||
6, 6, 6, 6,
|
||||
8, 8, 8, 8,
|
||||
9, 9, 9, 9
|
||||
5, 5, 5, 5, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9, 9, 9,
|
||||
]);
|
||||
});
|
||||
|
||||
it('усекает область, выходящую за границы', () => {
|
||||
it("усекает область, выходящую за границы", () => {
|
||||
const out = crop(grid(), -1, -1, 2, 2);
|
||||
expect(out.width).toBe(1);
|
||||
expect(out.height).toBe(1);
|
||||
expect([...out.data]).toEqual([1, 1, 1, 1]);
|
||||
});
|
||||
|
||||
it('бросает ToolError для области вне изображения', () => {
|
||||
it("бросает ToolError для области вне изображения", () => {
|
||||
expect(() => crop(grid(), 5, 5, 2, 2)).toThrow(/errors\.cropBounds/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('expandCanvas', () => {
|
||||
describe("expandCanvas", () => {
|
||||
const pixel = () => makeImage(1, 1, [[10, 20, 30, 255]]);
|
||||
|
||||
it('прозрачное расширение кладёт пиксель со смещением', () => {
|
||||
it("прозрачное расширение кладёт пиксель со смещением", () => {
|
||||
const out = expandCanvas(pixel(), 1, 2, 3, 4);
|
||||
expect(out.width).toBe(5);
|
||||
expect(out.height).toBe(7);
|
||||
expect([...out.data.slice(0, 4)]).toEqual([0, 0, 0, 0]);
|
||||
expect([...out.data.slice((2 * 5 + 1) * 4, (2 * 5 + 1) * 4 + 4)]).toEqual([10, 20, 30, 255]);
|
||||
expect([...out.data.slice((2 * 5 + 1) * 4, (2 * 5 + 1) * 4 + 4)]).toEqual([
|
||||
10, 20, 30, 255,
|
||||
]);
|
||||
});
|
||||
|
||||
it('цветной фон заливает всё вокруг', () => {
|
||||
const out = expandCanvas(pixel(), 1, 0, 0, 0, '#ffffff');
|
||||
it("цветной фон заливает всё вокруг", () => {
|
||||
const out = expandCanvas(pixel(), 1, 0, 0, 0, "#ffffff");
|
||||
expect(out.data[0]).toBe(255);
|
||||
expect(out.data[3]).toBe(255);
|
||||
expect(out.data[(0 * 2 + 1) * 4 + 3]).toBe(255);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tile', () => {
|
||||
it('повторяет изображение по сетке', () => {
|
||||
describe("tile", () => {
|
||||
it("повторяет изображение по сетке", () => {
|
||||
const out = tile(makeImage(1, 1, [[9, 9, 9, 255]]), 3, 2);
|
||||
expect(out.width).toBe(3);
|
||||
expect(out.height).toBe(2);
|
||||
expect([...out.data].filter((_, i) => i % 4 === 0)).toEqual([9, 9, 9, 9, 9, 9]);
|
||||
expect([...out.data].filter((_, i) => i % 4 === 0)).toEqual([
|
||||
9, 9, 9, 9, 9, 9,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('centerByAlpha', () => {
|
||||
it('вырезает непрозрачный блок и центрирует на прежнем холсте', () => {
|
||||
describe("centerByAlpha", () => {
|
||||
it("вырезает непрозрачный блок и центрирует на прежнем холсте", () => {
|
||||
const img = makeImage(3, 3, [
|
||||
[0, 0, 0, 0],
|
||||
[0, 0, 0, 0],
|
||||
@@ -165,7 +162,7 @@ describe('centerByAlpha', () => {
|
||||
[0, 0, 0, 0],
|
||||
[0, 0, 0, 0],
|
||||
[0, 0, 0, 0],
|
||||
[0, 0, 0, 0]
|
||||
[0, 0, 0, 0],
|
||||
]);
|
||||
const out = centerByAlpha(img);
|
||||
expect(out.width).toBe(3);
|
||||
@@ -175,30 +172,30 @@ describe('centerByAlpha', () => {
|
||||
expect(alphaAt(1, 1)).toBe(255);
|
||||
});
|
||||
|
||||
it('полностью прозрачное изображение возвращается без изменений', () => {
|
||||
it("полностью прозрачное изображение возвращается без изменений", () => {
|
||||
const img = makeImage(2, 1, [
|
||||
[0, 0, 0, 0],
|
||||
[0, 0, 0, 0]
|
||||
[0, 0, 0, 0],
|
||||
]);
|
||||
expect([...centerByAlpha(img).data]).toEqual([...img.data]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resize', () => {
|
||||
describe("resize", () => {
|
||||
const twoByTwo = () =>
|
||||
makeImage(2, 2, [
|
||||
[0, 0, 0, 255],
|
||||
[100, 100, 100, 255],
|
||||
[200, 200, 200, 255],
|
||||
[255, 255, 255, 255]
|
||||
[255, 255, 255, 255],
|
||||
]);
|
||||
|
||||
it('совпадает с входом при тех же размерах', () => {
|
||||
it("совпадает с входом при тех же размерах", () => {
|
||||
const img = twoByTwo();
|
||||
expect([...resize(img, 2, 2).data]).toEqual([...img.data]);
|
||||
});
|
||||
|
||||
it('апскейл 2x2 -> 4x4 билинейно интерполирует', () => {
|
||||
it("апскейл 2x2 -> 4x4 билинейно интерполирует", () => {
|
||||
const out = resize(twoByTwo(), 4, 4);
|
||||
expect(out.width).toBe(4);
|
||||
expect(out.height).toBe(4);
|
||||
@@ -207,7 +204,7 @@ describe('resize', () => {
|
||||
expect(red.slice(4, 8)).toEqual([50, 72, 117, 139]);
|
||||
});
|
||||
|
||||
it('бросает ToolError на некорректные размеры', () => {
|
||||
it("бросает ToolError на некорректные размеры", () => {
|
||||
const img = twoByTwo();
|
||||
expect(() => resize(img, 0, 10)).toThrow(/errors\.sizeInt/);
|
||||
expect(() => resize(img, 10.5, 10)).toThrow(/errors\.sizeInt/);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { parseHex } from './alpha';
|
||||
import { ToolError } from './errors';
|
||||
import { clonePixelImage, createPixelImage, type PixelImage } from './types';
|
||||
import { parseHex } from "./alpha";
|
||||
import { ToolError } from "./errors";
|
||||
import { clonePixelImage, createPixelImage, type PixelImage } from "./types";
|
||||
|
||||
export function expandCanvas(
|
||||
img: PixelImage,
|
||||
@@ -8,7 +8,7 @@ export function expandCanvas(
|
||||
top: number,
|
||||
right: number,
|
||||
bottom: number,
|
||||
backgroundHex?: string
|
||||
backgroundHex?: string,
|
||||
): PixelImage {
|
||||
const l = Math.max(0, Math.trunc(left));
|
||||
const t = Math.max(0, Math.trunc(top));
|
||||
@@ -28,13 +28,17 @@ export function expandCanvas(
|
||||
const srcStart = y * img.width * 4;
|
||||
out.data.set(
|
||||
img.data.subarray(srcStart, srcStart + img.width * 4),
|
||||
((y + t) * out.width + l) * 4
|
||||
((y + t) * out.width + l) * 4,
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function tile(img: PixelImage, columns: number, rows: number): PixelImage {
|
||||
export function tile(
|
||||
img: PixelImage,
|
||||
columns: number,
|
||||
rows: number,
|
||||
): PixelImage {
|
||||
const cols = Math.max(1, Math.trunc(columns));
|
||||
const rowsCount = Math.max(1, Math.trunc(rows));
|
||||
const out = createPixelImage(img.width * cols, img.height * rowsCount);
|
||||
@@ -44,7 +48,7 @@ export function tile(img: PixelImage, columns: number, rows: number): PixelImage
|
||||
const srcStart = y * img.width * 4;
|
||||
out.data.set(
|
||||
img.data.subarray(srcStart, srcStart + img.width * 4),
|
||||
((ty * img.height + y) * out.width + tx * img.width) * 4
|
||||
((ty * img.height + y) * out.width + tx * img.width) * 4,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -75,20 +79,20 @@ export function centerByAlpha(img: PixelImage): PixelImage {
|
||||
for (let y = 0; y < content.height; y++) {
|
||||
out.data.set(
|
||||
content.data.subarray(y * content.width * 4, (y + 1) * content.width * 4),
|
||||
((y + dy) * out.width + dx) * 4
|
||||
((y + dy) * out.width + dx) * 4,
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export type FlipAxis = 'horizontal' | 'vertical';
|
||||
export type FlipAxis = "horizontal" | "vertical";
|
||||
|
||||
export function flip(img: PixelImage, axis: FlipAxis): PixelImage {
|
||||
const out = createPixelImage(img.width, img.height);
|
||||
for (let y = 0; y < img.height; y++) {
|
||||
for (let x = 0; x < img.width; x++) {
|
||||
const sx = axis === 'horizontal' ? img.width - 1 - x : x;
|
||||
const sy = axis === 'vertical' ? img.height - 1 - y : y;
|
||||
const sx = axis === "horizontal" ? img.width - 1 - x : x;
|
||||
const sy = axis === "vertical" ? img.height - 1 - y : y;
|
||||
copyPixel(img, sx, sy, out, x, y);
|
||||
}
|
||||
}
|
||||
@@ -120,7 +124,7 @@ export function crop(
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number
|
||||
height: number,
|
||||
): PixelImage {
|
||||
const sx = clampInt(x, 0, img.width);
|
||||
const sy = clampInt(y, 0, img.height);
|
||||
@@ -129,7 +133,7 @@ export function crop(
|
||||
const w = ex - sx;
|
||||
const h = ey - sy;
|
||||
if (w <= 0 || h <= 0) {
|
||||
throw new ToolError('errors.cropBounds');
|
||||
throw new ToolError("errors.cropBounds");
|
||||
}
|
||||
const out = createPixelImage(w, h);
|
||||
for (let row = 0; row < h; row++) {
|
||||
@@ -139,9 +143,18 @@ export function crop(
|
||||
return out;
|
||||
}
|
||||
|
||||
export function resize(img: PixelImage, width: number, height: number): PixelImage {
|
||||
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) {
|
||||
throw new ToolError('errors.sizeInt');
|
||||
export function resize(
|
||||
img: PixelImage,
|
||||
width: number,
|
||||
height: number,
|
||||
): PixelImage {
|
||||
if (
|
||||
!Number.isInteger(width) ||
|
||||
!Number.isInteger(height) ||
|
||||
width < 1 ||
|
||||
height < 1
|
||||
) {
|
||||
throw new ToolError("errors.sizeInt");
|
||||
}
|
||||
const out = createPixelImage(width, height);
|
||||
const xr = img.width / width;
|
||||
@@ -173,7 +186,14 @@ export function resize(img: PixelImage, width: number, height: number): PixelIma
|
||||
return out;
|
||||
}
|
||||
|
||||
function copyPixel(src: PixelImage, sx: number, sy: number, dst: PixelImage, dx: number, dy: number): void {
|
||||
function copyPixel(
|
||||
src: PixelImage,
|
||||
sx: number,
|
||||
sy: number,
|
||||
dst: PixelImage,
|
||||
dx: number,
|
||||
dy: number,
|
||||
): void {
|
||||
const si = (sy * src.width + sx) * 4;
|
||||
const di = (dy * dst.width + dx) * 4;
|
||||
dst.data[di] = src.data[si];
|
||||
@@ -185,7 +205,7 @@ function copyPixel(src: PixelImage, sx: number, sy: number, dst: PixelImage, dx:
|
||||
export function sampleBilinear(
|
||||
img: PixelImage,
|
||||
fx: number,
|
||||
fy: number
|
||||
fy: number,
|
||||
): [number, number, number, number] {
|
||||
const maxX = img.width - 1;
|
||||
const maxY = img.height - 1;
|
||||
@@ -214,23 +234,21 @@ function clampInt(value: number, min: number, max: number): number {
|
||||
return Math.min(max, Math.max(min, Math.trunc(value)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
export type Anchor9 =
|
||||
| 'top-left'
|
||||
| 'top-center'
|
||||
| 'top-right'
|
||||
| 'middle-left'
|
||||
| 'center'
|
||||
| 'middle-right'
|
||||
| 'bottom-left'
|
||||
| 'bottom-center'
|
||||
| 'bottom-right';
|
||||
| "top-left"
|
||||
| "top-center"
|
||||
| "top-right"
|
||||
| "middle-left"
|
||||
| "center"
|
||||
| "middle-right"
|
||||
| "bottom-left"
|
||||
| "bottom-center"
|
||||
| "bottom-right";
|
||||
|
||||
/** Границы контента: пиксели с альфой строго больше порога. Пустое изображение → null. */
|
||||
export function contentBounds(
|
||||
img: PixelImage,
|
||||
alphaThreshold = 0
|
||||
alphaThreshold = 0,
|
||||
): { x: number; y: number; w: number; h: number } | null {
|
||||
let minX = img.width;
|
||||
let minY = img.height;
|
||||
@@ -262,11 +280,19 @@ export function changeCanvasSize(
|
||||
img: PixelImage,
|
||||
width: number,
|
||||
height: number,
|
||||
anchor: Anchor9
|
||||
anchor: Anchor9,
|
||||
): PixelImage {
|
||||
const out = createPixelImage(width, height);
|
||||
const pasteX = anchor.endsWith('-left') ? 0 : anchor.endsWith('-right') ? width - img.width : Math.floor((width - img.width) / 2);
|
||||
const pasteY = anchor.startsWith('top-') ? 0 : anchor.startsWith('bottom-') ? height - img.height : Math.floor((height - img.height) / 2);
|
||||
const pasteX = anchor.endsWith("-left")
|
||||
? 0
|
||||
: anchor.endsWith("-right")
|
||||
? width - img.width
|
||||
: Math.floor((width - img.width) / 2);
|
||||
const pasteY = anchor.startsWith("top-")
|
||||
? 0
|
||||
: anchor.startsWith("bottom-")
|
||||
? height - img.height
|
||||
: Math.floor((height - img.height) / 2);
|
||||
for (let y = 0; y < height; y++) {
|
||||
const sy = y - pasteY;
|
||||
if (sy < 0 || sy >= img.height) continue;
|
||||
@@ -307,13 +333,21 @@ export function padToRatio(img: PixelImage, ratio: number): PixelImage {
|
||||
else if (current < ratio) w = Math.round(h * ratio);
|
||||
w = Math.max(1, w);
|
||||
h = Math.max(1, h);
|
||||
return changeCanvasSize(img, w, h, 'center');
|
||||
return changeCanvasSize(img, w, h, "center");
|
||||
}
|
||||
|
||||
/** Разворачивает изображение на 90°, если его ориентация не совпадает с целевой. Квадрат не трогает. */
|
||||
export function forceOrientation(img: PixelImage, target: 'portrait' | 'landscape'): PixelImage {
|
||||
const current = img.width > img.height ? 'landscape' : img.width < img.height ? 'portrait' : 'square';
|
||||
if (current === target || current === 'square') return clonePixelImage(img);
|
||||
export function forceOrientation(
|
||||
img: PixelImage,
|
||||
target: "portrait" | "landscape",
|
||||
): PixelImage {
|
||||
const current =
|
||||
img.width > img.height
|
||||
? "landscape"
|
||||
: img.width < img.height
|
||||
? "portrait"
|
||||
: "square";
|
||||
if (current === target || current === "square") return clonePixelImage(img);
|
||||
return rotate90(img, 1);
|
||||
}
|
||||
|
||||
@@ -323,14 +357,14 @@ export function forceOrientation(img: PixelImage, target: 'portrait' | 'landscap
|
||||
*/
|
||||
export function symmetricCopy(
|
||||
img: PixelImage,
|
||||
axis: 'vertical' | 'horizontal',
|
||||
keepSide: 'left' | 'right' | 'top' | 'bottom'
|
||||
axis: "vertical" | "horizontal",
|
||||
keepSide: "left" | "right" | "top" | "bottom",
|
||||
): PixelImage {
|
||||
if (axis === 'vertical') {
|
||||
if (axis === "vertical") {
|
||||
const out = createPixelImage(img.width * 2, img.height);
|
||||
for (let y = 0; y < img.height; y++) {
|
||||
for (let x = 0; x < img.width; x++) {
|
||||
const srcX = keepSide === 'left' ? x : img.width - 1 - x;
|
||||
const srcX = keepSide === "left" ? x : img.width - 1 - x;
|
||||
const di = (y * out.width + x) * 4;
|
||||
const si = (y * img.width + srcX) * 4;
|
||||
out.data[di] = img.data[si];
|
||||
@@ -349,7 +383,7 @@ export function symmetricCopy(
|
||||
}
|
||||
const out = createPixelImage(img.width, img.height * 2);
|
||||
for (let y = 0; y < img.height; y++) {
|
||||
const srcY = keepSide === 'top' ? y : img.height - 1 - y;
|
||||
const srcY = keepSide === "top" ? y : img.height - 1 - y;
|
||||
for (let x = 0; x < img.width; x++) {
|
||||
const si = (srcY * img.width + x) * 4;
|
||||
const dTop = (y * out.width + x) * 4;
|
||||
|
||||
+34
-26
@@ -1,32 +1,40 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { isSupportedImage, unsupportedImageError } from './io';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isSupportedImage, unsupportedImageError } from "./io";
|
||||
|
||||
describe('isSupportedImage', () => {
|
||||
it.each(['image/png', 'image/jpeg', 'image/webp', 'image/gif', 'image/bmp', 'image/x-icon'])(
|
||||
'принимает %s',
|
||||
(type) => {
|
||||
expect(isSupportedImage(new File([], 'x', { type }))).toBe(true);
|
||||
}
|
||||
describe("isSupportedImage", () => {
|
||||
it.each([
|
||||
"image/png",
|
||||
"image/jpeg",
|
||||
"image/webp",
|
||||
"image/gif",
|
||||
"image/bmp",
|
||||
"image/x-icon",
|
||||
])("принимает %s", (type) => {
|
||||
expect(isSupportedImage(new File([], "x", { type }))).toBe(true);
|
||||
});
|
||||
|
||||
it("отклоняет неподдерживаемый тип", () => {
|
||||
expect(
|
||||
isSupportedImage(new File([], "a.txt", { type: "text/plain" })),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("отклоняет файл без типа", () => {
|
||||
expect(isSupportedImage(new File([], "x"))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("unsupportedImageError", () => {
|
||||
it("ключ ошибки и тип файла в vars", () => {
|
||||
const err = unsupportedImageError(
|
||||
new File([], "a.txt", { type: "text/plain" }),
|
||||
);
|
||||
|
||||
it('отклоняет неподдерживаемый тип', () => {
|
||||
expect(isSupportedImage(new File([], 'a.txt', { type: 'text/plain' }))).toBe(false);
|
||||
expect(err.key).toBe("errors.unsupportedFile");
|
||||
expect(err.vars?.type).toBe("text/plain");
|
||||
});
|
||||
|
||||
it('отклоняет файл без типа', () => {
|
||||
expect(isSupportedImage(new File([], 'x'))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('unsupportedImageError', () => {
|
||||
it('ключ ошибки и тип файла в vars', () => {
|
||||
const err = unsupportedImageError(new File([], 'a.txt', { type: 'text/plain' }));
|
||||
expect(err.key).toBe('errors.unsupportedFile');
|
||||
expect(err.vars?.type).toBe('text/plain');
|
||||
});
|
||||
|
||||
it('пустой тип передаётся как unknown', () => {
|
||||
const err = unsupportedImageError(new File([], 'x'));
|
||||
expect(err.vars?.type).toBe('unknown');
|
||||
it("пустой тип передаётся как unknown", () => {
|
||||
const err = unsupportedImageError(new File([], "x"));
|
||||
expect(err.vars?.type).toBe("unknown");
|
||||
});
|
||||
});
|
||||
|
||||
+67
-43
@@ -1,33 +1,40 @@
|
||||
import { encodeBmpBytes } from './bmp';
|
||||
import { ToolError } from './errors';
|
||||
import { type PixelImage } from './types';
|
||||
import { encodeBmpBytes } from "./bmp";
|
||||
import { ToolError } from "./errors";
|
||||
import { type PixelImage } from "./types";
|
||||
|
||||
export type OutputMime = 'image/png' | 'image/jpeg' | 'image/webp' | 'image/bmp';
|
||||
export type OutputMime =
|
||||
"image/png" | "image/jpeg" | "image/webp" | "image/bmp";
|
||||
|
||||
export const ACCEPTED_IMAGE_TYPES =
|
||||
'image/png,image/jpeg,image/webp,image/gif,image/bmp,image/x-icon';
|
||||
"image/png,image/jpeg,image/webp,image/gif,image/bmp,image/x-icon";
|
||||
|
||||
const SUPPORTED_MIME_TYPES = new Set(ACCEPTED_IMAGE_TYPES.split(','));
|
||||
const SUPPORTED_MIME_TYPES = new Set(ACCEPTED_IMAGE_TYPES.split(","));
|
||||
|
||||
export function isSupportedImage(file: File): boolean {
|
||||
return SUPPORTED_MIME_TYPES.has(file.type);
|
||||
}
|
||||
|
||||
export function unsupportedImageError(file: File): ToolError {
|
||||
return new ToolError('errors.unsupportedFile', { type: file.type || 'unknown' });
|
||||
return new ToolError("errors.unsupportedFile", {
|
||||
type: file.type || "unknown",
|
||||
});
|
||||
}
|
||||
|
||||
async function decodeBitmap(bitmap: ImageBitmap): Promise<PixelImage> {
|
||||
const canvas = document.createElement('canvas');
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = bitmap.width;
|
||||
canvas.height = bitmap.height;
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||
const ctx = canvas.getContext("2d", { willReadFrequently: true });
|
||||
if (!ctx) {
|
||||
throw new ToolError('errors.noCanvasCtx');
|
||||
throw new ToolError("errors.noCanvasCtx");
|
||||
}
|
||||
ctx.drawImage(bitmap, 0, 0);
|
||||
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||
return { width: imageData.width, height: imageData.height, data: imageData.data };
|
||||
return {
|
||||
width: imageData.width,
|
||||
height: imageData.height,
|
||||
data: imageData.data,
|
||||
};
|
||||
}
|
||||
|
||||
export async function decodeFile(file: File): Promise<PixelImage> {
|
||||
@@ -39,7 +46,9 @@ export async function decodeFile(file: File): Promise<PixelImage> {
|
||||
}
|
||||
}
|
||||
|
||||
export async function decodeBytes(bytes: Uint8Array<ArrayBuffer>): Promise<PixelImage> {
|
||||
export async function decodeBytes(
|
||||
bytes: Uint8Array<ArrayBuffer>,
|
||||
): Promise<PixelImage> {
|
||||
const blob = new Blob([bytes]);
|
||||
const bitmap = await createImageBitmap(blob);
|
||||
try {
|
||||
@@ -50,25 +59,25 @@ export async function decodeBytes(bytes: Uint8Array<ArrayBuffer>): Promise<Pixel
|
||||
}
|
||||
|
||||
export function toDataUrl(img: PixelImage): string {
|
||||
const canvas = document.createElement('canvas');
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = img.width;
|
||||
canvas.height = img.height;
|
||||
const ctx = canvas.getContext('2d');
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) {
|
||||
throw new ToolError('errors.noCanvasCtx');
|
||||
throw new ToolError("errors.noCanvasCtx");
|
||||
}
|
||||
ctx.putImageData(new ImageData(img.data, img.width, img.height), 0, 0);
|
||||
return canvas.toDataURL('image/png');
|
||||
return canvas.toDataURL("image/png");
|
||||
}
|
||||
|
||||
export function toBase64(img: PixelImage): string {
|
||||
return toDataUrl(img).slice('data:image/png;base64,'.length);
|
||||
return toDataUrl(img).slice("data:image/png;base64,".length);
|
||||
}
|
||||
|
||||
export async function decodeTextImage(text: string): Promise<PixelImage> {
|
||||
const cleaned = text.trim().replace(/^data:[^,]*,/, '');
|
||||
const cleaned = text.trim().replace(/^data:[^,]*,/, "");
|
||||
if (cleaned.length === 0) {
|
||||
throw new ToolError('errors.badBase64');
|
||||
throw new ToolError("errors.badBase64");
|
||||
}
|
||||
const binary = atob(cleaned);
|
||||
const bytes = Uint8Array.from(binary, (ch) => ch.charCodeAt(0));
|
||||
@@ -77,44 +86,48 @@ export async function decodeTextImage(text: string): Promise<PixelImage> {
|
||||
|
||||
export async function encode(
|
||||
img: PixelImage,
|
||||
mime: OutputMime = 'image/png',
|
||||
quality?: number
|
||||
mime: OutputMime = "image/png",
|
||||
quality?: number,
|
||||
): Promise<Blob> {
|
||||
if (mime === 'image/bmp') {
|
||||
if (mime === "image/bmp") {
|
||||
return new Blob([encodeBmpBytes(img)], { type: mime });
|
||||
}
|
||||
if (mime === 'image/jpeg' || mime === 'image/webp') {
|
||||
if (mime === "image/jpeg" || mime === "image/webp") {
|
||||
if (quality !== undefined && (quality < 0 || quality > 1)) {
|
||||
throw new ToolError('errors.qualityRange');
|
||||
throw new ToolError("errors.qualityRange");
|
||||
}
|
||||
}
|
||||
const canvas = document.createElement('canvas');
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = img.width;
|
||||
canvas.height = img.height;
|
||||
const ctx = canvas.getContext('2d');
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) {
|
||||
throw new ToolError('errors.noCanvasCtx');
|
||||
throw new ToolError("errors.noCanvasCtx");
|
||||
}
|
||||
ctx.putImageData(new ImageData(img.data, img.width, img.height), 0, 0);
|
||||
return await canvasToBlob(canvas, mime, quality);
|
||||
}
|
||||
|
||||
function canvasToBlob(canvas: HTMLCanvasElement, mime: OutputMime, quality?: number): Promise<Blob> {
|
||||
function canvasToBlob(
|
||||
canvas: HTMLCanvasElement,
|
||||
mime: OutputMime,
|
||||
quality?: number,
|
||||
): Promise<Blob> {
|
||||
return new Promise((resolve, reject) => {
|
||||
canvas.toBlob(
|
||||
(blob) =>
|
||||
blob
|
||||
? resolve(blob)
|
||||
: reject(new ToolError('errors.encodeUnsupported', { mime })),
|
||||
: reject(new ToolError("errors.encodeUnsupported", { mime })),
|
||||
mime,
|
||||
quality
|
||||
quality,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function downloadBlob(blob: Blob, filename: string): void {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.append(a);
|
||||
@@ -124,43 +137,54 @@ export function downloadBlob(blob: Blob, filename: string): void {
|
||||
}
|
||||
|
||||
export function replaceExtension(filename: string, ext: string): string {
|
||||
const base = filename.replace(/\.[^./\\]+$/, '');
|
||||
const base = filename.replace(/\.[^./\\]+$/, "");
|
||||
return `${base}.${ext}`;
|
||||
}
|
||||
|
||||
export async function decodeSvgText(text: string, targetWidth?: number): Promise<PixelImage> {
|
||||
export async function decodeSvgText(
|
||||
text: string,
|
||||
targetWidth?: number,
|
||||
): Promise<PixelImage> {
|
||||
const trimmed = text.trim();
|
||||
if (trimmed.length === 0) {
|
||||
throw new ToolError('errors.svgSize');
|
||||
throw new ToolError("errors.svgSize");
|
||||
}
|
||||
const blob = new Blob([trimmed], { type: 'image/svg+xml' });
|
||||
const blob = new Blob([trimmed], { type: "image/svg+xml" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
try {
|
||||
const img = new Image();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
img.onload = () => resolve();
|
||||
img.onerror = () => reject(new ToolError('errors.svgLoad'));
|
||||
img.onerror = () => reject(new ToolError("errors.svgLoad"));
|
||||
img.src = url;
|
||||
});
|
||||
const w = targetWidth ?? img.naturalWidth ?? 300;
|
||||
const ratio = img.naturalHeight > 0 ? img.naturalHeight / img.naturalWidth : 1;
|
||||
const ratio =
|
||||
img.naturalHeight > 0 ? img.naturalHeight / img.naturalWidth : 1;
|
||||
const h = Math.max(1, Math.round(w * ratio));
|
||||
const canvas = document.createElement('canvas');
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||
if (!ctx) throw new ToolError('errors.noCanvasCtx');
|
||||
const ctx = canvas.getContext("2d", { willReadFrequently: true });
|
||||
if (!ctx) throw new ToolError("errors.noCanvasCtx");
|
||||
ctx.drawImage(img, 0, 0, w, h);
|
||||
const imageData = ctx.getImageData(0, 0, w, h);
|
||||
return { width: imageData.width, height: imageData.height, data: imageData.data };
|
||||
return {
|
||||
width: imageData.width,
|
||||
height: imageData.height,
|
||||
data: imageData.data,
|
||||
};
|
||||
} finally {
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
}
|
||||
|
||||
export async function jpegRoundtrip(img: PixelImage, qualityPercent: number): Promise<PixelImage> {
|
||||
export async function jpegRoundtrip(
|
||||
img: PixelImage,
|
||||
qualityPercent: number,
|
||||
): Promise<PixelImage> {
|
||||
const quality = Math.min(Math.max(Math.trunc(qualityPercent), 1), 100) / 100;
|
||||
const jpegBlob = await encode(img, 'image/jpeg', quality);
|
||||
const jpegBlob = await encode(img, "image/jpeg", quality);
|
||||
const bitmap = await createImageBitmap(jpegBlob);
|
||||
try {
|
||||
return await decodeBitmap(bitmap);
|
||||
|
||||
@@ -1,79 +1,75 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
extractByColor,
|
||||
isGrayscaleish,
|
||||
luma01,
|
||||
rarityPredicate,
|
||||
renderPredicateMask
|
||||
} from './masks';
|
||||
import { makeImage } from './test-helpers';
|
||||
renderPredicateMask,
|
||||
} from "./masks";
|
||||
import { makeImage } from "./test-helpers";
|
||||
|
||||
const px = makeImage(2, 1, [
|
||||
[255, 0, 0, 255],
|
||||
[10, 10, 10, 255]
|
||||
[10, 10, 10, 255],
|
||||
]);
|
||||
|
||||
describe('isGrayscaleish / luma01', () => {
|
||||
it('серый распознаётся с допуском, цветной — нет', () => {
|
||||
describe("isGrayscaleish / luma01", () => {
|
||||
it("серый распознаётся с допуском, цветной — нет", () => {
|
||||
expect(isGrayscaleish(10, 10, 10, 0)).toBe(true);
|
||||
expect(isGrayscaleish(12, 10, 11, 2)).toBe(true);
|
||||
expect(isGrayscaleish(255, 0, 0, 0)).toBe(false);
|
||||
});
|
||||
|
||||
it('luma01: белый 1, чёрный 0', () => {
|
||||
it("luma01: белый 1, чёрный 0", () => {
|
||||
expect(luma01(255, 255, 255)).toBeCloseTo(1);
|
||||
expect(luma01(0, 0, 0)).toBeCloseTo(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderPredicateMask', () => {
|
||||
it('binary: совпавшие белые на чёрном, альфа принудительная', () => {
|
||||
const out = renderPredicateMask(
|
||||
px,
|
||||
(r) => r > 200,
|
||||
{ mode: 'binary' }
|
||||
);
|
||||
describe("renderPredicateMask", () => {
|
||||
it("binary: совпавшие белые на чёрном, альфа принудительная", () => {
|
||||
const out = renderPredicateMask(px, (r) => r > 200, { mode: "binary" });
|
||||
expect([...out.data.slice(0, 4)]).toEqual([255, 255, 255, 255]);
|
||||
expect([...out.data.slice(4, 8)]).toEqual([0, 0, 0, 255]);
|
||||
});
|
||||
|
||||
it('highlight: подкрашивает только совпавшие, остальные без изменений', () => {
|
||||
const out = renderPredicateMask(
|
||||
px,
|
||||
(r) => r > 200,
|
||||
{ mode: 'highlight', color: '#0000ff', opacityPercent: 100 }
|
||||
);
|
||||
it("highlight: подкрашивает только совпавшие, остальные без изменений", () => {
|
||||
const out = renderPredicateMask(px, (r) => r > 200, {
|
||||
mode: "highlight",
|
||||
color: "#0000ff",
|
||||
opacityPercent: 100,
|
||||
});
|
||||
expect([...out.data.slice(0, 4)]).toEqual([0, 0, 255, 255]);
|
||||
expect([...out.data.slice(4, 8)]).toEqual([10, 10, 10, 255]);
|
||||
});
|
||||
|
||||
it('прозрачность оригинала сохраняется в highlight-режиме', () => {
|
||||
it("прозрачность оригинала сохраняется в highlight-режиме", () => {
|
||||
const semi = makeImage(1, 1, [[200, 200, 200, 128]]);
|
||||
const out = renderPredicateMask(semi, () => true, {
|
||||
mode: 'highlight',
|
||||
color: '#00ff00',
|
||||
opacityPercent: 50
|
||||
mode: "highlight",
|
||||
color: "#00ff00",
|
||||
opacityPercent: 50,
|
||||
});
|
||||
expect(out.data[3]).toBe(128);
|
||||
expect(out.data[0]).toBeGreaterThan(90);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rarityPredicate + extractByColor', () => {
|
||||
describe("rarityPredicate + extractByColor", () => {
|
||||
const img = makeImage(3, 1, [
|
||||
[255, 0, 0, 255],
|
||||
[255, 0, 0, 255],
|
||||
[0, 255, 0, 255]
|
||||
[0, 255, 0, 255],
|
||||
]);
|
||||
|
||||
it('уникальный (единичный) цвет находится, массовый — нет', () => {
|
||||
it("уникальный (единичный) цвет находится, массовый — нет", () => {
|
||||
const pred = rarityPredicate(img, 1);
|
||||
expect(pred(0, 255, 0, 255)).toBe(true);
|
||||
expect(pred(255, 0, 0, 255)).toBe(false);
|
||||
});
|
||||
|
||||
it('extractByColor оставляет близкие и делает дальние прозрачными', () => {
|
||||
const out = extractByColor(px, '#0a0a0a', 5);
|
||||
it("extractByColor оставляет близкие и делает дальние прозрачными", () => {
|
||||
const out = extractByColor(px, "#0a0a0a", 5);
|
||||
expect(out.data[3]).toBe(0);
|
||||
expect(out.data[7]).toBe(255);
|
||||
});
|
||||
|
||||
+36
-14
@@ -1,8 +1,8 @@
|
||||
import { hexToRgb } from './palette';
|
||||
import type { PixelImage } from './types';
|
||||
import { createPixelImage } from './types';
|
||||
import { hexToRgb } from "./palette";
|
||||
import type { PixelImage } from "./types";
|
||||
import { createPixelImage } from "./types";
|
||||
|
||||
export type MaskMode = 'binary' | 'highlight';
|
||||
export type MaskMode = "binary" | "highlight";
|
||||
|
||||
export interface MaskOptions {
|
||||
/** binary: белое/чёрное без альфы; highlight: подкрасить совпавшие пиксели цветом. */
|
||||
@@ -18,10 +18,10 @@ export interface MaskOptions {
|
||||
export function renderPredicateMask(
|
||||
img: PixelImage,
|
||||
predicate: (r: number, g: number, b: number, a: number) => boolean,
|
||||
o: MaskOptions = {}
|
||||
o: MaskOptions = {},
|
||||
): PixelImage {
|
||||
const out = createPixelImage(img.width, img.height);
|
||||
const highlight = o.mode !== 'binary';
|
||||
const highlight = o.mode !== "binary";
|
||||
const tint = o.color ? hexToRgb(o.color) : { r: 255, g: 0, b: 170 };
|
||||
const opacity = Math.min(Math.max(o.opacityPercent ?? 70, 0), 100) / 100;
|
||||
if (!highlight) {
|
||||
@@ -34,7 +34,7 @@ export function renderPredicateMask(
|
||||
const b = img.data[i + 2];
|
||||
const a = img.data[i + 3];
|
||||
if (!predicate(r, g, b, a)) {
|
||||
if (highlight && o.mode === 'highlight') {
|
||||
if (highlight && o.mode === "highlight") {
|
||||
out.data[i] = r;
|
||||
out.data[i + 1] = g;
|
||||
out.data[i + 2] = b;
|
||||
@@ -57,13 +57,27 @@ export function renderPredicateMask(
|
||||
return out;
|
||||
}
|
||||
|
||||
function maxChannelDelta(r1: number, g1: number, b1: number, r2: number, g2: number, b2: number): number {
|
||||
function maxChannelDelta(
|
||||
r1: number,
|
||||
g1: number,
|
||||
b1: number,
|
||||
r2: number,
|
||||
g2: number,
|
||||
b2: number,
|
||||
): number {
|
||||
return Math.max(Math.abs(r1 - r2), Math.abs(g1 - g2), Math.abs(b1 - b2));
|
||||
}
|
||||
|
||||
export function isGrayscaleish(r: number, g: number, b: number, tolerance: number): boolean {
|
||||
export function isGrayscaleish(
|
||||
r: number,
|
||||
g: number,
|
||||
b: number,
|
||||
tolerance: number,
|
||||
): boolean {
|
||||
return (
|
||||
Math.abs(r - g) <= tolerance && Math.abs(g - b) <= tolerance && Math.abs(r - b) <= tolerance
|
||||
Math.abs(r - g) <= tolerance &&
|
||||
Math.abs(g - b) <= tolerance &&
|
||||
Math.abs(r - b) <= tolerance
|
||||
);
|
||||
}
|
||||
|
||||
@@ -78,13 +92,22 @@ export function luma01(r: number, g: number, b: number): number {
|
||||
export function extractByColor(
|
||||
img: PixelImage,
|
||||
targetHex: string,
|
||||
tolerancePercent: number
|
||||
tolerancePercent: number,
|
||||
): PixelImage {
|
||||
const out = createPixelImage(img.width, img.height);
|
||||
const t = hexToRgb(targetHex);
|
||||
const tol = (Math.min(Math.max(tolerancePercent, 0), 100) / 100) * 255;
|
||||
for (let i = 0; i < img.data.length; i += 4) {
|
||||
if (maxChannelDelta(img.data[i], img.data[i + 1], img.data[i + 2], t.r, t.g, t.b) <= tol) {
|
||||
if (
|
||||
maxChannelDelta(
|
||||
img.data[i],
|
||||
img.data[i + 1],
|
||||
img.data[i + 2],
|
||||
t.r,
|
||||
t.g,
|
||||
t.b,
|
||||
) <= tol
|
||||
) {
|
||||
out.data[i] = img.data[i];
|
||||
out.data[i + 1] = img.data[i + 1];
|
||||
out.data[i + 2] = img.data[i + 2];
|
||||
@@ -99,7 +122,7 @@ export function extractByColor(
|
||||
*/
|
||||
export function rarityPredicate(
|
||||
img: PixelImage,
|
||||
limit: number
|
||||
limit: number,
|
||||
): (r: number, g: number, b: number, a: number) => boolean {
|
||||
const counts = new Map<number, number>();
|
||||
for (let i = 0; i < img.data.length; i += 4) {
|
||||
@@ -111,4 +134,3 @@ export function rarityPredicate(
|
||||
return (counts.get(key) ?? 0) <= limit;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildAlphaMask,
|
||||
closingImage,
|
||||
@@ -8,15 +8,15 @@ import {
|
||||
erodeImage,
|
||||
erodeMask,
|
||||
openingImage,
|
||||
strokeImage
|
||||
} from './morphology';
|
||||
import { makeImage } from './test-helpers';
|
||||
strokeImage,
|
||||
} from "./morphology";
|
||||
import { makeImage } from "./test-helpers";
|
||||
|
||||
function maskFrom(rows: string[]): Uint8Array {
|
||||
const flat = rows.join('');
|
||||
const flat = rows.join("");
|
||||
const mask = new Uint8Array(flat.length);
|
||||
for (let i = 0; i < flat.length; i++) {
|
||||
mask[i] = flat[i] === '#' ? 1 : 0;
|
||||
mask[i] = flat[i] === "#" ? 1 : 0;
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
@@ -24,66 +24,74 @@ function maskFrom(rows: string[]): Uint8Array {
|
||||
function toRows(mask: Uint8Array, w: number): string[] {
|
||||
const rows: string[] = [];
|
||||
for (let y = 0; y < mask.length / w; y++) {
|
||||
let row = '';
|
||||
let row = "";
|
||||
for (let x = 0; x < w; x++) {
|
||||
row += mask[y * w + x] === 1 ? '#' : '.';
|
||||
row += mask[y * w + x] === 1 ? "#" : ".";
|
||||
}
|
||||
rows.push(row);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
describe('dilateMask', () => {
|
||||
it('одиночный пиксель r=1 превращается в плюс', () => {
|
||||
describe("dilateMask", () => {
|
||||
it("одиночный пиксель r=1 превращается в плюс", () => {
|
||||
const out = dilateMask(
|
||||
maskFrom(['.....', '.....', '..#..', '.....', '.....']),
|
||||
maskFrom([".....", ".....", "..#..", ".....", "....."]),
|
||||
5,
|
||||
5,
|
||||
1
|
||||
1,
|
||||
);
|
||||
expect(toRows(out, 5)).toEqual(['.....', '..#..', '.###.', '..#..', '.....']);
|
||||
expect(toRows(out, 5)).toEqual([
|
||||
".....",
|
||||
"..#..",
|
||||
".###.",
|
||||
"..#..",
|
||||
".....",
|
||||
]);
|
||||
});
|
||||
|
||||
it('r=2 даёт ромб радиуса 2', () => {
|
||||
it("r=2 даёт ромб радиуса 2", () => {
|
||||
const out = dilateMask(
|
||||
maskFrom(['.....', '.....', '..#..', '.....', '.....']),
|
||||
maskFrom([".....", ".....", "..#..", ".....", "....."]),
|
||||
5,
|
||||
5,
|
||||
2
|
||||
2,
|
||||
);
|
||||
expect(toRows(out, 5)).toEqual(['..#..', '.###.', '#####', '.###.', '..#..']);
|
||||
expect(toRows(out, 5)).toEqual([
|
||||
"..#..",
|
||||
".###.",
|
||||
"#####",
|
||||
".###.",
|
||||
"..#..",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('erodeMask', () => {
|
||||
it('сплошной объект во весь кадр не сжимается от границ', () => {
|
||||
const solid = maskFrom(['#####', '#####', '#####', '#####', '#####']);
|
||||
describe("erodeMask", () => {
|
||||
it("сплошной объект во весь кадр не сжимается от границ", () => {
|
||||
const solid = maskFrom(["#####", "#####", "#####", "#####", "#####"]);
|
||||
expect([...erodeMask(solid, 5, 5, 1)]).toEqual([...solid]);
|
||||
});
|
||||
|
||||
it('изолированный пиксель исчезает', () => {
|
||||
it("изолированный пиксель исчезает", () => {
|
||||
const out = erodeMask(
|
||||
maskFrom(['.....', '.....', '..#..', '.....', '.....']),
|
||||
maskFrom([".....", ".....", "..#..", ".....", "....."]),
|
||||
5,
|
||||
5,
|
||||
1
|
||||
1,
|
||||
);
|
||||
expect([...out].every((v) => v === 0)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('opening/closing образы', () => {
|
||||
it('opening убирает отстоящий мусорный пиксель и сохраняет блок', () => {
|
||||
describe("opening/closing образы", () => {
|
||||
it("opening убирает отстоящий мусорный пиксель и сохраняет блок", () => {
|
||||
const B = [10, 10, 10, 255];
|
||||
const T = [0, 0, 0, 0];
|
||||
const S = [200, 200, 200, 255];
|
||||
const out = openingImage(
|
||||
makeImage(
|
||||
6,
|
||||
3,
|
||||
[B, B, B, T, S, T, B, B, B, T, T, T, B, B, B, T, T, T]
|
||||
),
|
||||
1
|
||||
makeImage(6, 3, [B, B, B, T, S, T, B, B, B, T, T, T, B, B, B, T, T, T]),
|
||||
1,
|
||||
);
|
||||
const at = (x: number, y: number) => out.data[(y * 6 + x) * 4 + 3];
|
||||
expect(at(0, 1)).toBe(255);
|
||||
@@ -91,7 +99,7 @@ describe('opening/closing образы', () => {
|
||||
expect(at(4, 1)).toBe(0);
|
||||
});
|
||||
|
||||
it('closing заполняет одиночную прозрачную дыру чёрным', () => {
|
||||
it("closing заполняет одиночную прозрачную дыру чёрным", () => {
|
||||
const pixels: number[][] = [];
|
||||
for (let y = 0; y < 3; y++) {
|
||||
for (let x = 0; x < 3; x++) {
|
||||
@@ -104,27 +112,32 @@ describe('opening/closing образы', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('image-обёртки', () => {
|
||||
it('dilateImage сохраняет RGB содержимого, новые пиксели непрозрачны', () => {
|
||||
describe("image-обёртки", () => {
|
||||
it("dilateImage сохраняет RGB содержимого, новые пиксели непрозрачны", () => {
|
||||
const T = [0, 0, 0, 0];
|
||||
const O = [200, 50, 25, 255];
|
||||
const img = makeImage(5, 2, [T, O, T, T, T, T, T, T, T, T]);
|
||||
const out = dilateImage(img, 1);
|
||||
const at = (x: number, y: number) => {
|
||||
const di = (y * 5 + x) * 4;
|
||||
return [out.data[di], out.data[di + 1], out.data[di + 2], out.data[di + 3]];
|
||||
return [
|
||||
out.data[di],
|
||||
out.data[di + 1],
|
||||
out.data[di + 2],
|
||||
out.data[di + 3],
|
||||
];
|
||||
};
|
||||
expect(at(1, 0)).toEqual([200, 50, 25, 255]);
|
||||
expect(at(0, 0)).toEqual([0, 0, 0, 255]);
|
||||
expect(at(4, 0)[3]).toBe(0);
|
||||
});
|
||||
|
||||
it('erodeImage не стирает объект у края кадра', () => {
|
||||
it("erodeImage не стирает объект у края кадра", () => {
|
||||
const img = makeImage(2, 2, [
|
||||
[10, 20, 30, 255],
|
||||
[10, 20, 30, 255],
|
||||
[10, 20, 30, 255],
|
||||
[10, 20, 30, 255]
|
||||
[10, 20, 30, 255],
|
||||
]);
|
||||
const out = erodeImage(img, 1);
|
||||
for (let i = 0; i < out.data.length; i += 4) {
|
||||
@@ -133,34 +146,44 @@ describe('image-обёртки', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('strokeImage', () => {
|
||||
it('кольцо цвета обводки вокруг квадрата', () => {
|
||||
describe("strokeImage", () => {
|
||||
it("кольцо цвета обводки вокруг квадрата", () => {
|
||||
const pixels: number[][] = [];
|
||||
for (let y = 0; y < 7; y++) {
|
||||
for (let x = 0; x < 7; x++) {
|
||||
pixels.push(x >= 2 && x <= 4 && y >= 2 && y <= 4 ? [255, 0, 0, 255] : [0, 0, 0, 0]);
|
||||
pixels.push(
|
||||
x >= 2 && x <= 4 && y >= 2 && y <= 4
|
||||
? [255, 0, 0, 255]
|
||||
: [0, 0, 0, 0],
|
||||
);
|
||||
}
|
||||
}
|
||||
const out = strokeImage(makeImage(7, 7, pixels), 1, '#0000ff');
|
||||
const at = (x: number, y: number) =>
|
||||
[...out.data.slice((y * 7 + x) * 4, (y * 7 + x) * 4 + 4)];
|
||||
const out = strokeImage(makeImage(7, 7, pixels), 1, "#0000ff");
|
||||
const at = (x: number, y: number) => [
|
||||
...out.data.slice((y * 7 + x) * 4, (y * 7 + x) * 4 + 4),
|
||||
];
|
||||
expect(at(2, 3)).toEqual([255, 0, 0, 255]);
|
||||
expect(at(1, 3)).toEqual([0, 0, 255, 255]);
|
||||
expect(at(0, 0)).toEqual([0, 0, 0, 0]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('contourImage', () => {
|
||||
it('линия по краю квадрата, центр прозрачен', () => {
|
||||
describe("contourImage", () => {
|
||||
it("линия по краю квадрата, центр прозрачен", () => {
|
||||
const pixels: number[][] = [];
|
||||
for (let y = 0; y < 7; y++) {
|
||||
for (let x = 0; x < 7; x++) {
|
||||
pixels.push(x >= 2 && x <= 4 && y >= 2 && y <= 4 ? [255, 0, 0, 255] : [0, 0, 0, 0]);
|
||||
pixels.push(
|
||||
x >= 2 && x <= 4 && y >= 2 && y <= 4
|
||||
? [255, 0, 0, 255]
|
||||
: [0, 0, 0, 0],
|
||||
);
|
||||
}
|
||||
}
|
||||
const out = contourImage(makeImage(7, 7, pixels), 1, '#0000ff');
|
||||
const at = (x: number, y: number) =>
|
||||
[...out.data.slice((y * 7 + x) * 4, (y * 7 + x) * 4 + 4)];
|
||||
const out = contourImage(makeImage(7, 7, pixels), 1, "#0000ff");
|
||||
const at = (x: number, y: number) => [
|
||||
...out.data.slice((y * 7 + x) * 4, (y * 7 + x) * 4 + 4),
|
||||
];
|
||||
expect(at(2, 2)).toEqual([0, 0, 255, 255]);
|
||||
expect(at(3, 3)).toEqual([0, 0, 0, 0]);
|
||||
expect(at(1, 3)).toEqual([0, 0, 0, 0]);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user