sf-i-events
Version:
Superflows Navigation Component
572 lines • 20.4 kB
JavaScript
import * as XLSX from 'xlsx';
const validateName = (name) => {
if ((name + "").length > 2) {
return true;
}
return false;
};
function createDiagonalPattern1(color) {
// create a 10x10 px canvas for the pattern's base shape
let shape = document.createElement('canvas');
shape.width = 10;
shape.height = 10;
// get the context for drawing
let c = shape.getContext('2d');
// draw 1st line of the shape
c.strokeStyle = color;
c.lineWidth = 3;
c.beginPath();
c.moveTo(2, 0);
c.lineTo(10, 8);
c.stroke();
// draw 2nd line of the shape
c.beginPath();
c.moveTo(2, 10);
c.lineTo(0, 8);
c.stroke();
// create the pattern from the shape
return c.createPattern(shape, 'repeat');
}
// function createDiagonalPattern2(color: string) {
// let shape = document.createElement('canvas')
// shape.width = 10
// shape.height = 10
// // get the context for drawing
// let c = shape.getContext('2d')
// // draw 1st line of the shape
// c!.beginPath();
// c!.rect(2, 2, 8, 8)
// c!.fillStyle = color;
// c!.fill();
// // create the pattern from the shape
// return c!.createPattern(shape, 'repeat')
// }
function createDiagonalPattern2(color) {
// create a 10x10 px canvas for the pattern's base shape
let shape = document.createElement('canvas');
shape.width = 10;
shape.height = 10;
// get the context for drawing
let c = shape.getContext('2d');
// draw 1st line of the shape
c.beginPath();
c.rect(1, 1, 9, 9);
c.fillStyle = color;
c.fill();
c.lineWidth = 1;
c.strokeStyle = color;
c.stroke();
// create the pattern from the shape
// create tick
//draw tick
c.beginPath();
c.moveTo(2, 2);
c.lineTo(8, 8);
c.moveTo(2, 8);
c.lineTo(8, 2);
c.lineWidth = 2;
c.strokeStyle = '#fff';
c.stroke();
return c.createPattern(shape, 'repeat');
}
function createDiagonalPattern3(color) {
// create a 10x10 px canvas for the pattern's base shape
let shape = document.createElement('canvas');
shape.width = 10;
shape.height = 10;
// get the context for drawing
let c = shape.getContext('2d');
// draw 1st line of the shape
c.beginPath();
c.rect(1, 1, 9, 9);
c.fillStyle = color;
c.fill();
c.lineWidth = 1;
c.strokeStyle = color;
c.stroke();
// create the pattern from the shape
// create tick
//draw tick
c.beginPath();
c.moveTo(2, 5);
c.lineTo(4, 7);
c.lineTo(8, 2);
c.lineWidth = 2;
c.strokeStyle = '#fff';
c.stroke();
return c.createPattern(shape, 'repeat');
}
// function createDiagonalPattern3(color: string) {
// // create a 10x10 px canvas for the pattern's base shape
// let shape = document.createElement('canvas')
// shape.width = 14
// shape.height = 14
// // get the context for drawing
// let c = shape.getContext('2d')
// // draw 1st line of the shape
// c!.beginPath();
// c!.arc(7, 7, 6, 0, 2 * Math.PI, false);
// c!.fillStyle = color;
// c!.fill();
// c!.lineWidth = 1;
// c!.strokeStyle = color;
// c!.stroke();
// // create the pattern from the shape
// // create tick
// //draw tick
// c!.beginPath();
// c!.moveTo(4,6);
// c!.lineTo(6,9);
// c!.lineTo(10,4);
// c!.lineWidth = 2;
// c!.strokeStyle = '#fff';
// c!.stroke();
// return c!.createPattern(shape, 'repeat')
// }
// function createDiagonalPattern3(color: string) {
// // create a 10x10 px canvas for the pattern's base shape
// let shape = document.createElement('canvas')
// shape.width = 10
// shape.height = 10
// // get the context for drawing
// let c = shape.getContext('2d')
// // draw 1st line of the shape
// c!.beginPath();
// c!.arc(5, 5, 4, 0, 2 * Math.PI, false);
// c!.fillStyle = color;
// c!.fill();
// c!.lineWidth = 1;
// c!.strokeStyle = color;
// c!.stroke();
// // create the pattern from the shape
// return c!.createPattern(shape, 'repeat')
// }
const timeSince = (date) => {
var seconds = Math.floor((new Date().getTime() - date) / 1000);
if (seconds > 0) {
var interval = seconds / 31536000;
if (interval > 1) {
return Math.floor(interval) + " years ago";
}
interval = seconds / 2592000;
if (interval > 1) {
return Math.floor(interval) + " months ago";
}
interval = seconds / 86400;
if (interval > 1) {
return Math.floor(interval) + " days ago";
}
interval = seconds / 3600;
if (interval > 1) {
return Math.floor(interval) + " hours ago";
}
interval = seconds / 60;
if (interval > 1) {
return Math.floor(interval) + " minutes ago";
}
return Math.floor(seconds) + " seconds ago";
}
else {
var interval = Math.abs(seconds) / 31536000;
console.log('timesince', seconds);
console.log('interval year', interval);
if (interval > 1) {
return Math.floor(interval) + " years later";
}
interval = Math.abs(seconds) / 2592000;
console.log('interval months', interval);
if (interval > 1) {
return Math.floor(interval) + " months later";
}
interval = Math.abs(seconds) / 86400;
console.log('interval days', interval);
if (interval > 1) {
return Math.floor(interval) + " days later";
}
interval = Math.abs(seconds) / 3600;
console.log('interval hours', interval);
if (interval > 1) {
return Math.floor(interval) + " hours later";
}
interval = Math.abs(seconds) / 60;
if (interval > 1) {
return Math.floor(interval) + " minutes later";
}
return Math.floor(Math.abs(seconds)) + " seconds";
}
};
function readCookie(key) {
let name = key + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
async function callApi(url, data, authorization) {
return new Promise((resolve) => {
const jsonData = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", () => {
if (xhr != null) {
if (xhr.readyState === 4) {
resolve(xhr);
}
}
});
xhr.open("POST", url);
xhr.timeout = 1800000;
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
if (authorization != null) {
xhr.setRequestHeader('Authorization', 'Basic ' + authorization);
}
xhr.send(jsonData);
return xhr;
});
}
async function callApiPresignedDelete(url) {
return new Promise((resolve) => {
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", () => {
if (xhr != null) {
if (xhr.readyState === 4) {
resolve(xhr);
}
}
});
xhr.open("DELETE", url);
xhr.timeout = 1800000;
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send(null);
return xhr;
});
}
async function callApiPresignedGet(url) {
return new Promise((resolve) => {
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", () => {
if (xhr != null) {
if (xhr.readyState === 4) {
resolve(xhr);
}
}
});
xhr.open("GET", url);
xhr.timeout = 1800000;
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send(null);
return xhr;
});
}
async function callApiPresigned(url, data) {
return new Promise((resolve) => {
const jsonData = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", () => {
if (xhr != null) {
if (xhr.readyState === 4) {
resolve(xhr);
}
}
});
xhr.open("PUT", url);
xhr.timeout = 1800000;
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send(jsonData);
return xhr;
});
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function isInteger(value) {
return /^-?\d+$/.test(value);
}
function clearListeners(old_element) {
var _a;
var new_element = old_element.cloneNode(true);
(_a = old_element.parentNode) === null || _a === void 0 ? void 0 : _a.replaceChild(new_element, old_element);
return new_element;
}
function jsonObjectToHtml(json) {
var html = '';
for (var i = 0; i < Object.keys(json).length; i++) {
var key = Object.keys(json)[i];
html += '<div>';
html += ('<span style="margin-left: 0px; padding-left: 0px">' + key + ':</span> ');
html += ('<span class="td-body" part="td-head"><sf-i-elastic-text text="' + json[key].replace(/"/g, '') + '" lineSize="6" minLength="10"></sf-i-elastic-text></span>');
html += '</div>';
}
return html;
}
function convertToCSV(arr) {
const array = [Object.keys(arr[0])].concat(arr);
let fieldsArr = Object.keys(arr[0]);
return array.map((it, index) => {
var _a;
let strIt = "";
for (let [i, objkey] of Object.keys(it).entries()) {
if (index == 0) {
strIt += "\"" + it[objkey].replace(/"/g, "\"\"") + "\"";
}
else {
strIt += "\"" + JSON.stringify((_a = it[fieldsArr[i]]) !== null && _a !== void 0 ? _a : "").replace(/"/g, "\"\"") + "\"";
}
if (i < (Object.keys(it).length - 1)) {
strIt += ",";
}
}
return strIt;
}).join('\n');
}
function parseCsv(csv) {
const re = /(,|\r?\n|\r|^)(?:"([^"]*(?:""[^"]*)*)"|([^,\r\n]*))/gi;
const result = [[]];
let matches;
while ((matches = re.exec(csv))) {
if (matches[1].length && matches[1] !== ',')
result.push([]);
result[result.length - 1].push(matches[2] !== undefined ? matches[2].replace(/""/g, '"') : matches[3]);
}
// console.log('csv arr result', result, result.length);
let csvResult = arrayToObject(result);
return csvResult;
}
function arrayToObject(csvArray) {
//Take the first line (headers) from the array and remove it from the array.
const headers = csvArray.shift();
// Iterate through the rows and reduce each column to an object
return csvArray.filter((row) => {
console.log('csv object keys lngth', Object.keys(row).length);
return Object.keys(row).length > 1;
}).map((row) => {
return headers.reduce((acc, currentHeader, i) => {
// console.log('parsing row', row[i], index);
return ((currentHeader.indexOf('cols_') >= 0 || currentHeader == '') ? acc : ((row[i] != '' && row[i] != null) ? { ...acc, ...{ [currentHeader]: JSON.parse(row[i] == "TRUE" ? "true" : (row[i] == "FALSE" ? "false" : row[i])) } } : acc));
}, {});
});
}
function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
for (var i = 0; i < splitStr.length; i++) {
// You do not need to check if i is larger than splitStr length, as your for does that for you
// Assign it back to the array
splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
}
// Directly return the joined string
return splitStr.join(' ');
}
function alphabeticalSort(arr) {
let arrSorted = arr.sort((a, b) => {
return a.trim().toLowerCase().localeCompare(b.trim().toLowerCase());
});
return arrSorted;
}
function percentageString(val, valTotal) {
if (valTotal == 0) {
return "";
}
let num = (100 * val) / valTotal;
return " (" + (Math.round((num + Number.EPSILON) * 100) / 100) + "%)";
}
function getCurrentFiscal() {
let date = new Date();
if (date.getMonth() < 4) {
return (date.getFullYear() - 1);
}
return date.getFullYear();
}
function getDateTimeStrings(unixTimestamp) {
// Convert to milliseconds if the timestamp is in seconds
if (unixTimestamp.toString().length === 10) {
unixTimestamp *= 1000;
}
const date = new Date(unixTimestamp);
const options = {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
};
const estFormatter = new Intl.DateTimeFormat('en-US', {
...options,
timeZone: 'America/New_York',
});
const istFormatter = new Intl.DateTimeFormat('en-IN', {
...options,
timeZone: 'Asia/Kolkata',
});
const [estDate, estTime] = estFormatter.format(date).split(', ');
const [istDate, istTime] = istFormatter.format(date).split(', ');
return `${estDate} ${estTime} EST, ${istDate} ${istTime} IST`;
}
function getUsermap() {
var _a;
let userinfo = JSON.parse((_a = localStorage.getItem('userinfo')) !== null && _a !== void 0 ? _a : "{}");
let userMapHome = JSON.parse(JSON.parse((userinfo.user.usermap.S).replace(/_QUOTES_/g, "\\\"")));
return userMapHome;
}
function getProjectConfigHome() {
var _a;
let userinfo = JSON.parse((_a = localStorage.getItem('userinfo')) !== null && _a !== void 0 ? _a : "{}");
let projectConfigHome = JSON.parse(JSON.parse((userinfo.project.data.value.confighome)));
return projectConfigHome;
}
function getProjectUsermap() {
var _a;
let projectUsermap = JSON.parse(((_a = localStorage.getItem('projectusermap')) !== null && _a !== void 0 ? _a : "{}").replace(/_QUOTES_/g, "\\\""));
return projectUsermap;
}
function setFeatures(features) {
localStorage.setItem('features', JSON.stringify(features));
}
function getFeatures() {
var _a;
let features = JSON.parse((_a = localStorage.getItem('features')) !== null && _a !== void 0 ? _a : '["compliances"]');
return features;
}
export const downloadExcelFromCSV = (csvString, fileName = 'report.xlsx', title, projectname) => {
const coverSheetData = [
[title],
[],
['Project:', projectname],
['Date:', getDateTimeStrings(new Date().getTime())],
['Classification:', 'Confidential'],
['Confidentiality Notice:', 'This document is intended only for the recipient(s) and may contain confidential information. Unauthorized use or disclosure is prohibited. If you are not the intended recipient, please notify the sender and delete this document.']
];
// Create cover sheet
const coverSheet = XLSX.utils.aoa_to_sheet(coverSheetData);
// Create CSV data sheet
const csvSheet = XLSX.read(csvString, { type: 'string' }).Sheets.Sheet1;
// Create a workbook and append both sheets
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, coverSheet, 'Doc');
XLSX.utils.book_append_sheet(workbook, csvSheet, title);
// Write workbook to binary
const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' });
const s2ab = (s) => {
const buf = new ArrayBuffer(s.length);
const view = new Uint8Array(buf);
for (let i = 0; i < s.length; i++) {
view[i] = s.charCodeAt(i) & 0xff;
}
return buf;
};
const blob = new Blob([s2ab(wbout)], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
function isJSONParsable(str) {
if (typeof str !== "string")
return false;
try {
JSON.parse(str);
return true;
}
catch {
return false;
}
}
function isVisible(el) {
const style = window.getComputedStyle(el);
const rect = el.getBoundingClientRect();
console.log('previous style', style.display, rect, el.id, (rect.height > 0 &&
rect.width > 0) && (style.display !== "none" &&
style.visibility !== "hidden" &&
style.opacity !== "0"));
return (rect.height > 0 &&
rect.width > 0) && (style.display !== "none" &&
style.visibility !== "hidden" &&
style.opacity !== "0");
}
function compareObjects(obj1, obj2) {
if (obj1 === obj2)
return {};
// Case: both are arrays
if (Array.isArray(obj1) && Array.isArray(obj2)) {
// One empty, one not → full diff
if (obj1.length === 0 && obj2.length > 0) {
return obj2;
}
if (obj2.length === 0 && obj1.length > 0) {
return obj1;
}
const maxLength = Math.max(obj1.length, obj2.length);
const result = [];
for (let i = 0; i < maxLength; i++) {
if (i >= obj1.length) {
result[i] = obj2[i]; // new item
}
else if (i >= obj2.length) {
result[i] = obj1[i]; // removed item
}
else {
const diff = compareObjects(obj1[i], obj2[i]);
if (Object.keys(diff).length > 0) {
result[i] = diff;
}
}
}
return result.filter(v => v !== undefined).length > 0 ? result : {};
}
// Case: both are objects
if (typeof obj1 === "object" &&
obj1 !== null &&
typeof obj2 === "object" &&
obj2 !== null) {
const keys = new Set([...Object.keys(obj1), ...Object.keys(obj2)]);
const diff = {};
for (const key of keys) {
if (!(key in obj1)) {
diff[key] = obj2[key];
}
else if (!(key in obj2)) {
diff[key] = obj1[key];
}
else {
const valueDiff = compareObjects(obj1[key], obj2[key]);
if (typeof valueDiff === "object" &&
valueDiff !== null &&
Object.keys(valueDiff).length === 0) {
continue;
}
if (valueDiff !== undefined) {
diff[key] = valueDiff;
}
}
}
return Object.keys(diff).length > 0 ? diff : {};
}
// Case: primitives
return obj1 !== obj2 ? [obj1, obj2] : {};
}
const exportFunctions = {
callApiPresignedDelete, callApiPresignedGet, callApiPresigned, jsonObjectToHtml, clearListeners, isInteger, callApi, validateName, readCookie, timeSince, createDiagonalPattern1, createDiagonalPattern2, createDiagonalPattern3, getRandomColor, convertToCSV, parseCsv, titleCase, alphabeticalSort, percentageString, getCurrentFiscal, getDateTimeStrings, getUsermap, getProjectConfigHome, setFeatures, getFeatures, getProjectUsermap, downloadExcelFromCSV, isJSONParsable, isVisible, compareObjects
};
export default exportFunctions;
//# sourceMappingURL=util.js.map