WLED/wled00/data/pxmagic/pxmagic.htm
2023-06-13 19:42:16 -03:00

2081 lines
58 KiB
HTML

<!DOCTYPE html>
<html lang="pt_BR">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta
http-equiv="Cache-Control"
content="no-cache, no-store, must-revalidate"
/>
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<title>Pixel Magic Tool - @ajotanc</title>
<link
rel="shortcut icon"
href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAK9JREFUeNqUUssNwyAMJZWVUw4dhRHakZA6RqWMFEbwKDnk1FNBekEWxOBYQggL/D68yXXq+M7PtHkcefn89vrOw/UrP96w/NUFGiDLRz71GyY0QJa1Yn+nFa0ShqUNYCAF0QvoceOB4naEZif6UTNRapYaTyauRi4DEspr4Hbs5YKsbmtMyeJ0LxeESV4gB+hlSy4oO2txWysyus0a0+lO6vBjxcTMlG4mt2H6F2AAhU5NWu4dorQAAAAASUVORK5CYII=
"
/>
<style>
* {
box-sizing: border-box;
font-family: "Tahoma", monospace;
margin: 0;
padding: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
font-size: 12px;
}
small {
display: block;
font-size: 11px;
font-weight: 400;
margin: 2px 0 5px;
color: #1982c4;
}
a {
text-decoration: none;
color: #1982c4;
}
a:hover,
a:focus,
a:active {
color: #235789;
}
.divider {
width: calc(100% - 10px);
height: 1px;
background: #ececec;
margin: 20px auto;
}
.container {
display: flex;
align-items: center;
justify-content: center;
}
.content {
width: 100%;
min-width: 540px;
max-width: 900px;
margin: 20px;
}
.w-full {
flex-basis: 100% !important;
}
.m-zero {
margin: 0 !important;
}
#response,
#preview,
form,
canvas {
width: 100%;
}
form {
margin: 0 auto;
padding: 20px;
background-color: #f8f8f8;
border-radius: 8px;
border: 1px solid #cccccc;
}
.row {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
margin: 20px 0 0;
}
.row:nth-child(2) {
margin: 0;
}
.column {
flex-basis: calc(50% - 10px);
position: relative;
padding: 0 5px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input[type="text"],
input[type="number"],
select,
textarea {
width: 100%;
padding: 10px;
border-radius: 5px;
border: none;
background-color: #f0f0f0;
font-size: 12px;
display: inline-block;
outline: none;
}
input[type="color"] {
width: 32px;
height: 32px;
cursor: pointer;
padding: 0px 1px;
outline: none;
}
.input-group {
display: flex;
}
.input-group input {
border-radius: 5px 0 0 5px;
}
.input-group .input-description {
padding: 10px;
font-size: 14px;
color: #626262;
background: #d9d9d9;
border-radius: 0px 5px 5px 0;
}
textarea {
resize: vertical;
min-height: 120px;
margin: 0 0 10px;
}
input[type="submit"] {
padding: 10px 20px;
border: none;
border-radius: 5px;
background-color: #4caf50;
color: #fff;
font-size: 12px;
cursor: pointer;
}
.dropzone {
width: 100%;
border: 1px dashed #a9a9a9;
background-color: #f5f5f5;
color: #666;
font-size: 12px;
text-align: center;
padding: 40px 10px;
border-radius: 5px;
margin: 20px 0;
transition: all 0.5s ease-in-out;
}
.dropzone p {
margin: 0;
padding: 0;
}
.dropzone:hover {
cursor: pointer;
background-color: #eee;
}
.dropzone.dragover {
background-color: #ddd;
}
.range-slider {
appearance: none;
background-color: #ddd;
height: 8px;
width: 100%;
border-radius: 10px;
outline: none;
margin: 16px 0;
}
.range-slider::-webkit-slider-thumb {
appearance: none;
height: 16px;
width: 16px;
background-color: #4caf50;
border-radius: 50%;
cursor: pointer;
border: 0;
}
.switch {
position: relative;
display: inline-block;
width: 38px;
height: 20px;
}
.switch input {
outline: none;
display: none;
}
.switch-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
border-radius: 34px;
transition: 0.4s;
}
.switch-slider:before {
position: absolute;
content: "";
height: 14px;
width: 14px;
left: 3px;
bottom: 3px;
background-color: white;
border-radius: 50%;
transition: 0.4s;
}
input:checked + .switch-slider {
background-color: #4caf50;
}
input:focus + .switch-slider {
box-shadow: 0 0 1px #4caf50;
}
input:checked + .switch-slider:before {
transform: translateX(18px);
}
#toast-container {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 9999;
}
.toast {
display: flex;
align-items: center;
width: max-content;
padding: 6px 12px;
margin: 10px 0 0;
border-radius: 8px;
color: #fff;
font-size: 12px;
transform: translateY(30px);
opacity: 0;
visibility: hidden;
}
.toast .toast-body {
padding: 8px 0;
color: #fdfdfd;
}
.toast.success {
background-color: #8ac926;
}
.toast.error {
background-color: #ff595e;
}
.toast.warning {
background-color: #f48c06;
}
.toast-progress {
position: absolute;
left: 4px;
bottom: 4px;
width: calc(100% - 8px);
height: 3px;
transform: scaleX(0);
transform-origin: left;
border-radius: inherit;
}
.toast.success .toast-progress {
background: linear-gradient(to right, #8ac926, #548c2f);
}
.toast.error .toast-progress {
background: linear-gradient(to right, #ff595e, #c9262b);
}
.toast.warning .toast-progress {
background: linear-gradient(to right, #f48c06, #e85d04);
}
#multipleCanvas {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
position: relative;
}
#multipleCanvas .carousel {
display: flex;
height: 100%;
width: 100%;
cursor: pointer;
}
#multipleCanvas .carousel img {
display: block;
width: 100%;
height: 100%;
margin-right: 20px;
border: 0;
}
#multipleCanvas .carousel img:last-child {
margin-right: 0;
}
.button {
width: 100%;
border: 0;
padding: 10px 18px;
border-radius: 4px;
color: #fdfdfd;
cursor: pointer;
margin: 0 0 10px;
background: #1982c4;
transition: all 0.5s ease-in-out;
}
.button:hover {
background: #4267ac;
}
.button:last-child {
margin-bottom: 0;
}
.buttons {
display: flex;
flex-direction: column;
width: 100%;
}
.buttonRainbow {
width: 100%;
border: 0;
padding: 10px 18px;
border-radius: 4px;
color: #fdfdfd;
cursor: pointer;
background: linear-gradient(
to right,
#ff595e,
#ffca3a,
#8ac926,
#1982c4,
#6a4c93
);
}
.buttonRainbow:hover {
animation-play-state: paused;
}
#preview {
border: 1px solid #cccccc;
padding: 20px;
margin: 20px 0 10px;
border-radius: 8px;
}
#preview .buttons {
margin: 0 0 20px;
}
#overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: none;
}
#overlay.loading::after {
content: "";
display: block;
position: absolute;
top: calc(50% - 19px);
left: calc(50% - 19px);
width: 26px;
height: 26px;
border: 6px solid rgba(255, 255, 255, 0.5);
border-radius: 50%;
animation: spin 1s linear infinite;
}
input.invalid,
select.invalid,
textarea.invalid {
border: 1px solid #df1f1f;
}
input.invalid + .error-message,
select.invalid + .error-message,
textarea.invalid + .error-message {
display: block;
color: #df1f1f;
padding: 4px 0;
font-size: 14px;
font-weight: 600;
}
.slide-container {
width: 100%;
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
}
.slide {
scroll-snap-align: center;
}
.header {
display: flex;
align-items: center;
padding: 0 0 30px;
flex-direction: column;
}
.header .brand {
width: 100%;
max-width: 200px;
height: 100%;
display: block;
outline: none;
border: 0;
}
footer {
margin-top: 10px;
}
@media (max-width: 767px) {
.content {
min-width: 360px;
}
.row {
flex-direction: column;
margin: 0;
}
.column {
flex-basis: 100%;
margin: 20px 0 0;
padding: 0;
}
.divider {
margin: 20px auto 0;
}
}
@media (min-width: 768px) {
.row {
flex-wrap: nowrap;
}
}
@keyframes spin {
to {
transform: rotate(360deg);
}
0% {
border-top-color: #ff595e;
}
25% {
border-top-color: #ffca3a;
}
50% {
border-top-color: #8ac926;
}
75% {
border-top-color: #1982c4;
}
100% {
border-top-color: #6a4c93;
}
}
@keyframes progress {
to {
transform: scaleX(1);
}
}
@keyframes fadeIn {
5% {
opacity: 1;
visibility: visible;
transform: translateY(0);
}
95% {
opacity: 1;
transform: translateY(0);
}
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<form id="formGenerate" novalidate>
<div class="header">
<svg
class="brand"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
x="0px"
y="0px"
viewBox="0 0 560 360"
enable-background="new 0 0 560 360"
xml:space="preserve"
>
<image
x="0"
y="0"
href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAjAAAAFoCAMAAAB+GjFaAAAABGdBTUEAALGPC/xhBQAAACBjSFJN
AAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAA8FBMVEUAAAD0jAb0jAb0jAb0
jAb0jAb0jAb0jAYlJSUlJSUlJSX0jAb0jAb0jAYlJSUlJSUlJSUlJSUlJSX0jAYlJSUlJSUlJSUl
JSUlJSVqTJNqTJNqTJNqTJNqTJNqTJMZgsSKySb/yjr/WV6KySYZgsT/WV6KySaKySZqTJP/WV7/
WV4ZgsT/WV7/WV7/WV7/yjoZgsQZgsSKySZqTJNqTJOKySYZgsSKySaKySb/WV7/WV4ZgsSKySZq
TJMZgsSKySaKySaKySYZgsQZgsT/yjr/yjr/yjolJSX0jAYlJSVqTJMZgsSKySb/yjr/WV7///+0
60LYAAAASHRSTlMAj78wQIDfn2C/gM9wIBBAMCCfYI/P799wIIBgQL/vQIC/QL+/v0Bw3xDPEHCA
34/fgGDPcDBgnxBgIJ/fEM+PzyAwIJ+AQFCp9vlwAAAAAWJLR0RPbmZBSQAAAAd0SU1FB+cGCgIB
LXgoLQQAAAtPSURBVHja7d1rQ9vWAYdxQoFgkiBwQwkEGgokTZMlS9ru0jXd1u5Wlm7f/+O0WJLR
OT63vyRbFz/PO9DFkvWrSyzpaGODiIiIiIiIiIiIiIiIqNvubRZ90vWW0CDa/Lloq+stoUEEGJIC
DEkBhqQAQ1KAobS283ZKMPfzn3FD7n52t931dlFPAwxJAYakAENSgCGpOmB2J+G63qc6zfdpt+st
6Xl1wOzdhOt6n+o036e9rrek5wHG2ifAhNvKe1BKeZj//Ci0DGBIOjUAGAIMYKQAAxipNDB7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nJw/j
swBmREXA3Hi6uwIik2bpenepaYAhKcCQFGBICjAkFQFjfuXv0rBvzPEEMCNPOvno0mCWAWbkAYak
AENSYTD5oZ5/0397z/WxtYA5y4F/FsCMIgmMa4HkWQAzigBDUoAhKT+Yu5tcvRoSZrkNMCPKD2Yy
n+DVkDDLbYAZUYAhKcCQFGBICjAkBRiSAgxJAYakAENSKWBmZY4FEma5DTAjKuVcUqoGwKxBgCEp
wJBUMpjpbMzn/2RTv4aEWbreXWpaMhizmY0as3S9u9S0mmC4kW1dAwxJAYakAENSOZgnt/dFO6bu
3z3eM0dQtq/MkoOZel6DBtWe9WngnSX4ASHfe0BDDTAkBRiSAgwRERERERERERERERENol8B24m3
Ck3A57UAAAAldEVYdGRhdGU6Y3JlYXRlADIwMjMtMDYtMTBUMDI6MDE6NDUrMDA6MDB2cvTKAAAA
JXRFWHRkYXRlOm1vZGlmeQAyMDIzLTA2LTEwVDAyOjAxOjQ1KzAwOjAwBy9MdgAAACh0RVh0ZGF0
ZTp0aW1lc3RhbXAAMjAyMy0wNi0xMFQwMjowMTo0NSswMDowMFA6bakAAAAZdEVYdFNvZnR3YXJl
AEFkb2JlIEltYWdlUmVhZHlxyWU8AAAAAElFTkSuQmCC"
/>
</svg>
</div>
<div class="row">
<div class="column valitade">
<label for="hostname">Hostname</label>
<input type="text" name="hostname" id="hostname" required />
</div>
<div class="column valitade">
<label for="name">Preset Name</label>
<input
type="text"
name="name"
id="name"
value="New Preset"
required
/>
</div>
</div>
<div class="row">
<div class="column valitade">
<label for="pattern">Pattern</label>
<select name="pattern" id="pattern" required>
<option value="">Select a choice</option>
<option value="1" title="['ffffff']" selected>
Individual
</option>
<option value="2" title="[0, 'ffffff']">Index</option>
<option value="3" title="[0, 5, 'ffffff']">Range</option>
</select>
</div>
<div class="column valitade">
<label for="output">Output</label>
<select name="output" id="output" required>
<option value="">Select a choice</option>
<option value="json" selected>WLED JSON</option>
<option value="ha">Home Assistant</option>
<option value="curl">CURL</option>
</select>
</div>
</div>
<div class="row output" style="display: none">
<div class="column valitade">
<label for="device">Device</label>
<input type="text" name="device" id="device" required />
</div>
<div class="column valitade">
<label for="uniqueId">Unique Id</label>
<input type="text" name="uniqueId" id="uniqueId" required />
</div>
<div class="column valitade">
<label for="friendlyName">Friendly Name</label>
<input
type="text"
name="friendlyName"
id="friendlyName"
required
/>
</div>
</div>
<div class="row">
<div class="column valitade">
<label for="segments">Segment Id</label>
<select name="segments" id="segments" required>
<option value="">Select a choice</option>
</select>
</div>
<div class="column valitade">
<label for="brightness">Brightness</label>
<input
type="range"
name="brightness"
id="brightness"
min="0"
max="255"
value="128"
class="range-slider"
/>
</div>
</div>
<div class="row">
<div class="column valitade">
<label for="animation">Animation</label>
<label class="switch">
<input type="checkbox" name="animation" id="animation" />
<span class="switch-slider"></span>
</label>
</div>
<div class="column valitade">
<label for="transparentImage">Transparent Image</label>
<label class="switch">
<input
type="checkbox"
name="transparentImage"
id="transparentImage"
/>
<span class="switch-slider"></span>
</label>
</div>
<div class="column valitade">
<label for="resizeImage">Resize Image</label>
<label class="switch">
<input type="checkbox" name="resizeImage" id="resizeImage" />
<span class="switch-slider"></span>
</label>
</div>
</div>
<div class="row resizeImage" style="display: none">
<div class="column valitade">
<label for="width">Width</label>
<input type="number" name="width" id="width" value="16" />
</div>
<div class="column valitade">
<label for="height">Height</label>
<input type="number" name="height" id="height" value="16" />
</div>
</div>
<div class="row animation" style="display: none">
<div class="column valitade">
<label for="frames">Frames</label>
<input type="number" name="frames" id="frames" value="4" />
</div>
<div class="column valitade">
<label for="duration">Duration</label>
<div class="input-group">
<input
type="number"
name="duration"
id="duration"
value="0.5"
required="required"
min="0"
step="0.1"
inputmode="numeric"
/>
<div class="input-description">sec</div>
</div>
</div>
<div class="column valitade">
<label for="transition">Transition</label>
<div class="input-group">
<input
type="number"
name="transition"
id="transition"
value="0.2"
required="required"
min="0"
step="0.1"
inputmode="numeric"
/>
<div class="input-description">sec</div>
</div>
</div>
</div>
<div class="row transparentImage" style="display: none">
<div class="column valitade w-full">
<label for="color">Choose a color</label>
<small class="subtitle"
>Color that will replace the
<strong>transparent pixels</strong> in the image</small
>
<input type="color" name="color" id="color" value="#ffffff" />
</div>
</div>
<div class="row">
<div class="column valitade w-full">
<label for="images">Images</label>
<small class="subtitle"
>Images uploaded to
<a href="http://[wled-ip]/edit" target="_blank"
><strong>WLED</strong></a
>
or upload image</small
>
<select name="images" id="images" required>
<option value="">Select a choice</option>
</select>
</div>
</div>
<div id="dropzone" class="dropzone valitade" style="display: none">
<p id="dropzoneLabel">
Drag and drop a file here or click to select a file
</p>
<input
type="file"
name="source"
id="source"
accept="image/*"
style="display: none"
/>
</div>
<div class="row">
<div class="column w-full">
<button type="button" class="buttonRainbow" id="btnGenerate">
Generate
</button>
</div>
</div>
</form>
<div id="preview" style="display: none">
<div class="row m-zero">
<div class="column w-full">
<textarea
name="response"
id="response"
cols="30"
rows="10"
readonly="readonly"
></textarea>
</div>
</div>
<div id="isNotAnimation">
<div class="buttons">
<div class="row m-zero">
<div class="column">
<button type="button" class="button" id="btnCopyToClipboard">
Copy to Clipboard
</button>
</div>
<div class="column">
<button type="button" class="button" id="btnDownloadPreset">
Download
</button>
</div>
</div>
<div class="divider"></div>
<div class="row m-zero">
<div class="column">
<button type="button" class="button" id="btnSimulatePreset">
Simulate
</button>
</div>
<div class="column">
<button type="button" class="button" id="btnSavePreset">
Save
</button>
</div>
</div>
</div>
<div id="singleCanvas"></div>
</div>
<div id="isAnimation">
<div class="buttons">
<div class="row m-zero">
<div class="column">
<button type="button" class="button" id="btnCopyToClipboard">
Copy to Clipboard
</button>
</div>
<div class="column">
<button type="button" class="button" id="btnDownloadPreset">
Download
</button>
</div>
</div>
<div class="divider"></div>
<div class="row m-zero">
<div class="column w-full">
<button type="button" class="button" id="btnSavePlaylist">
Save
</button>
</div>
</div>
</div>
<div id="multipleCanvas"></div>
</div>
</div>
<footer>
<a href="https://github.com/ajotanc/PixelMagicTool" target="_blank"
>Github &copy; Pixel Magic Tool</a
>
</footer>
</div>
</div>
<div id="toast-container"></div>
<div id="overlay"></div>
</body>
<script>
const protocol =
window.location.protocol === "file:" ? "http:" : window.location.protocol;
const host = "10.0.0.41";
// const host = window.location.host || "0.0.0.0";
let wledUrl = `${protocol}//${host}`;
const hostname = document.getElementById("hostname");
hostname.value = host;
hostname.addEventListener("change", async () => {
wledUrl = `${protocol}//${hostname.value}`;
await segments();
await images();
hostnameLabel();
});
let jsonSaveWLED = [];
let jsonSendWLED = {};
(async function () {
await segments();
await images();
hostnameLabel();
})();
function hostnameLabel() {
const images = document.getElementById("images");
const link = images.parentNode.querySelector("a");
link.href = link.href.replace("[wled-ip]", hostname.value);
}
async function playlist() {
const { value: duration } = document.getElementById("duration");
const { value: transition } = document.getElementById("transition");
const { value: name } = document.getElementById("name");
const urlPreset = `${wledUrl}/presets.json`;
const url = `${wledUrl}/json`;
try {
const response = await fetch(urlPreset);
const data = await response.json();
const items = Object.keys(data);
const ps = items.filter(
(key) =>
typeof data[key] === "object" &&
!data[key].playlist &&
data[key].n &&
data[key].n.startsWith(name)
);
const psave =
items.find(
(key) =>
typeof data[key] === "object" &&
data[key].playlist &&
data[key].n &&
data[key].n === name
) || parseInt(items.pop()) + 1;
const body = {
psave,
n: name,
on: true,
o: false,
playlist: {
ps,
dur: Array.from({ length: ps.length }, () => duration * 10),
transition: Array.from(
{ length: ps.length },
() => transition * 10
),
repeat: 0,
end: 0,
},
};
const options = {
method: "POST",
body: JSON.stringify(body),
};
try {
const response = await fetch(url, options);
const { success } = await response.json();
if (success) {
toast(`Playlist "${name}" save successfully!`);
}
} catch (error) {
toast(`Error saving preset: ${error}`, "error");
}
} catch (error) {
toast(error, "error");
}
}
async function insert(data, isAnimated = false, delay = 5000) {
const urlPreset = `${wledUrl}/presets.json`;
const url = `${wledUrl}/json`;
let requestsCompleted = 0;
show();
const promises = data.map(async (item) => {
return new Promise((resolve, reject) => {
setTimeout(async () => {
try {
const response = await fetch(urlPreset);
const data = await response.json();
const items = Object.keys(data);
const psave =
items.find(
(key) =>
typeof data[key] === "object" &&
!data[key].playlist &&
data[key].n === item.n
) || parseInt(items.pop()) + 1;
const body = Object.assign(item, { psave });
const options = {
method: "POST",
body: JSON.stringify(body),
};
try {
const response = await fetch(url, options);
const { success } = await response.json();
if (success) {
toast(`Preset "${item.n}" save successfully!`);
}
} catch (error) {
toast(`Error saving preset: ${error}`, "error");
}
} catch (error) {
toast(error, "error");
} finally {
resolve();
}
}, delay * requestsCompleted++);
});
});
await Promise.all(promises);
if (isAnimated) {
setTimeout(async () => {
await playlist()
.then(() => {
hide();
})
.catch(() => {
hide();
});
}, delay);
} else {
hide();
}
}
async function images() {
const url = `${wledUrl}/edit?list=/`;
const selectImages = document.getElementById("images");
selectImages.innerHTML = "";
const options = [
{ text: "Select a choice", value: "" },
{ text: "Upload", value: "upload" },
];
options.forEach(({ text, value }) => {
const option = new Option(text, value);
selectImages.appendChild(option);
});
show();
try {
const response = await fetch(url);
const data = await response.json();
const mimeTypes = ["jpeg", "jpg", "png", "gif"];
const images = data
.filter((file) => {
const { name } = file;
const [filename, mimetype] = name.split(".");
file.name = name.replace("/", "");
return mimeTypes.includes(mimetype);
})
.map((file) => {
const { name } = file;
const option = document.createElement("option");
option.text = name;
option.value = `${wledUrl}/${name}`;
selectImages.add(option);
});
} catch (error) {
toast(error, "error");
} finally {
hide();
}
}
async function segments() {
const selectSegments = document.getElementById("segments");
const pattern = document.getElementById("pattern");
const width = document.getElementById("width");
const height = document.getElementById("height");
const url = `${wledUrl}/json/state`;
selectSegments.innerHTML = "";
const options = [{ text: "Select a choice", value: "" }];
options.forEach(({ text, value }) => {
const option = new Option(text, value);
selectSegments.appendChild(option);
});
show();
try {
const response = await fetch(url);
const { seg: segments } = await response.json();
segments &&
segments.forEach(function ({ id, n, stop: w, stopY: h }, index) {
const option = document.createElement("option");
option.text = n ? n : `Segment ${id}`;
option.value = id;
option.dataset.width = w;
option.dataset.height = h;
if (index === 0) {
option.selected = true;
width.value = w;
height.value = h;
pattern.value = w * h > 512 ? 3 : 1;
}
selectSegments.add(option);
});
} catch (error) {
toast(error, "error");
} finally {
hide();
}
}
const dropzone = document.getElementById("dropzone");
const source = document.getElementById("source");
dropzone.addEventListener("dragover", (e) => {
e.preventDefault();
});
dropzone.addEventListener("drop", (e) => {
e.preventDefault();
const label = document.getElementById("dropzoneLabel");
source.files = e.dataTransfer.files;
const { name } = source.files[0];
label.textContent = `Image ${name} selected!`;
validateForm(e);
});
dropzone.addEventListener("click", () => {
source.click();
});
source.addEventListener("change", (e) => {
const label = document.getElementById("dropzoneLabel");
const { name } = e.target.files[0];
label.textContent = `Image ${name} selected!`;
validateForm(e);
});
document
.getElementById("btnSimulatePreset")
.addEventListener("click", async () => {
const url = `${wledUrl}/json/state`;
const options = {
method: "POST",
body: JSON.stringify(jsonSendWLED),
};
show();
try {
const response = await fetch(url, options);
const { success } = await response.json();
if (success) {
toast("Preset sent successfully!");
}
} catch (error) {
toast(error, "error");
} finally {
hide();
}
});
document
.getElementById("btnSavePreset")
.addEventListener("click", async () => {
const { value: name } = document.getElementById("name");
jsonSaveWLED.splice(0);
jsonSaveWLED.push(
Object.assign({}, jsonSendWLED, { n: name, o: false })
);
await insert(jsonSaveWLED);
});
document
.getElementById("btnSavePlaylist")
.addEventListener("click", async () => {
await insert(jsonSaveWLED, true);
});
document.querySelectorAll("#btnCopyToClipboard").forEach((button) => {
button.addEventListener("click", async () => {
const response = document.getElementById("response");
response.select();
try {
await navigator.clipboard.writeText(response.value);
toast("Text copied to clipboard");
} catch (error) {
try {
await document.execCommand("copy");
toast("Text copied to clipboard");
} catch (error) {
toast(error, "error");
}
}
});
});
document.querySelectorAll("#btnDownloadPreset").forEach((button) => {
button.addEventListener("click", () => {
const { value: response } = document.getElementById("response");
const { value: output } = document.getElementById("output");
const timestamp = new Date().getTime();
const filename = `WLED_${timestamp}`;
downloadFile(response, filename, output);
});
});
document.getElementById("segments").addEventListener("change", (e) => {
const width = document.getElementById("width");
const height = document.getElementById("height");
const { width: w, height: h } = e.target.selectedOptions[0].dataset;
width.value = w;
height.value = h;
});
document.getElementById("output").addEventListener("change", (e) => {
const output = document.getElementsByClassName("output");
const { value } = e.target.selectedOptions[0];
Array.from(output).forEach(function (element) {
if (value === "ha") {
element.style.display = "flex";
} else {
element.style.display = "none";
}
});
});
document.getElementById("images").addEventListener("change", (e) => {
const dropzone = document.getElementById("dropzone");
const { value } = e.target.selectedOptions[0];
if (value === "upload") {
const dropzoneLabel = document.getElementById("dropzoneLabel");
const source = document.getElementById("source");
dropzoneLabel.textContent =
"Drag and drop a file here or click to select a file";
source.value = "";
dropzone.style.display = "block";
} else {
dropzone.style.display = "none";
}
});
document
.getElementById("transparentImage")
.addEventListener("change", (e) => {
const transparentImage =
document.getElementsByClassName("transparentImage");
const { checked } = e.target;
Array.from(transparentImage).forEach(function (element) {
if (checked) {
element.style.display = "flex";
} else {
element.style.display = "none";
}
});
});
document.getElementById("resizeImage").addEventListener("change", (e) => {
const resizeImage = document.getElementsByClassName("resizeImage");
const pattern = document.getElementById("pattern");
const { checked } = e.target;
Array.from(resizeImage).forEach(function (element) {
if (checked) {
pattern.value = 3;
element.style.display = "flex";
} else {
pattern.value = 1;
element.style.display = "none";
}
});
});
document.getElementById("animation").addEventListener("change", (e) => {
const animation = document.getElementsByClassName("animation");
const pattern = document.getElementById("pattern");
const { checked } = e.target;
Array.from(animation).forEach(function (element) {
if (checked) {
toast(
'If you want all frames in the image, set it to "0"',
"warning",
5000
);
element.style.display = "flex";
pattern.value = 3;
} else {
element.style.display = "none";
pattern.value = 1;
}
});
});
document
.getElementById("btnGenerate")
.addEventListener("click", async (event) => {
const { checked: animation } = document.getElementById("animation");
const preview = document.getElementById("preview");
const isNotAnimation = document.getElementById("isNotAnimation");
const singleCanvas = document.getElementById("singleCanvas");
const isAnimation = document.getElementById("isAnimation");
const multipleCanvas = document.getElementById("multipleCanvas");
if (validateForm(event)) {
jsonSaveWLED.splice(0);
preview.style.display = "block";
if (animation) {
isAnimation.style.display = "block";
isNotAnimation.style.display = "none";
singleCanvas.innerHTML = "";
await generateAnimation();
} else {
isAnimation.style.display = "none";
isNotAnimation.style.display = "block";
multipleCanvas.innerHTML = "";
await generate();
}
}
});
function loadImage(src) {
return new Promise((resolve, reject) => {
const image = new Image();
image.addEventListener("load", function () {
resolve(image);
});
image.addEventListener("error", function () {
reject(new Error("Error loading image"));
});
image.src = src;
});
}
async function generate() {
if (checkMimeType()) {
const file = document.getElementById("source").files[0];
const { value: images } = document.getElementById("images");
const { value: output } = document.getElementById("output");
show();
try {
const response = document.getElementById("response");
const singleCanvas = document.getElementById("singleCanvas");
singleCanvas.innerHTML = "";
const urlImage =
images === "upload" ? URL.createObjectURL(file) : images;
const image = await loadImage(urlImage);
const { canvas, bri, id, i, length } = recreate(image);
await new Promise((resolve) => {
Object.assign(jsonSendWLED, {
on: true,
bri,
seg: {
id,
i,
},
});
resolve();
});
const jsonData = JSON.stringify(jsonSendWLED);
const dataResponse = formatOutput(output, jsonData);
response.value = dataResponse;
singleCanvas.appendChild(canvas);
} catch (error) {
toast(error, "error");
} finally {
hide();
}
}
}
async function generateAnimation() {
if (checkMimeType()) {
const file = document.getElementById("source").files[0];
const images = document.getElementById("images");
const preview = document.getElementById("preview");
const response = document.getElementById("response");
const { value: presetName } = document.getElementById("name");
const { value: amount } = document.getElementById("frames");
const { value: output } = document.getElementById("output");
const { value: duration } = document.getElementById("duration");
const { text: imageName, value: imageValue } =
images.selectedOptions[0];
show();
try {
const body = new FormData();
if (imageValue === "upload") {
body.append("image", file);
} else {
const responseImage = await fetch(imageValue);
const blob = await responseImage.blob();
const file = new File([blob], imageName, { type: blob.type });
body.append("image", file);
}
const responseFrames = await fetch(
`https://pixelmagictool.vercel.app/api/wled/frames?amount=${amount}`,
{
method: "POST",
body,
}
);
const { message, frames } = await responseFrames.json();
if (!responseFrames.ok) {
toast(message, "error");
return;
}
jsonSaveWLED = [];
const texteares = [];
const canvases = [];
const delay = duration * 1000;
const promises = frames.map(async (frame, index) => {
const image = await loadImage(frame);
const { canvas, bri, id, i } = recreate(image);
const jsonData = {
on: true,
bri,
seg: { id, i },
};
const n = `${presetName} ${index + 1}`;
texteares.push(`${n}|${JSON.stringify(jsonData)}`);
canvases.push(canvas);
jsonSaveWLED.push(Object.assign(jsonData, { n, o: true }));
});
await Promise.all(promises);
const dataResponse = texteares.map((item) => {
const [presetName, json] = item.split("|");
const outputFormatted = formatOutput(output, json);
const comment = ["ha", "curl"].includes(output) ? "#" : "//";
return `${comment} ${presetName}\n${outputFormatted}`;
});
response.value = dataResponse.join("\n");
toast(message);
carousel("multipleCanvas", canvases, delay);
} catch (error) {
toast(error, "error");
} finally {
hide();
}
}
}
function recreate(image) {
const { value: pattern } = document.getElementById("pattern");
const { value: segmentId } = document.getElementById("segments");
const { value: bri } = document.getElementById("brightness");
const { value: width } = document.getElementById("width");
const { value: height } = document.getElementById("height");
const { checked: resizeImage } = document.getElementById("resizeImage");
const pixelsRef = 48;
const fullWidth = width * pixelsRef;
const fullHeight = height * pixelsRef;
const fontSize = fullWidth <= 768 ? 14 : 18;
const length = width * height;
const colors = [];
let i = [];
const { ctx: reference } = createCanvas(width, height);
reference.drawImage(image, 0, 0, width, height);
const imageData = reference.getImageData(0, 0, width, height);
const pixels = imageData.data;
const { canvas, ctx } = createCanvas(fullWidth, fullHeight);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const index = y * width + x;
const red = pixels[index * 4];
const green = pixels[index * 4 + 1];
const blue = pixels[index * 4 + 2];
const alpha = pixels[index * 4 + 3];
const hex = pixelColor(red, green, blue, alpha);
const { r, g, b } = hexToRgb(hex);
colors.push(hex);
let coordinateX = x * pixelsRef;
let coordinateY = y * pixelsRef;
ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;
ctx.fillRect(coordinateX, coordinateY, pixelsRef, pixelsRef);
ctx.lineWidth = 1;
ctx.strokeStyle = "#ffffff";
ctx.strokeRect(coordinateX, coordinateY, pixelsRef, pixelsRef);
let offsetX = coordinateX + pixelsRef / 2;
let offsetY = coordinateY + pixelsRef / 2;
ctx.font = `${fontSize}px Arial`;
ctx.fillStyle = hex == "ffffff" ? "#252525" : "#ffffff";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(index + 1, offsetX, offsetY);
}
}
switch (pattern) {
case "1":
i = colors;
break;
case "2":
i = individualLedIndex(colors);
break;
case "3":
i = rangeLeds(colors);
break;
}
return {
canvas,
bri,
id: segmentId,
i,
length,
};
}
function rangeLeds(colors) {
let startIndex = 0;
let endIndex = 0;
let currentColor = colors[0];
let pattern = [];
colors.forEach((color, index) => {
if (color !== currentColor) {
endIndex = index;
const repetitions = endIndex - startIndex;
if (repetitions == 1) {
pattern.push(currentColor);
} else {
pattern.push(startIndex, endIndex, currentColor);
}
startIndex = index;
}
currentColor = color;
});
const lastRepetition = colors.length - startIndex;
if (lastRepetition === 1) {
pattern.push(currentColor);
} else {
pattern.push(startIndex, colors.length, currentColor);
}
return pattern;
}
function pixelColor(r, g, b, a) {
const { checked } = document.getElementById("transparentImage");
const { value } = document.getElementById("color");
if (a === 0) {
if (checked) {
return value.replace("#", "").toLowerCase();
}
return rgbToHex(255, 255, 255);
}
return rgbToHex(r, g, b);
}
function hexToRgb(hex) {
hex = hex.replace("#", "");
if (hex.length === 3) {
hex = hex.replace(/(.)/g, "$1$1");
}
const [r, g, b] = hex
.match(/.{2}/g)
.map((component) => parseInt(component, 16));
return { r, g, b };
}
function rgbToHex(r, g, b) {
const hex = ((r << 16) | (g << 8) | b).toString(16);
return ("000000" + hex).slice(-6);
}
function individualLedIndex(colors) {
const pattern = [];
colors.forEach((led, index) => {
pattern.push(index, led);
});
return pattern;
}
function createCanvas(width, height) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d", { willReadFrequently: true });
ctx.imageSmoothingQuality = "high";
ctx.imageSmoothingEnabled = false;
return { canvas, ctx };
}
function formatOutput(output, json) {
return output === "ha"
? homeAssistant(json)
: output === "curl"
? curl(json)
: json;
}
function downloadFile(text, filename, output) {
let mimeType;
let fileExtension;
let response;
switch (output) {
case "json":
mimeType = "application/json";
fileExtension = "json";
break;
case "ha":
mimeType = "application/x-yaml";
fileExtension = "yaml";
break;
case "curl":
mimeType = "text/plain";
fileExtension = "txt";
break;
}
const blob = new Blob([text], { type: mimeType });
const url = URL.createObjectURL(blob);
const anchorElement = document.createElement("a");
anchorElement.href = url;
anchorElement.download = `${filename}.${fileExtension}`;
anchorElement.click();
URL.revokeObjectURL(url);
}
function homeAssistant(jsonData) {
const { value: device } = document.getElementById("device");
const { value: friendly_name } = document.getElementById("friendlyName");
const { value: unique_id } = document.getElementById("uniqueId");
const { value: hostname } = document.getElementById("hostname");
if (device) {
const yamlData = {
switches: {
[device]: {
friendly_name,
unique_id,
command_on: `curl -X POST "http://${hostname}/json/state" -d '${jsonData}' -H "Content-Type: application/json"`,
command_off: `curl -X POST "http://${hostname}/json/state" -d '{"on":false}' -H "Content-Type: application/json"`,
},
},
};
return convertToYaml(yamlData);
}
}
function curl(jsonData) {
const { value: hostname } = document.getElementById("hostname");
return `curl -X POST "http://${hostname}/json/state" -d '${jsonData}' -H "Content-Type: application/json"`;
}
function convertToYaml(obj) {
function processValue(value, indentationLevel) {
if (typeof value === "object" && !Array.isArray(value)) {
return processObject(value, indentationLevel + 1);
} else {
return value;
}
}
function processObject(obj, indentationLevel = 0) {
const indent = " ".repeat(indentationLevel);
const lines = Object.entries(obj).map(([key, value]) => {
if (typeof value === "object" && !Array.isArray(value)) {
return `${indent}${key}:\n${processObject(
value,
indentationLevel + 1
)}`;
} else {
return `${indent}${key}: ${processValue(value, indentationLevel)}`;
}
});
return lines.join("\n");
}
return processObject(obj);
}
function toast(
message,
type = "success",
duration = 2000,
hideElement = "preview"
) {
const hide = document.getElementById(hideElement);
const toast = document.createElement("div");
const wait = 100;
toast.style.animation = "fadeIn";
toast.style.animationDuration = `${duration + wait}ms`;
toast.style.animationTimingFunction = "linear";
toast.classList.add("toast", type);
const body = document.createElement("span");
body.classList.add("toast-body");
body.textContent = message;
toast.appendChild(body);
const progress = document.createElement("div");
progress.classList.add("toast-progress");
progress.style.animation = "progress";
progress.style.animationDuration = `${duration + wait}ms`;
progress.style.animationDelay = "0s";
toast.appendChild(progress);
document.getElementById("toast-container").appendChild(toast);
setTimeout(() => {
toast.style.opacity = 0;
setTimeout(() => {
toast.remove();
}, wait);
}, duration);
if (type === "error") {
hide.style.display = "none";
}
}
function carousel(id, images, delay = 3000) {
let index = 0;
const carousel = document.createElement("div");
carousel.classList.add("carousel");
images.forEach((canvas, i) => {
if (i === index) {
carousel.appendChild(canvas);
} else {
canvas.style.display = "none";
carousel.appendChild(canvas);
}
});
const container = document.getElementById(id);
container.innerHTML = "";
container.appendChild(carousel);
function next() {
images[index].style.display = "none";
index++;
if (index >= images.length) {
index = 0;
}
images[index].style.display = "block";
loop();
}
function previous() {
images[index].style.display = "none";
index--;
if (index < 0) {
index = images.length - 1;
}
images[index].style.display = "block";
loop();
}
let timeoutId;
function loop() {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
next();
if (index === 0) {
carousel.scrollTo(0, 0);
}
}, delay);
}
loop();
carousel.addEventListener("mouseover", () => {
clearTimeout(timeoutId);
});
carousel.addEventListener("mouseout", () => {
loop();
});
}
function show() {
const overlay = document.getElementById("overlay");
overlay.classList.add("loading");
overlay.style.display = "block";
overlay.style.cursor = "not-allowed";
document.body.style.overflow = "hidden";
}
function hide() {
const overlay = document.getElementById("overlay");
overlay.classList.remove("loading");
overlay.style.display = "none";
overlay.style.cursor = "default";
document.body.style.overflow = "auto";
}
function validateForm(event) {
event.preventDefault();
const form = document.getElementById("formGenerate");
const inputs = form.querySelectorAll("input, select, textarea");
let isValid = true;
const browserLanguage = navigator.language || navigator.userLanguage;
inputs.forEach((input) => {
const parent = input.closest(".valitade");
if (!parent) {
return;
}
let isVisible = true;
let tempParent = parent;
while (tempParent !== document.body) {
const parentStyles = window.getComputedStyle(tempParent);
if (
parentStyles.display === "none" ||
parentStyles.display === "hidden"
) {
isVisible = false;
break;
}
tempParent = tempParent.parentNode;
}
if (
isVisible &&
(!input.checkValidity() ||
(input.type === "file" && input.files.length === 0))
) {
input.classList.add("invalid");
const errorMessage =
input.dataset.errorMessage ||
input.validationMessage ||
getRequiredFieldMessage(browserLanguage);
let errorElement = parent.querySelector(".error-message");
if (!errorElement) {
errorElement = document.createElement("div");
errorElement.classList.add("error-message");
parent.appendChild(errorElement);
}
errorElement.innerText = errorMessage;
isValid = false;
} else {
input.classList.remove("invalid");
const errorElement = parent.querySelector(".error-message");
if (errorElement) {
parent.removeChild(errorElement);
}
}
});
return isValid;
}
function getRequiredFieldMessage(language) {
if (language.includes("-")) {
language = language.split("-")[1];
}
const messages = {
en: "This field is required.",
br: "Este campo é obrigatório.",
pt: "Este campo é obrigatório.",
es: "¡Este campo es obligatorio.",
fr: "Ce champ est obligatoire.",
de: "Dieses Feld ist erforderlich.",
it: "Questo campo è obbligatorio.",
};
return messages[language.toLowerCase()] || messages.en;
}
function checkMimeType() {
const { checked: animation } = document.getElementById("animation");
const mimeTypes = animation ? ["gif"] : ["jpeg", "jpg", "png", "gif"];
const source = document.getElementById("source").files[0];
const images = document.getElementById("images");
const { value: image } = images.selectedOptions[0];
const extension =
image === "upload"
? source.name.split(".").pop()
: image.split(".").pop();
if (!mimeTypes.includes(extension)) {
toast(
animation
? "Image format is not valid, select a GIF!"
: "Image format is not valid",
"error"
);
return false;
}
return true;
}
</script>
</html>