-
Notifications
You must be signed in to change notification settings - Fork 2
/
background.js
330 lines (279 loc) · 11 KB
/
background.js
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
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
"use strict";
function executeScriptBasedOnModals() {
var exportData = false;
var exportTab = "";
if (
document.querySelector('[class*="dsa_file_view_modal--container--"]') ||
document.querySelector('[class*="org_view_modal--container--"]')
) {
console.log("------");
console.log("✅ Library Analytics: Open");
var exportData = true;
if (document.querySelector('[class*="org_view_modal--container--"]')) {
console.log("Modal: Org wrapper");
var modalTypeOrg = true;
} else {
console.log("Modal: DSA wrapper");
var modalTypeOrg = false;
}
if (
document.querySelector('[class*="dsa_file_view_overview--fileViewDSA--"]')
) {
console.log("❌ Visible: Overview");
alert("ℹ️ Switch to the Analytics tab to export data.");
} else if (
modalTypeOrg && document.querySelector(
'[class*="overview_stats_view--componentDescriptionAndImage--"]'
)) {
console.log("✅ Visible: Org Component detail");
var exportTab = "Component Detail";
}
else if (
document.querySelector('[class*="dsa_file_view_v2--slidingPaneLeft--"]'))
{
console.log("✅ Visible: Component detail");
var exportTab = "Component Detail";
} else if (
modalTypeOrg && document.querySelector(
'[class*="dsa_library_view--slidingPaneContainer--"]'
)) {
console.log("✅ Visible: All org components");
var exportTab = "Component List";
} else if (
document.querySelector(
'[class*="dsa_file_view_v2--slidingPaneContainer--"]'
)
) {
console.log("✅ Visible: All components");
var exportTab = "Component List";
} else {
console.log("❌ Can't determine current tab");
}
} else {
alert("Library Analytics modal is not visible.");
console.log("❌ Library Analytics: Closed");
}
if (exportData && exportTab == "Component Detail") {
// Call the function for element1
// functionForElement1();
// alert("component page");
// Export Figma Component Analytics
console.log("Running: Component Detail export");
// Scrape content from the webpage
const containerDiv = document.querySelector(
'div[class*="library_item_stats--statsTable--"]'
);
const rows = Array.from(
containerDiv.querySelectorAll('div[class*="library_item_stats--row--"]')
);
// Extract table headings
const headerRow = containerDiv.querySelector(
'div[class*="library_item_stats--statsTableHeaderRow--"]'
);
const headings = Array.from(
headerRow.querySelectorAll('div[class^="entity--sortableField--"]')
).map((heading) => heading.textContent.trim());
// Extract data from each row
const data = rows.map((row) => {
const avatarColumn = row.querySelector(
'div[class*="library_item_stats--avatarColumnComponentName--"]'
);
const componentName = avatarColumn.textContent.trim();
const statsColumns = Array.from(
row.querySelectorAll('div[class*="library_item_stats--statsColVal--"]')
).map((column) => column.textContent.trim());
return [componentName, ...statsColumns];
});
// Get current date
const currentDate = new Date().toISOString().split("T")[0];
// Get the text from the div with the partial classname
let headerElement = "Undefined";
let text = ""; // Declare text outside the if block
if (modalTypeOrg) {
console.log("✅ Org view header");
// Select the span element that contains the text
let element = document.querySelector('span[class*="end_truncated_text--truncatedText--"]');
if (element) {
text = element.textContent; // Now text is accessible outside this block
console.log(text);
// Check if the text contains " • Default library for all files"
if (text.includes(" • Default library for all files")) {
// Remove the unwanted part
text = text.replace(" • Default library for all files", "");
}
} else {
console.error("Element not found");
}
// Set headerElement to the cleaned text
headerElement = text;
} else {
console.log("✅ DSA File view header");
let element = document.querySelector('div[class*="header_modal--headerModalTitle--"]');
headerElement = element ? element.textContent.trim() : "Undefined";
}
const headerTitle = headerElement ? headerElement : "Undefined";
// Get the component title
const componentTitle = document
.querySelector('div[class*="asset_file_view_header--name--"]')
.textContent.trim();
// Extract additional content
const description = document
.querySelector(
'div[class*="overview_stats_view--componentDescription--"]'
)
.textContent.trim();
const total = document
.querySelector('div[class*="overview_stats_view--stat--"]')
.textContent.trim();
const usedBy = document
.querySelectorAll('div[class*="overview_stats_view--stat--"]')[1]
.textContent.trim();
const usedIn = document
.querySelectorAll('div[class*="overview_stats_view--stat--"]')[2]
.textContent.trim();
// Prepend additional content to data
const prependedData = [
["Library", headerTitle],
["Date", currentDate],
["Name", componentTitle],
["Description", description],
["Total", total],
["Used by", usedBy],
["Used in", usedIn],
[],
];
// Combine prependedData with existing data
const combinedData = [...prependedData, headings, ...data];
// Create CSV content
const csvComponentContent = `${combinedData
.map((row) =>
row.map((value) => `"${value.replace(/"/g, '""')}"`).join(",")
)
.join("\n")}`;
// Replace spaces and special characters with underscores
const cleanedHeaderTitle = headerTitle.replace(/[^a-zA-Z0-9]/g, "_");
const cleanedComponentTitle = componentTitle.replace(/[^a-zA-Z0-9]/g, "_");
// Generate the filename with today's date and the cleaned header title
const fileNameDetail = `Figma-Component-Analytics_-_${cleanedHeaderTitle}_-_${cleanedComponentTitle}_-_${currentDate}.csv`;
// Create a Blob object to download the CSV file
const blob = new Blob([csvComponentContent], {
type: "text/csv;charset=utf-8;",
});
// Create a temporary link element to initiate the download
const link = document.createElement("a");
if (link.download !== undefined) {
const url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", fileNameDetail);
link.style.visibility = "hidden";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
console.log("📄 Exporting: " + fileNameDetail + "");
}
} else if (exportData && exportTab == "Component List") {
// Export Figma Library Analytics
console.log("Running: Component List export");
// Scrape content from the webpage
const containerDiv = document.querySelector(
'div[class*="library_item_stats--statsTable--"]'
);
const rows = Array.from(
containerDiv.querySelectorAll('div[class*="library_item_stats--row--"]')
);
// Extract table headings
const headerRow = containerDiv.querySelector(
'div[class*="library_modal_stats--headerRow--"]'
);
const headings = Array.from(
headerRow.querySelectorAll('div[class^="entity--sortableField--"]')
).map((heading) => heading.textContent.trim());
// Extract data from each row
const data = rows.map((row) => {
const avatarColumn = row.querySelector(
'div[class*="library_item_stats--avatarColumnComponentName--"]'
);
const componentName = avatarColumn.textContent.trim();
const statsColumns = Array.from(
row.querySelectorAll('div[class*="library_item_stats--statsColVal--"]')
).map((column) => column.textContent.trim());
return [componentName, ...statsColumns];
});
// Get current date
const currentDate = new Date().toISOString().split("T")[0];
// Get the text from the div with the partial classname
let headerTitle;
if (modalTypeOrg) {
console.log("Org Modal");
// Select the span element that contains the text
let element = document.querySelector(
".end_truncated_text--truncatedText--lYsyo"
);
// Extract the text content
let text = element.innerText || element.textContent;
// Check if the text contains " • Default library for all files"
if (text.includes(" • Default library for all files")) {
// Remove the unwanted part
text = text.replace(" • Default library for all files", "");
}
// Log or use the cleaned text
headerTitle = text.trim();
} else {
console.log("File Modal");
headerTitle = document
.querySelector('div[class*="header_modal--headerModalTitle--"]').textContent.trim();
}
// Get the date range from the div with the partial classname
const headerDateRange = document
.querySelector('span[class*="dsa_file_view_tabs--duration--"]')
.textContent.trim();
// Prepend additional content to data
const prependedData = [
["Library", headerTitle],
["Date", currentDate],
["Date range", headerDateRange],
[],
];
// Combine prependedData with existing data
const combinedData = [...prependedData, headings, ...data];
// Create CSV content
const csvContent = `${combinedData
.map((row) =>
row.map((value) => `"${value.replace(/"/g, '""')}"`).join(",")
)
.join("\n")}`;
// Replace spaces and special characters with underscores
const cleanedHeaderTitle = headerTitle.replace(/[^a-zA-Z0-9]/g, "_");
const cleanedDateRange = headerDateRange.replace(/[^a-zA-Z0-9]/g, "_");
// Generate the filename with today's date and the cleaned header title
const fileName = `Figma-Analytics_-_${cleanedHeaderTitle}_-_${cleanedDateRange}_-_${currentDate}.csv`;
// Create a Blob object to download the CSV file
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
// Create a temporary link element to initiate the download
const link = document.createElement("a");
if (link.download !== undefined) {
const url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", fileName);
link.style.visibility = "hidden";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
console.log("📄 Exporting: " + fileName + "");
}
}
}
// Receive message from the extension popup to execute the script
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request === "executeScript") {
executeScriptBasedOnModals();
}
});
chrome.runtime.onInstalled.addListener((_reason) => {
chrome.tabs.create({
url: "page.html",
});
});