-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
575 lines (507 loc) · 17.1 KB
/
script.js
File metadata and controls
575 lines (507 loc) · 17.1 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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
const byId = (id) => document.getElementById(id);
const fields = {
projectName: byId("projectName"),
tagline: byId("tagline"),
description: byId("description"),
repoUrl: byId("repoUrl"),
demoUrl: byId("demoUrl"),
version: byId("version"),
author: byId("author"),
features: byId("features"),
tech: byId("tech"),
install: byId("install"),
configuration: byId("configuration"),
structure: byId("structure"),
screenshots: byId("screenshots"),
license: byId("license"),
contribUrl: byId("contribUrl"),
support: byId("support"),
// FAQ handled separately
socialGithub: byId("socialGithub"),
socialCodepen: byId("socialCodepen"),
socialMedium: byId("socialMedium"),
socialTelegram: byId("socialTelegram"),
socialInstagram: byId("socialInstagram"),
socialPinterest: byId("socialPinterest"),
credits: byId("credits"),
acknowledgements: byId("acknowledgements"),
};
const previewPanel = byId("previewPanel");
const preview = byId("preview");
const previewCode = byId("previewCode");
const wordCount = byId("wordCount");
const charCount = byId("charCount");
const btnToggle = byId("btnToggle");
const btnPreview = byId("btnPreview");
const btnOpenPreview = byId("btnOpenPreview");
const autosaveStatus = byId("autosaveStatus");
const btnReset = byId("btnReset");
const techBadgeSelect = byId("techBadgeSelect");
const btnCopyMarkdownView = byId("btnCopyMarkdownView");
const faqList = byId("faqList");
const btnAddFaq = byId("btnAddFaq");
let autosaveTimer;
const sanitizeList = (raw) =>
raw
.split(",")
.map((item) => item.trim())
.filter(Boolean);
const sanitizeLines = (raw) =>
raw
.split("\n")
.map((line) => line.trim())
.filter(Boolean);
const titleCase = (value) =>
value
.split(" ")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(" ");
const toBullets = (lines) => lines.map((item) => `- ${item}`).join("\n");
const toParagraphs = (raw) =>
raw
.split("\n")
.map((line) => line.trim())
.filter(Boolean)
.join("\n\n");
const slugify = (value) =>
value
.toLowerCase()
.replace(/[^a-z0-9\s-]/g, "")
.trim()
.replace(/\s+/g, "-");
const parseRepoSlug = (repoUrl) => {
if (!repoUrl) return null;
try {
const url = new URL(repoUrl);
if (!url.hostname.includes("github.com")) return null;
const parts = url.pathname.split("/").filter(Boolean);
if (parts.length < 2) return null;
return `${parts[0]}/${parts[1].replace(/\.git$/, "")}`;
} catch (err) {
return null;
}
};
const buildBadges = (name, repoUrl, license) => {
if (!name) return "";
const slug = name.toLowerCase().replace(/\s+/g, "-");
const repoSlug = parseRepoSlug(repoUrl);
const badgeSet = [
``,
``,
];
if (repoSlug) {
badgeSet.push(
``,
``,
``,
``,
``
);
}
if (license) {
badgeSet.push(
`}-f97316?style=flat-square)`
);
}
return badgeSet.join(" ");
};
const buildGenericBadge = (label, url, color, logo) => {
if (!url) return "";
const safeLabel = label.replace(/\s+/g, "_");
const logoPart = logo ? `&logo=${logo}&logoColor=white` : "";
return `[](${url})`;
};
const buildSocialBadges = (links) => {
const entries = Object.entries(links).filter(([, url]) => url);
if (!entries.length) return "";
const map = {
GitHub: {
color: "181717",
logo: "github",
},
CodePen: {
color: "000000",
logo: "codepen",
},
Medium: {
color: "12100E",
logo: "medium",
},
Telegram: {
color: "2CA5E0",
logo: "telegram",
},
Instagram: {
color: "E4405F",
logo: "instagram",
},
Pinterest: {
color: "BD081C",
logo: "pinterest",
},
};
return entries
.map(([label, url]) => {
const meta = map[label] || { color: "64748b", logo: "" };
return `[](${url})`;
})
.join("\n");
};
const section = (title, body) => `${title}\n\n${body}\n`;
const getFieldValue = (node) => {
if (!node) return "";
return node.value.trim();
};
const buildTableOfContents = (titles) => {
if (!titles.length) return "";
return titles.map((title) => `- [${title}](#${slugify(title)})`).join("\n");
};
const buildMarkdown = () => {
const data = Object.fromEntries(
Object.entries(fields).map(([key, node]) => [key, getFieldValue(node)])
);
const features = sanitizeList(data.features);
const tech = sanitizeList(data.tech);
const screenshots = sanitizeLines(data.screenshots);
const faqs = getFaqItems();
const name = data.projectName || "README";
const tagline = data.tagline ? `> ${data.tagline}` : "";
let md = `# ${titleCase(name)}\n\n`;
const badges = buildBadges(name, data.repoUrl, data.license);
if ((data.repoUrl || data.license) && badges) {
const communityLine =
"Awesome GitHub Profile README · Awesome GitHub Profiles (Product Hunt) · Awesome Badge website · Join Community";
md += `<div align=\"center\">\n\n${communityLine}\n\n${badges}\n\n</div>\n\n---\n\n`;
}
if (tagline) {
md += `${tagline}\n\n`;
}
if (data.version) {
md += section("## Version", data.version);
}
const sectionTitles = [
...(data.description ? ["What It Is"] : []),
...(data.demoUrl ? ["Demo"] : []),
...(screenshots.length ? ["Screenshots"] : []),
...(features.length ? ["Features"] : []),
...(tech.length ? ["Tech Stack"] : []),
...(data.install ? ["Installation"] : []),
...(data.configuration ? ["Configuration"] : []),
...(data.structure ? ["Project Structure"] : []),
...(data.contribUrl ? ["Contributing"] : []),
...(data.support ? ["Support"] : []),
...(faqs.length ? ["FAQ"] : []),
...(data.socialGithub ||
data.socialCodepen ||
data.socialMedium ||
data.socialTelegram ||
data.socialInstagram ||
data.socialPinterest
? ["Connect With Me"]
: []),
...(data.repoUrl ? ["Repository"] : []),
...(data.author ? ["Author"] : []),
...(data.credits ? ["Author & Credits"] : []),
...(data.acknowledgements ? ["Acknowledgements"] : []),
...(data.license ? ["License"] : []),
];
if (sectionTitles.length > 3) {
const toc = buildTableOfContents(sectionTitles);
if (toc) {
md += section("## Table of Contents", toc);
md += "---\n\n";
}
}
if (data.description) {
md += section("## What It Is", data.description);
}
if (data.demoUrl) {
const demoBadge = buildGenericBadge("Live_Demo", data.demoUrl, "22c55e", "vercel");
md += section("## Demo", demoBadge || data.demoUrl);
}
if (screenshots.length) {
const shotLines = screenshots.map((url, idx) => ``).join("\n\n");
md += section("## Screenshots", shotLines);
}
if (features.length) {
md += section("## Features", features.map((item) => `- ${item}`).join("\n"));
}
if (tech.length) {
md += section("## Tech Stack", tech.map((item) => `- ${item}`).join("\n"));
}
if (data.install) {
md += section("## Installation", `\`\`\`\n${data.install}\n\`\`\``);
}
if (data.configuration) {
md += section("## Configuration", toParagraphs(data.configuration));
}
if (data.structure) {
md += section("## Project Structure", toParagraphs(data.structure));
}
if (data.contribUrl) {
const contribBadge = buildGenericBadge("Contributing", data.contribUrl, "f97316", "github");
const contribText = contribBadge || `See ${data.contribUrl} for contribution guidelines.`;
md += section("## Contributing", contribText);
}
if (data.support) {
md += section("## Support", toParagraphs(data.support));
}
if (faqs.length) {
const faqLines = faqs
.map((item) => `**Q: ${item.question}**\n\nA: ${item.answer}`)
.join("\n\n");
md += section("## FAQ", faqLines);
}
const socialBadges = buildSocialBadges({
GitHub: data.socialGithub,
CodePen: data.socialCodepen,
Medium: data.socialMedium,
Telegram: data.socialTelegram,
Instagram: data.socialInstagram,
Pinterest: data.socialPinterest,
});
if (socialBadges) {
md += `## 📫 Connect With Me\n\n<div align=\"center\">\n\n${socialBadges}\n\n</div>\n\n`;
}
if (data.repoUrl) {
const repoBadge = buildGenericBadge("Repository", data.repoUrl, "0ea5e9", "github");
md += section("## Repository", repoBadge || data.repoUrl);
}
if (data.author) {
md += section("## Author", data.author);
}
if (data.credits) {
md += section("## Author & Credits", toParagraphs(data.credits));
}
if (data.acknowledgements) {
md += section("## Acknowledgements", toParagraphs(data.acknowledgements));
}
if (data.license) {
md += section("## License", `Distributed under the ${data.license} License.`);
}
return md.trim() + "\n";
};
const renderMarkdown = (md) => {
if (window.marked) {
const raw = marked.parse(md, { mangle: false, headerIds: true });
return window.DOMPurify ? DOMPurify.sanitize(raw) : raw;
}
return md.replace(/\n/g, "<br>");
};
const addCopyButtonsToCode = (container) => {
if (!container) return;
const blocks = container.querySelectorAll("pre");
blocks.forEach((block) => {
if (block.querySelector(".copy-code-btn")) return;
const button = document.createElement("button");
button.type = "button";
button.className = "copy-code-btn";
button.textContent = "Copy";
button.addEventListener("click", async () => {
const code = block.querySelector("code");
const text = code ? code.textContent : block.textContent;
try {
await navigator.clipboard.writeText(text.trim());
button.textContent = "Copied";
setTimeout(() => {
button.textContent = "Copy";
}, 1500);
} catch (err) {
button.textContent = "Failed";
setTimeout(() => {
button.textContent = "Copy";
}, 1500);
}
});
block.appendChild(button);
});
};
const updatePreview = () => {
const md = buildMarkdown();
previewCode.textContent = md;
preview.innerHTML = renderMarkdown(md);
addCopyButtonsToCode(preview);
const words = md.trim().split(/\s+/).filter(Boolean);
wordCount.textContent = `${words.length} words`;
charCount.textContent = `${md.length} chars`;
scheduleAutosave();
};
const copyMarkdown = async () => {
const md = buildMarkdown();
try {
await navigator.clipboard.writeText(md);
if (btnCopyMarkdownView) btnCopyMarkdownView.textContent = "Copied";
setTimeout(() => {
if (btnCopyMarkdownView) btnCopyMarkdownView.textContent = "Copy Markdown";
}, 1600);
} catch (err) {
alert("Copy failed. Try selecting the preview text and copying manually.");
}
};
const clearTechBadges = () => {
if (!techBadgeSelect) return;
Array.from(techBadgeSelect.querySelectorAll(".badge-option")).forEach((btn) =>
btn.classList.remove("is-active")
);
fields.tech.value = "";
};
const getFaqItems = () => {
if (!faqList) return [];
return Array.from(faqList.querySelectorAll(".faq-item"))
.map((item) => {
const question = item.querySelector(".faq-question")?.value.trim() || "";
const answer = item.querySelector(".faq-answer")?.value.trim() || "";
return { question, answer };
})
.filter((item) => item.question || item.answer);
};
const addFaqItem = () => {
if (!faqList) return;
const wrapper = document.createElement("div");
wrapper.className = "faq-item";
wrapper.innerHTML = `
<input class="faq-question" type="text" placeholder="Question" />
<textarea class="faq-answer" rows="2" placeholder="Answer"></textarea>
`;
faqList.appendChild(wrapper);
const inputs = wrapper.querySelectorAll("input, textarea");
inputs.forEach((node) => {
node.addEventListener("input", updatePreview);
node.addEventListener("change", updatePreview);
});
};
const setTechBadges = (stack) => {
if (!techBadgeSelect) return;
const normalized = stack.map((item) => item.toLowerCase());
const selected = [];
const buttons = Array.from(techBadgeSelect.querySelectorAll(".badge-option"));
const existingValues = buttons.map((btn) => (btn.dataset.value || btn.textContent).trim().toLowerCase());
stack.forEach((item) => {
if (!existingValues.includes(item.toLowerCase())) {
const newBtn = document.createElement("button");
newBtn.type = "button";
newBtn.className = "badge-option";
newBtn.dataset.value = item;
newBtn.textContent = item;
techBadgeSelect.appendChild(newBtn);
}
});
Array.from(techBadgeSelect.querySelectorAll(".badge-option")).forEach((btn) => {
const value = (btn.dataset.value || btn.textContent).trim();
const match = normalized.includes(value.toLowerCase());
if (match) {
btn.classList.add("is-active");
selected.push(value);
} else {
btn.classList.remove("is-active");
}
});
fields.tech.value = selected.join(", ");
};
const toggleTechBadge = (event) => {
const target = event.target.closest(".badge-option");
if (!target) return;
target.classList.toggle("is-active");
const selected = Array.from(techBadgeSelect.querySelectorAll(".badge-option.is-active")).map(
(btn) => btn.dataset.value || btn.textContent
);
fields.tech.value = selected.join(", ");
updatePreview();
};
const resetForm = () => {
Object.values(fields).forEach((node) => {
node.value = "";
});
clearTechBadges();
if (faqList) {
faqList.innerHTML = `
<div class="faq-item">
<input class="faq-question" type="text" placeholder="Question" />
<textarea class="faq-answer" rows="2" placeholder="Answer"></textarea>
</div>
`;
}
localStorage.removeItem("readmeStudioDraft");
updatePreview();
};
const toggleView = () => {
if (previewPanel.classList.contains("is-collapsed")) {
return;
}
const showingCode = !previewCode.parentElement.classList.contains("is-hidden");
if (showingCode) {
previewCode.parentElement.classList.add("is-hidden");
preview.classList.remove("is-hidden");
previewPanel.classList.remove("markdown-only");
btnToggle.textContent = "Show Markdown";
} else {
preview.classList.add("is-hidden");
previewCode.parentElement.classList.remove("is-hidden");
previewPanel.classList.add("markdown-only");
btnToggle.textContent = "Show Preview";
}
};
const setPreviewState = (open) => {
if (open) {
previewPanel.classList.remove("is-collapsed");
document.body.classList.add("preview-fullscreen");
btnPreview.textContent = "Exit Fullscreen";
btnToggle.disabled = false;
previewCode.parentElement.classList.add("is-hidden");
preview.classList.remove("is-hidden");
previewPanel.classList.remove("markdown-only");
btnToggle.textContent = "Show Markdown";
} else {
previewPanel.classList.add("is-collapsed");
document.body.classList.remove("preview-fullscreen");
btnPreview.textContent = "Exit Fullscreen";
btnToggle.disabled = true;
}
};
const togglePreview = () => {
const isOpen = !previewPanel.classList.contains("is-collapsed");
setPreviewState(!isOpen);
};
const openPreview = () => setPreviewState(true);
const scheduleAutosave = () => {
clearTimeout(autosaveTimer);
autosaveTimer = setTimeout(() => {
const data = Object.fromEntries(
Object.entries(fields).map(([key, node]) => [key, getFieldValue(node)])
);
const draft = { data, tech: fields.tech.value };
localStorage.setItem("readmeStudioDraft", JSON.stringify(draft));
if (autosaveStatus) autosaveStatus.textContent = "Saved";
}, 400);
};
const init = () => {
Object.values(fields).forEach((node) => {
node.addEventListener("input", updatePreview);
node.addEventListener("change", updatePreview);
});
btnCopyMarkdownView?.addEventListener("click", copyMarkdown);
btnReset?.addEventListener("click", resetForm);
btnToggle?.addEventListener("click", toggleView);
btnPreview?.addEventListener("click", togglePreview);
btnOpenPreview?.addEventListener("click", openPreview);
if (techBadgeSelect) {
techBadgeSelect.addEventListener("click", toggleTechBadge);
}
if (btnAddFaq) {
btnAddFaq.addEventListener("click", () => {
addFaqItem();
});
}
if (faqList) {
faqList.querySelectorAll("input, textarea").forEach((node) => {
node.addEventListener("input", updatePreview);
node.addEventListener("change", updatePreview);
});
}
updatePreview();
};
if (document.readyState === "loading") {
window.addEventListener("DOMContentLoaded", init);
} else {
init();
}