-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
241 lines (196 loc) · 6.86 KB
/
Copy pathscript.js
File metadata and controls
241 lines (196 loc) · 6.86 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
const contributorsGrid = document.getElementById("contributorsGrid");
const statusText = document.getElementById("status");
const jsonFileCount = document.getElementById("jsonFileCount");
const cardCount = document.getElementById("cardCount");
const DATA_DIR = "data";
const DEFAULT_JSON_FILES = ["john-doe.json", "karthik.json", "rahul.json"];
function normalizeJsonFileName(fileName) {
return String(fileName || "").trim().split("/").pop() || "";
}
function isJsonFile(fileName) {
return fileName.toLowerCase().endsWith(".json");
}
function getGitHubRepoContext() {
const host = window.location.hostname;
if (!host.endsWith(".github.io")) {
return null;
}
const owner = host.split(".")[0];
const pathParts = window.location.pathname.split("/").filter(Boolean);
const repo = pathParts.length > 0 ? pathParts[0] : `${owner}.github.io`;
if (!owner || !repo) {
return null;
}
return { owner, repo };
}
async function discoverJsonFilesFromGitHubApi() {
const repoContext = getGitHubRepoContext();
if (!repoContext) {
return [];
}
try {
const apiUrl = `https://api.github.com/repos/${repoContext.owner}/${repoContext.repo}/contents/${DATA_DIR}`;
const response = await fetch(apiUrl, { cache: "no-store" });
if (!response.ok) {
return [];
}
const entries = await response.json();
if (!Array.isArray(entries)) {
return [];
}
return entries
.filter((entry) => entry && entry.type === "file" && isJsonFile(entry.name))
.map((entry) => normalizeJsonFileName(entry.name));
} catch (error) {
return [];
}
}
function escapeHTML(value) {
return String(value)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
function buildCard(contributor) {
const card = document.createElement("article");
card.className = "card";
const fallbackPortfolio = `portfolios/${contributor.slug}.html`;
const portfolioPath = contributor.portfolio || fallbackPortfolio;
card.innerHTML = `
<h3>${escapeHTML(contributor.name)}</h3>
<p class="year">${escapeHTML(contributor.year)}</p>
<p class="intro">${escapeHTML(contributor.intro)}</p>
<a href="${escapeHTML(portfolioPath)}" aria-label="View ${escapeHTML(contributor.name)} portfolio">View Portfolio</a>
`;
return card;
}
function inferSlugFromFile(fileName) {
return fileName.replace(/\.json$/i, "");
}
function normalizePortfolioPath(rawPath, slug) {
const fallbackPath = `portfolios/${slug}.html`;
const value = String(rawPath || "").trim();
if (!value) {
return fallbackPath;
}
if (value.toLowerCase().startsWith("portfolios/") && value.toLowerCase().endsWith(".html")) {
return value;
}
if (value.toLowerCase().endsWith(".html")) {
return `portfolios/${value.split("/").pop()}`;
}
return fallbackPath;
}
async function discoverJsonFiles() {
const discovered = new Set();
try {
const directoryResponse = await fetch(`${DATA_DIR}/`, { cache: "no-store" });
if (directoryResponse.ok) {
const directoryHtml = await directoryResponse.text();
const matches = directoryHtml.matchAll(/href=["']([^"']+\.json)["']/gi);
for (const match of matches) {
const filePath = match[1].split("?")[0].split("#")[0];
const file = normalizeJsonFileName(filePath);
if (file && isJsonFile(file)) {
discovered.add(file);
}
}
}
} catch (error) {
// Some static hosts do not expose directory listings; fallback handles this.
}
if (discovered.size === 0) {
const apiDiscoveredFiles = await discoverJsonFilesFromGitHubApi();
apiDiscoveredFiles.forEach((file) => discovered.add(file));
}
if (discovered.size === 0) {
DEFAULT_JSON_FILES.forEach((file) => discovered.add(file));
}
return Array.from(discovered);
}
async function loadContributors() {
const files = await discoverJsonFiles();
const results = await Promise.allSettled(
files.map(async (file) => {
const response = await fetch(`${DATA_DIR}/${file}`, { cache: "no-store" });
if (!response.ok) {
throw new Error(`Unable to read ${file}`);
}
const data = await response.json();
return {
slug: inferSlugFromFile(file),
name: data.name || "Unknown Contributor",
year: data.year || "Year not provided",
intro: data.intro || "No intro added yet.",
portfolio: normalizePortfolioPath(data.portfolio, inferSlugFromFile(file)),
};
})
);
const validContributors = results
.filter((item) => item.status === "fulfilled")
.map((item) => item.value)
.filter((item) => item.name && item.slug)
.sort((a, b) => a.name.localeCompare(b.name));
return {
contributors: validContributors,
discoveredFileCount: files.length,
invalidFileCount: Math.max(files.length - validContributors.length, 0),
};
}
function animateReveals() {
const revealElements = document.querySelectorAll(".reveal, .card");
const observer = new IntersectionObserver(
(entries, obs) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add("visible");
obs.unobserve(entry.target);
}
});
},
{ threshold: 0.12 }
);
revealElements.forEach((element, index) => {
if (element.classList.contains("card")) {
element.style.transitionDelay = `${Math.min(index * 70, 340)}ms`;
}
observer.observe(element);
});
}
async function renderContributors() {
try {
const { contributors, discoveredFileCount, invalidFileCount } = await loadContributors();
contributorsGrid.innerHTML = "";
if (jsonFileCount) {
jsonFileCount.textContent = `JSON Files: ${discoveredFileCount}`;
}
if (cardCount) {
cardCount.textContent = `Cards Shown: ${contributors.length}`;
}
if (contributors.length === 0) {
statusText.textContent = "No contributors found yet. Add JSON files in the data folder.";
return;
}
const cards = contributors.map((contributor) => buildCard(contributor));
cards.forEach((card) => contributorsGrid.appendChild(card));
if (invalidFileCount > 0) {
statusText.textContent = `Showing ${contributors.length} contributor${contributors.length > 1 ? "s" : ""}. ${invalidFileCount} JSON file${invalidFileCount > 1 ? "s were" : " was"} skipped due to invalid data.`;
} else {
statusText.textContent = `Showing ${contributors.length} contributor${contributors.length > 1 ? "s" : ""}.`;
}
animateReveals();
} catch (error) {
statusText.textContent = "Unable to load contributors. Make sure you are running with a local server.";
contributorsGrid.innerHTML = "";
if (jsonFileCount) {
jsonFileCount.textContent = "JSON Files: 0";
}
if (cardCount) {
cardCount.textContent = "Cards Shown: 0";
}
}
}
animateReveals();
renderContributors();