-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
217 lines (185 loc) · 7 KB
/
script.js
File metadata and controls
217 lines (185 loc) · 7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
const retrieveBtn = document.getElementById("retrieveBtn");
const binIdInput = document.getElementById("binIdInput");
const resultSection = document.getElementById("resultSection");
const infoMessage = document.getElementById("infoMessage");
const visualContainer = document.getElementById("visualContainer");
const downloadBtn = document.getElementById("downloadBtn");
const JSONBIN_BASE_URL = "https://api.jsonbin.io/v3/b/";
window.structuredData = null; // Will hold the object { colorSequence, propsColors, firstColor, lastColor... }
/**************************************************
* 1) When you click “Retrieve”
**************************************************/
retrieveBtn.addEventListener("click", async () => {
visualContainer.innerHTML = "";
infoMessage.textContent = "Loading...";
resultSection.classList.remove("hidden");
downloadBtn.classList.add("hidden");
window.structuredData = null;
const binId = binIdInput.value.trim();
if(!binId) {
infoMessage.textContent = "Please, enter a Gradient ID.";
return;
}
try {
const url = `${JSONBIN_BASE_URL}${encodeURIComponent(binId)}`;
const resp = await fetch(url);
if(!resp.ok) {
infoMessage.textContent = `Error: ID not found or server down. (status ${resp.status})`;
return;
}
const fullJson = await resp.json(); // { record: {...}, metadata: {...} }
infoMessage.textContent = "Gradient successfully retrieved.";
downloadBtn.classList.remove("hidden");
if(!fullJson.record) {
visualContainer.innerHTML = "";
infoMessage.textContent = "No 'record' field detected.";
return;
}
let gradientData = fullJson.record.gradientData;
if(!gradientData) {
infoMessage.textContent = "No 'gradientData' in the record.";
return;
}
// Convert to a single structure => window.structuredData
const isXml = gradientData.trim().startsWith("<root>");
let dataObj = null;
if(isXml) {
infoMessage.textContent = "Detected format: XML → converting to structured JSON.";
dataObj = parseXmlToObject(gradientData);
} else {
infoMessage.textContent = "Detected format: JSON → direct parsing.";
dataObj = parseJsonToObject(gradientData);
}
if(!dataObj) {
infoMessage.textContent = "Unable to parse/convert into JSON structure.";
return;
}
// Store the final object
window.structuredData = dataObj;
// Display the gradient on the page
visualizeGradient(dataObj, isXml ? "Gradient (XML→JSON)" : "Gradient (JSON)");
} catch(err) {
infoMessage.textContent = "Network/fetch error: " + err;
}
});
/**************************************************
* 2) “Download structured JSON” button
**************************************************/
downloadBtn.addEventListener("click", () => {
if(!window.structuredData) {
alert("No structured data available ! ");
return;
}
// Serialize to JSON
const dataStr = JSON.stringify(window.structuredData, null, 2);
const blob = new Blob([dataStr], { type: "application/json" });
const blobUrl = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = blobUrl;
link.download = `gradient_${Date.now()}.json`;
document.body.appendChild(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(blobUrl), 500);
});
/**************************************************
* parseXmlToObject(xmlString)
* => we parse the XML, rebuild an object
* { colorSequence: [ {time, color}, ... ],
* propsColors: [ {name, color}, ...],
* firstColor: "...",
* lastColor: "..." }
**************************************************/
function parseXmlToObject(xmlString) {
const parser = new DOMParser();
const dom = parser.parseFromString(xmlString, "application/xml");
const errNode = dom.querySelector("parsererror");
if(errNode) {
console.warn("Error parsing XML:", errNode.textContent);
return null;
}
const colorSeqNodes = [...dom.querySelectorAll("colorSequence > keypoint")];
const propsNodes = [...dom.querySelectorAll("propsColors > prop")];
const firstC = dom.querySelector("firstColor")?.textContent?.trim() || null;
const lastC = dom.querySelector("lastColor")?.textContent?.trim() || null;
// colorSequence
let colorSequence = colorSeqNodes.map(kp => {
let t = parseFloat(kp.getAttribute("time")) || 0;
let c = kp.getAttribute("color") || "#FFF";
return { time: t, color: c };
});
// propsColors
let propsColors = propsNodes.map(pn => {
let nm = pn.getAttribute("name") || "??";
let col = pn.textContent.trim() || "#FFF";
return { name: nm, color: col };
});
colorSequence.sort((a,b) => a.time - b.time);
return {
colorSequence,
propsColors,
firstColor: firstC,
lastColor: lastC
};
}
/**************************************************
* parseJsonToObject(jsonString)
* => we parse the JSON. We expect
* { colorSequence, propsColors, firstColor, lastColor }
* => we normalize a bit
**************************************************/
function parseJsonToObject(jsonString) {
let obj;
try {
obj = JSON.parse(jsonString);
} catch(err) {
console.warn("Error parsing JSON:", err);
return null;
}
if(!obj.colorSequence) obj.colorSequence = [];
if(!obj.propsColors) obj.propsColors = [];
if(!obj.firstColor) obj.firstColor = null;
if(!obj.lastColor) obj.lastColor = null;
// Sort by time
obj.colorSequence.sort((a,b) => (a.time || 0) - (b.time || 0));
return obj;
}
/**************************************************
* visualizeGradient(dataObj, label)
* => dataObj = { colorSequence: [...], propsColors: [...], firstColor, lastColor }
* => we build a multi-stop linear-gradient
**************************************************/
function visualizeGradient(dataObj, label) {
const colorSeq = dataObj.colorSequence;
if(!colorSeq || colorSeq.length === 0) {
visualContainer.innerHTML = "No colorSequence to display.";
return;
}
const gradientStr = buildMultiStopGradient(colorSeq);
const box = document.createElement("div");
box.classList.add("gradient-box");
box.style.background = gradientStr;
const title = document.createElement("div");
title.classList.add("gradient-title");
title.textContent = label;
box.appendChild(title);
visualContainer.appendChild(box);
}
/**************************************************
* buildMultiStopGradient(kpArray)
* => "linear-gradient(to right, #FFF 0%, #CCC 50%, #000 100%)"
**************************************************/
function buildMultiStopGradient(kpArray) {
const stops = kpArray.map(kp => {
const pct = Math.round(kp.time * 100);
return `${kp.color} ${pct}%`;
});
return `linear-gradient(to right, ${stops.join(", ")})`;
}
// On cible le bouton du footer
const apiStatusBtn = document.getElementById("apiStatusBtn");
apiStatusBtn.addEventListener("click", () => {
// Redirige l’utilisateur vers la page de statut
// Ici on ouvre dans un nouvel onglet
window.open("https://status.jsonbin.io/", "_blank");
});