First commit after cleanup
Some checks failed
armco-org/utils/pipeline/head There was a failure building this commit

This commit is contained in:
2025-11-09 01:56:25 +05:30
commit b576d978d3
28 changed files with 6907 additions and 0 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

17
.gitignore vendored Normal file
View File

@@ -0,0 +1,17 @@
dist
node_modules
build
HOC
adapters
chartGenerators
contexts
dateHelper
dateformat
domHelper
gridHelper
helper
hooks
network
providers
recursionHelper
validators

6
Jenkinsfile vendored Normal file
View File

@@ -0,0 +1,6 @@
@Library('jenkins-shared') _
kanikoPipeline(
repoName: 'utils',
branch: env.BRANCH_NAME ?: 'main',
isNpmLib: true
)

2
README.md Normal file
View File

@@ -0,0 +1,2 @@
# utils
Armco frontend shared utilities

36
build-tools/build.sh Executable file
View File

@@ -0,0 +1,36 @@
#!/bin/bash
# Get the directory of the current script
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Default values
DEV_FLAG=""
# Parse arguments
for arg in "$@"
do
case $arg in
--dev)
DEV_FLAG="--dev"
shift # Remove --dev from processing
;;
esac
done
echo "[BUILD:SH] Dev flag is: $DEV_FLAG"
echo "[BUILD:SH] Removing build if exists"
rm -rf build
echo "[BUILD:SH] Checking TS Types"
npx tsc
echo "[BUILD:SH] Initiating build..."
# Conditionally use vite-dev.config.ts if --dev flag is present
if [ "$DEV_FLAG" == "--dev" ]; then
vite build --config vite-dev.config.ts
else
vite build
fi
echo "[BUILD:SH] Running post processor scripts..."
# Run Post processors: Update style imports in .js files, create component modules
node "$SCRIPT_DIR/post-processor.js" build/cjs $DEV_FLAG
node "$SCRIPT_DIR/post-processor.js" build/es $DEV_FLAG

View File

@@ -0,0 +1,33 @@
import { promises as fs } from "fs"
import { dirname, resolve } from "path"
import { fileURLToPath } from "url"
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const exclusions = ["enums.js", "v4.js", "index.js"]
async function generateModule(fileName, isDev) {
if (!exclusions.includes(fileName) && !fileName.endsWith(".js.map")) {
const dir = fileName.slice(0, -3)
const name = `@armco/utils/${dir}`
const packageJsonContent = {
name,
main: `../${isDev ? "build/" : ""}cjs/${dir}.js`,
module: `../${isDev ? "build/" : ""}es/${dir}.js`,
types: `../${isDev ? "build/" : ""}types/${dir}.d.ts`,
}
const dirPath = resolve(__dirname, `../${isDev ? "" : "build/"}${dir}`)
try {
await fs.mkdir(dirPath, { recursive: true })
await fs.writeFile(
resolve(dirPath, "package.json"),
JSON.stringify(packageJsonContent, null, 2),
)
} catch (error) {
console.error(`Error processing directory ${dirPath}:`, error)
}
}
}
export default generateModule

View File

@@ -0,0 +1,25 @@
import { readdir } from "fs/promises"
import generateModule from "./generate-module.js"
async function postProcessor(dir, isDev) {
try {
const files = await readdir(dir)
await Promise.all(
files.map(async (file) => {
await generateModule(file, isDev)
}),
)
} catch (error) {
console.error(`Error processing directory ${dir}:`, error)
}
}
const targetDir = process.argv[2]
const isDev = process.argv.includes("--dev")
if (targetDir) {
postProcessor(targetDir, isDev)
} else {
console.error("Please provide the build directory to run post processor on.")
process.exit(1)
}

4517
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

66
package.json Normal file
View File

@@ -0,0 +1,66 @@
{
"name": "@armco/utils",
"version": "0.0.29",
"type": "module",
"scripts": {
"build": "./build-tools/build.sh",
"build:sm": "./build-tools/build.sh --dev",
"format": "prettier --write .",
"lint": "eslint .",
"publish:sh": "./publish.sh",
"publish:local": "./publish-local.sh"
},
"dependencies": {
"@armco/configs": "^0.0.12"
},
"peerDependencies": {
"@armco/types": "^0.0.18",
"d3": "^7.9.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.18.2",
"uuid": "^9.0.0"
},
"devDependencies": {
"@armco/types": "^0.0.20",
"@types/d3": "^7.4.3",
"@types/node": "^24.10.0",
"@types/react": "^19.2.2",
"@vitejs/plugin-react": "^5.1.0",
"glob": "^11.0.3",
"react-dom": "18.3.1",
"typescript": "^5.9.3",
"vite-plugin-dts": "^4.5.4",
"vite-plugin-externalize-deps": "^0.10.0",
"vitest": "^4.0.8"
},
"eslintConfig": {
"plugins": [
"prettier"
],
"rules": {
"prettier/prettier": "error"
}
},
"prettier": "prettier-config-nick",
"main": "build/cjs/index.js",
"module": "build/es/index.js",
"types": "build/types/index.d.ts",
"repository": {
"type": "git",
"url": "git+https://gitea.armco.dev/ReStruct-Corporate-Advantage/utils.git"
},
"files": [
"build"
],
"keywords": [
"components",
"atomic",
"building-blocks",
"foundation"
],
"license": "ISC",
"bugs": {
"url": "https://gitea.armco.dev/ReStruct-Corporate-Advantage/utils/issues"
},
"homepage": "https://gitea.armco.dev/ReStruct-Corporate-Advantage/utils#readme"
}

16
publish-local.sh Executable file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
semver=${1:-patch}
set -e
npm run build
cp package.json build/
sed -i '' -E 's/"build"/"*"/' build/package.json
sed -i '' 's#"build/cjs/index.js"#"cjs/index.js"#' build/package.json
sed -i '' 's#"build/es/index.js"#"es/index.js"#' build/package.json
sed -i '' 's#"build/types/index.d.ts"#"types/index.d.ts"#' build/package.json
cd build
npm pack --pack-destination ~/__Projects__/Common

28
publish.sh Executable file
View File

@@ -0,0 +1,28 @@
#!/bin/sh
semver=${1:-patch}
set -e
npm --no-git-tag-version version ${semver}
npm run build
cp package.json build/
# Use Node.js for portable package.json normalization
# Pass the target path via env var to avoid Node treating it as a module/script argument
PKG_PATH="$(pwd)/build/package.json" node - <<'EOF'
const fs = require('fs');
const path = process.env.PKG_PATH;
const pkg = JSON.parse(fs.readFileSync(path, 'utf8'));
pkg.private = false;
delete pkg.scripts;
delete pkg.devDependencies;
if (!pkg.files) pkg.files = ['*'];
else pkg.files = pkg.files.map(x => x === 'build' ? '*' : x);
['main','module','types'].forEach(k => {
if (pkg[k]) pkg[k] = pkg[k].replace(/^build\//, '');
});
fs.writeFileSync(path, JSON.stringify(pkg, null, 2) + '\n');
EOF
cd build
npm publish --access public --loglevel verbose

View File

@@ -0,0 +1,6 @@
{
"name": "@armco/utils/react-app-env.d",
"main": "../build/cjs/react-app-env.d.js",
"module": "../build/es/react-app-env.d.js",
"types": "../build/types/react-app-env.d.d.ts"
}

11
src/HOC.tsx Normal file
View File

@@ -0,0 +1,11 @@
import { ComponentType } from "react"
import { useTheme } from "./hooks" // Adjust the import path as needed
export const withTheme = <P extends object>(
Component: ComponentType<P>,
): ComponentType<P> => {
return (props: P) => {
const { theme, setTheme } = useTheme()
return <Component {...(props as P)} theme={theme} setTheme={setTheme} />
}
}

45
src/chartGenerators.ts Normal file
View File

@@ -0,0 +1,45 @@
import * as d3 from "d3"
import { ArrayType, ObjectType } from "@armco/types"
export const generateBubbleChart = (data: ArrayType | ObjectType) => {
const svg = d3.select("#ar-ArViz__chart-container")
if (svg && data) {
svg
.selectAll("circle")
.data(data as ArrayType)
.enter()
.append("circle")
.attr("cx", function (d) {
return (d as ObjectType).x as number
})
.attr("cy", function (d) {
return (d as ObjectType).y as number
})
.attr("r", function (d) {
return Math.sqrt((d as ObjectType).val as number) / Math.PI
})
.attr("fill", function (d) {
return (d as ObjectType).color as string
})
// Step 5
svg
.selectAll("text")
.data(data as ArrayType)
.enter()
.append("text")
.attr("x", function (d) {
const x = (d as ObjectType).x as number
const sqrt = Math.sqrt((d as ObjectType).val as number) as number
return x + sqrt / Math.PI
})
.attr("y", function (d) {
return ((d as ObjectType).y as number) + 4
})
.text(function (d) {
return (d as ObjectType).source as string
})
.style("font-family", "arial")
.style("font-size", "12px")
}
}

22
src/contexts.ts Normal file
View File

@@ -0,0 +1,22 @@
import { createContext } from "react"
import { ArContextType, ArThemes, FunctionType } from "@armco/types"
import { isMobile } from "./helper"
export const SlotterContext = createContext<{
slotted: Array<string>
setSlotted?: FunctionType
}>({ slotted: [] })
export const ArContext = createContext<ArContextType>({
theme: ArThemes.DARK1,
drawerState: { collapsed: isMobile() },
notify: () => {},
setDrawerState: () => {},
setLeftPanelContent: () => {},
setLoggedIn: () => {},
setModalState: () => {},
setRightPanelContent: () => {},
setTheme: () => {},
setUser: () => {},
clearUser: () => {},
})

337
src/dateformat.ts Normal file
View File

@@ -0,0 +1,337 @@
import { ArDateMasks, FunctionType } from "@armco/types"
const token =
/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g
const timezone =
/\b(?:[A-Z]{1,3}[A-Z][TC])(?:[-+]\d{4})?|((?:Australian )?(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time)\b/g
const timezoneClip = /[^-+\dA-Z]/g
/**
* @param {string | number | Date} date
* @param {string} mask
* @param {boolean} utc
* @param {boolean} gmt
*/
export function dateFormat(
date?: number | Date,
mask?: ArDateMasks | string,
utc?: boolean,
gmt?: boolean,
) {
// You can't provide utc if you skip other args (use the 'UTC:' mask prefix)
if (arguments.length === 1 && typeof date === "string" && !/\d/.test(date)) {
mask = date
date = undefined
}
date = date || date === 0 ? date : new Date()
if (isNaN(date as number)) {
throw TypeError("Invalid date")
}
if (!(date instanceof Date)) {
date = new Date(date)
}
mask = String(
ArDateMasksRecord[mask as string] || mask || ArDateMasksRecord["DEFAULT"],
)
// Allow setting the utc/gmt argument via the mask
const maskSlice = mask.slice(0, 4)
if (maskSlice === "UTC:" || maskSlice === "GMT:") {
mask = mask.slice(4)
utc = true
if (maskSlice === "GMT:") {
gmt = true
}
}
const _ = () => (utc ? "getUTC" : "get")
const d = () => (date as Date)[(_() + "Date") as "getDate" | "getUTCDate"]()
const D = () => (date as Date)[(_() + "Day") as "getDay" | "getUTCDay"]()
const m = () =>
(date as Date)[(_() + "Month") as "getMonth" | "getUTCMonth"]()
const y = () =>
(date as Date)[(_() + "FullYear") as "getFullYear" | "getUTCFullYear"]()
const H = () =>
(date as Date)[(_() + "Hours") as "getHours" | "getUTCHours"]()
const M = () =>
(date as Date)[(_() + "Minutes") as "getMinutes" | "getUTCMinutes"]()
const s = () =>
(date as Date)[(_() + "Seconds") as "getSeconds" | "getUTCSeconds"]()
const L = () =>
(date as Date)[
(_() + "Milliseconds") as "getMilliseconds" | "getUTCMilliseconds"
]()
const o = () => (utc ? 0 : (date as Date).getTimezoneOffset())
const W = () => date instanceof Date && getWeek(date)
const N = () => date instanceof Date && getDayOfWeek(date)
const flags: { [key: string]: FunctionType } = {
d: () => d(),
dd: () => pad(d()),
ddd: () => i18n.dayNames[D()],
DDD: () =>
getDayName({
y: y(),
m: m(),
d: d(),
_: _(),
dayName: i18n.dayNames[D()],
short: true,
}),
dddd: () => i18n.dayNames[D() + 7],
DDDD: () =>
getDayName({
y: y(),
m: m(),
d: d(),
_: _(),
dayName: i18n.dayNames[D() + 7],
}),
m: () => m() + 1,
mm: () => pad(m() + 1),
mmm: () => i18n.monthNames[m()],
mmmm: () => i18n.monthNames[m() + 12],
yy: () => String(y()).slice(2),
yyyy: () => pad(y(), 4),
h: () => H() % 12 || 12,
hh: () => pad(H() % 12 || 12),
H: () => H(),
HH: () => pad(H()),
M: () => M(),
MM: () => pad(M()),
s: () => s(),
ss: () => pad(s()),
l: () => pad(L(), 3),
L: () => pad(Math.floor(L() / 10)),
t: () => (H() < 12 ? i18n.timeNames[0] : i18n.timeNames[1]),
tt: () => (H() < 12 ? i18n.timeNames[2] : i18n.timeNames[3]),
T: () => (H() < 12 ? i18n.timeNames[4] : i18n.timeNames[5]),
TT: () => (H() < 12 ? i18n.timeNames[6] : i18n.timeNames[7]),
Z: () =>
gmt ? "GMT" : utc ? "UTC" : date instanceof Date && formatTimezone(date),
o: () =>
(o() > 0 ? "-" : "+") +
pad(Math.floor(Math.abs(o()) / 60) * 100 + (Math.abs(o()) % 60), 4),
p: () =>
(o() > 0 ? "-" : "+") +
pad(Math.floor(Math.abs(o()) / 60), 2) +
":" +
pad(Math.floor(Math.abs(o()) % 60), 2),
S: () =>
["th", "st", "nd", "rd"][
d() % 10 > 3 ? 0 : (+((d() % 100) - (d() % 10) !== 10) * d()) % 10
],
W: () => W(),
WW: () => {
const date = W()
date && pad(date)
},
N: () => N(),
}
return mask.replace(token, (match) => {
if (match in flags) {
return flags[match]()
}
return match.slice(1, match.length - 1)
})
}
const ArDateMasksRecord: Record<string, string> = {
DEFAULT: ArDateMasks.DEFAULT,
SHORTDATE: ArDateMasks.SHORTDATE,
PADDEDSHORTDATE: ArDateMasks.PADDEDSHORTDATE,
MEDIUMDATE: ArDateMasks.MEDIUMDATE,
LONGDATE: ArDateMasks.LONGDATE,
FULLDATE: ArDateMasks.FULLDATE,
SHORTTIME: ArDateMasks.SHORTTIME,
MEDIUMTIME: ArDateMasks.MEDIUMTIME,
LONGTIME: ArDateMasks.LONGTIME,
ISODATE: ArDateMasks.ISODATE,
ISOTIME: ArDateMasks.ISOTIME,
ISODATETIME: ArDateMasks.ISODATETIME,
ISOUTCDATETIME: ArDateMasks.ISOUTCDATETIME,
EXPIRESHEADERFORMAT: ArDateMasks.EXPIRESHEADERFORMAT,
}
// Internationalization strings
export let i18n = {
dayNames: [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat",
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
],
monthNames: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
],
timeNames: ["a", "p", "am", "pm", "A", "P", "AM", "PM"],
}
const pad = (val: number, len = 2) => String(val).padStart(len, "0")
/**
* Get day name
* Yesterday, Today, Tomorrow if the date lies within, else fallback to Monday - Sunday
* @param {Object}
* @return {String}
*/
const getDayName = ({
y,
m,
d,
_,
dayName,
short = false,
}: {
y: number
m: number
d: number
_: string
dayName: string
short?: boolean
}) => {
const today = new Date()
const yesterday = new Date()
const tomorrow = new Date()
const dateAccessor = (_ + "Date") as "getDate" | "getUTCDate"
const monthAccessor = (_ + "Month") as "getMonth" | "getUTCMonth"
const yearAccessor = (_ + "FullYear") as "getFullYear" | "getUTCFullYear"
yesterday.setDate(yesterday[dateAccessor]() - 1)
tomorrow.setDate(tomorrow[dateAccessor]() + 1)
const today_d = () => today[dateAccessor]()
const today_m = () => today[monthAccessor]()
const today_y = () => today[yearAccessor]()
const yesterday_d = () => yesterday[dateAccessor]()
const yesterday_m = () => yesterday[monthAccessor]()
const yesterday_y = () => yesterday[yearAccessor]()
const tomorrow_d = () => tomorrow[dateAccessor]()
const tomorrow_m = () => tomorrow[monthAccessor]()
const tomorrow_y = () => tomorrow[yearAccessor]()
if (today_y() === y && today_m() === m && today_d() === d) {
return short ? "Tdy" : "Today"
} else if (
yesterday_y() === y &&
yesterday_m() === m &&
yesterday_d() === d
) {
return short ? "Ysd" : "Yesterday"
} else if (tomorrow_y() === y && tomorrow_m() === m && tomorrow_d() === d) {
return short ? "Tmw" : "Tomorrow"
}
return dayName
}
/**
* Get the ISO 8601 week number
* Based on comments from
* http://techblog.procurios.nl/k/n618/news/view/33796/14863/Calculate-ISO-8601-week-and-year-in-javascript.html
*
* @param {Date} `date`
* @return {Number}
*/
const getWeek = (date: Date) => {
// Remove time components of date
const targetThursday = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate(),
)
// Change date to Thursday same week
targetThursday.setDate(
targetThursday.getDate() - ((targetThursday.getDay() + 6) % 7) + 3,
)
// Take January 4th as it is always in week 1 (see ISO 8601)
const firstThursday = new Date(targetThursday.getFullYear(), 0, 4)
// Change date to Thursday same week
firstThursday.setDate(
firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3,
)
// Check if daylight-saving-time-switch occurred and correct for it
const ds =
targetThursday.getTimezoneOffset() - firstThursday.getTimezoneOffset()
targetThursday.setHours(targetThursday.getHours() - ds)
// Number of weeks between target Thursday and first Thursday
const weekDiff =
(targetThursday.getTime() - firstThursday.getTime()) / (86400000 * 7)
return 1 + Math.floor(weekDiff)
}
/**
* Get ISO-8601 numeric representation of the day of the week
* 1 (for Monday) through 7 (for Sunday)
*
* @param {Date} `date`
* @return {Number}
*/
const getDayOfWeek = (date: Date) => {
let dow = date.getDay()
if (dow === 0) {
dow = 7
}
return dow
}
/**
* Get proper timezone abbreviation or timezone offset.
*
* This will fall back to `GMT+xxxx` if it does not recognize the
* timezone within the `timezone` RegEx above. Currently only common
* American and Australian timezone abbreviations are supported.
*
* @param {String | Date} date
* @return {String}
*/
export const formatTimezone = (date: Date) => {
const strDate = String(date)
const match = strDate.match(timezone) || [""]
return match
.pop()
?.replace(timezoneClip, "")
.replace(/GMT\+0000/g, "UTC")
}
export { dateFormat as DateFormatter }

353
src/domHelper.ts Normal file
View File

@@ -0,0 +1,353 @@
import { Children } from "react"
import {
CarouselProps,
ArPopoverPositions,
ObjectType,
Position,
} from "@armco/types"
const style = window.getComputedStyle(document.documentElement)
const fontSize = parseFloat(style.fontSize)
const markerSize = 7
export function outerWidth(el: HTMLElement) {
let width = el.offsetWidth
const style = getComputedStyle(el)
width += parseInt(style.marginLeft) + parseInt(style.marginRight)
return width
}
export function translate(
position: number,
metric: "px" | "%",
axis: "horizontal" | "vertical",
) {
const positionPercent = position === 0 ? position : position + metric
const positionCss =
axis === "horizontal" ? [positionPercent, 0, 0] : [0, positionPercent, 0]
const transitionProp = "translate3d"
const translatedPosition = "(" + positionCss.join(",") + ")"
return transitionProp + translatedPosition
}
export function hexToHsl(color: string, returnRaw?: boolean) {
const [r, g, b] = hexToRgb(color)
return rgbToHsl(r, g, b, returnRaw)
}
export function hexToRgb(color: string) {
const r = parseInt(color.substring(1, 3), 16) // Grab the hex representation of red (chars 1-2) and convert to decimal (base 10).
const g = parseInt(color.substring(3, 5), 16)
const b = parseInt(color.substring(5, 7), 16)
return [r, g, b]
}
/**
* Converts an RGB color value to HSL. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns h, s, and l in the set [0, 1].
*
* @param Number r The red color value
* @param Number g The green color value
* @param Number b The blue color value
* @return Array The HSL representation
*/
export function rgbToHsl(r: number, g: number, b: number, returnRaw?: boolean) {
r /= 255
g /= 255
b /= 255
const max = Math.max(r, g, b),
min = Math.min(r, g, b)
let h,
s,
l = (max + min) / 2
if (max === min) {
h = s = 0 // achromatic
} else {
const d = max - min
s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0)
break
case g:
h = (b - r) / d + 2
break
case b:
h = (r - g) / d + 4
break
}
// @ts-ignore
h /= 6
}
const colorInHSL = "hsl(" + h + ", " + s + "%, " + l + "%)"
return returnRaw ? [h, s, l] : colorInHSL
}
export function hslToRgb(h: number, s: number, l: number) {
let r, g, b
let hue2rgb
if (s === 0) {
r = g = b = l // achromatic
} else {
hue2rgb = (p: number, q: number, t: number) => {
if (t < 0) t += 1
if (t > 1) t -= 1
if (t < 1 / 6) return p + (q - p) * 6 * t
if (t < 1 / 2) return q
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6
return p
}
const q = l < 0.5 ? l * (1 + s) : l + s - l * s
const p = 2 * l - q
r = hue2rgb && hue2rgb(p, q, h + 1 / 3)
g = hue2rgb && hue2rgb(p, q, h)
b = hue2rgb && hue2rgb(p, q, h - 1 / 3)
}
return [r * 255, g * 255, b * 255]
}
export function rgbToHex(r: number, g: number, b: number) {
function componentToHex(c: number) {
var hex = c.toString(16)
return hex.length === 1 ? "0" + hex : hex
}
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b)
}
export function hslToHex(h: number, s: number, l: number) {
const [r, g, b] = hslToRgb(h, s, l)
return rgbToHex(Math.round(r), Math.round(g), Math.round(b))
}
/**
* Gets the list 'position' relative to a current index
* @param index
*/
export function getPosition(index: number, props: CarouselProps): number {
if (props.infiniteLoop) {
// index has to be added by 1 because of the first cloned slide
++index
}
if (index === 0) {
return 0
}
const childrenLength = Children.count(props.children)
if (props.centerMode && props.axis === "horizontal") {
let currentPosition = -index * props.centerSlidePercentage
const lastPosition = childrenLength - 1
if (index && (index !== lastPosition || props.infiniteLoop)) {
currentPosition += (100 - props.centerSlidePercentage) / 2
} else if (index === lastPosition) {
currentPosition += 100 - props.centerSlidePercentage
}
return currentPosition
}
return -index * 100
}
/**
* Sets the 'position' transform for sliding animations
* @param position
* @param forceReflow
*/
export function setPosition(
position: number,
axis: "horizontal" | "vertical",
): React.CSSProperties {
const style = {}
;[
"WebkitTransform",
"MozTransform",
"MsTransform",
"OTransform",
"transform",
"msTransform",
].forEach((prop) => {
// @ts-ignore
style[prop] = CSSTranslate(position, "%", axis)
})
return style
}
export function isKeyboardEvent(
e?: React.MouseEvent | React.KeyboardEvent,
): e is React.KeyboardEvent {
return e ? e.hasOwnProperty("key") : false
}
export function shouldUsePosition(
position: ArPopoverPositions,
anchorRect: DOMRect,
popoverRect: DOMRect,
) {
const exceeds: ObjectType = {
bottom:
anchorRect.top + anchorRect.height + popoverRect.height >
window.innerHeight,
right:
anchorRect.left + anchorRect.width + popoverRect.width >
window.innerWidth,
left: anchorRect.left - popoverRect.width < 0,
top: anchorRect.top - popoverRect.height < 0,
}
if (exceeds[position]) return false
if (position === "left" || position === "right") {
if (fontSize > anchorRect.top || fontSize > anchorRect.bottom) return false
} else {
if (fontSize > anchorRect.left || fontSize > anchorRect.right) return false
}
return position
}
export function adjustPosition(
position: ArPopoverPositions,
anchorRect: DOMRect,
popoverRect: DOMRect,
hideMarker?: boolean,
topOffset?: number,
) {
const popoverPositions: { [key: string]: Position } = {
[ArPopoverPositions.BOTTOM]: {
top:
anchorRect.top +
anchorRect.height +
(hideMarker ? 0 : markerSize) +
(topOffset || 0),
left: anchorRect.left + (anchorRect.width - popoverRect.width) / 2,
},
[ArPopoverPositions.RIGHT]: {
top: anchorRect.top + (anchorRect.height - popoverRect.height) / 2,
left: anchorRect.left + anchorRect.width + (hideMarker ? 0 : markerSize),
},
[ArPopoverPositions.LEFT]: {
top: anchorRect.top + (anchorRect.height - popoverRect.height) / 2,
left: anchorRect.left - popoverRect.width - (hideMarker ? 0 : markerSize),
},
[ArPopoverPositions.TOP]: {
top:
anchorRect.top -
popoverRect.height -
(hideMarker ? 0 : markerSize) -
(topOffset || 0),
left: anchorRect.left + (anchorRect.width - popoverRect.width) / 2,
},
}
let { left, top } = popoverPositions[position]
if (
position === ArPopoverPositions.BOTTOM ||
position === ArPopoverPositions.TOP
) {
if ((left as number) < 0) {
left = fontSize
}
if ((left as number) + popoverRect.width > window.innerWidth) {
left = `calc(100% - ${popoverRect.width}px - ${fontSize}px)`
}
} else {
if ((top as number) < 0) {
top = fontSize
}
if ((top as number) + popoverRect.height > window.innerHeight) {
top = `calc(100% - ${popoverRect.height}px - ${fontSize}px)`
}
}
return { left, top }
}
export function getPositionToUse(
anchorRect: DOMRect,
popoverRect: DOMRect,
requestedPosition?: ArPopoverPositions,
) {
if (requestedPosition && requestedPosition !== ArPopoverPositions.AUTO) {
return requestedPosition
}
const positionsPriority = [
ArPopoverPositions.BOTTOM,
ArPopoverPositions.RIGHT,
ArPopoverPositions.LEFT,
ArPopoverPositions.TOP,
]
for (const position of positionsPriority) {
if (shouldUsePosition(position, anchorRect, popoverRect)) {
return position
}
continue
}
return ArPopoverPositions.BOTTOM
}
export function calculatePopoverPosition(
anchorRect: DOMRect,
popoverRect: DOMRect,
requestedPosition?: ArPopoverPositions,
hideMarker?: boolean,
clickCoordinates?: Array<number> | null,
topOffset?: number,
) {
anchorRect = clickCoordinates
? {
left: clickCoordinates[0],
x: clickCoordinates[0],
top: clickCoordinates[1],
y: clickCoordinates[1],
height: 0,
width: 0,
right: window.screen.width - clickCoordinates[0],
bottom: window.screen.height - clickCoordinates[1],
toJSON: () => {},
}
: anchorRect
const position = getPositionToUse(anchorRect, popoverRect, requestedPosition)
const { left, top } = adjustPosition(
position,
anchorRect,
popoverRect,
hideMarker,
topOffset,
)
return {
leftTop: {
top: ("" + top).startsWith("calc") ? top : top + "px",
left: ("" + left).startsWith("calc") ? left : left + "px",
},
position,
}
}
export function openInNewTab(url: string) {
const win = window.open(url, "_blank")
if (win != null) {
win.focus()
}
}
export function download(data: string | Blob, filename?: string) {
const anchor = document.createElement("a")
anchor.href =
typeof data === "string" ? data : window.URL.createObjectURL(data)
anchor.download = filename || "edited-image.png"
document.body.appendChild(anchor)
anchor.click()
document.body.removeChild(anchor)
}

504
src/helper.tsx Normal file
View File

@@ -0,0 +1,504 @@
import { JSX, lazy } from "react"
import {
FunctionType,
ObjectType,
SearchArgs,
RouteConfig,
} from "@armco/types"
const validImageMimeTypes = [
"image/jpeg",
"image/png",
"image/gif",
"image/webp",
"image/svg+xml",
"image/tiff",
"image/bmp",
"image/x-icon",
]
interface ReplacerFunction {
(key: string, value: any): any
}
interface StringifyOnce {
(obj: any, replacer?: ReplacerFunction | null, indent?: number): string
}
export function populatePagesInRoutes(
routes: RouteConfig[],
fallback: FunctionType,
) {
routes &&
routes.forEach((route) => {
if (typeof route.element === "string") {
const elementName = route.element
const Component: JSX.ElementType = lazy(() =>
import(`../pages/${elementName}/${elementName}.tsx`).catch(fallback),
)
route.element = <Component />
if (route.children) {
populateComponentsInRoutes(route.children, fallback)
}
}
})
}
export function populateComponentsInRoutes(
routes: RouteConfig[],
fallback: FunctionType,
) {
routes &&
routes.forEach((route) => {
const hierarchy = route.hierarchy
if (typeof route.element === "string") {
const elementName = route.element
const Component: JSX.ElementType = lazy(
() =>
import(
`../components/${hierarchy}/${elementName}/${elementName}.tsx`
).catch(fallback),
// () => import(`../components/Component_404`)
)
route.element = <Component />
if (route.children) {
populateComponentsInRoutes(route.children, fallback)
}
}
})
}
export function recrusiveFilter(
data: Array<any>,
filter: string,
matchCase?: boolean,
searchKeys?: false | Array<string>,
) {
if (!filter || !data || data.length === 0) {
return data
}
if (!searchKeys || searchKeys.length === 0) {
searchKeys = ["label", "name", "id", "value"]
}
const dataClone = JSON.parse(JSON.stringify(data))
const filteredItems = dataClone.filter((obj: any) => {
return (
searchKeys &&
searchKeys.reduce((acc, key) => {
let isMatch =
obj[key] &&
(matchCase
? obj[key].indexOf(filter) > -1
: obj[key] &&
obj[key].toString().toLowerCase().indexOf(filter.toLowerCase()) >
-1)
if (obj.children) {
obj.children = recrusiveFilter(obj.children, filter, matchCase)
isMatch = isMatch || obj.children.length > 0
}
return acc || isMatch
}, false)
)
})
return filteredItems
}
export function search({
obj,
key,
value,
}: SearchArgs): ObjectType | undefined {
if (Array.isArray(obj)) {
for (const item of obj) {
const result = search({ obj: item, key, value })
if (result) return result
}
} else if (obj && typeof obj === "object" && !(obj instanceof Date)) {
if (key in obj && (value === undefined || obj[key] === value)) {
return obj
}
for (const item of Object.values(obj)) {
if (typeof item === "object" && !(item instanceof Date)) {
const result = search({ obj: item as ObjectType, key, value })
if (result) return result
}
}
}
return undefined
}
export function searchBy(
obj: any,
query: Record<string, string>,
matchType: "AND" | "OR" = "AND",
): ObjectType | undefined {
// Helper function to check if an object matches the query
const matchesQuery = (item: any): boolean => {
const conditions = Object.entries(query).map(([key, value]) => {
return key in item && item[key] === value;
});
// Match all conditions (AND) or any condition (OR)
return matchType === "AND" ? conditions.every(Boolean) : conditions.some(Boolean);
};
if (Array.isArray(obj)) {
// If obj is an array, recursively search each item
for (const item of obj) {
const result = searchBy(item, query, matchType);
if (result) return result;
}
} else if (obj && typeof obj === "object" && !(obj instanceof Date)) {
// If obj is an object, check if it matches the query
if (matchesQuery(obj)) {
return obj;
}
// Recursively search through the object's values
for (const value of Object.values(obj)) {
if (typeof value === "object" && !(value instanceof Date)) {
const result = searchBy(value, query, matchType);
if (result) return result;
}
}
}
return undefined;
}
export function filterTreeStructure(
args: SearchArgs,
): boolean | Array<ObjectType> | ObjectType | void {
let { obj, key, value } = args
if (Array.isArray(obj)) {
return obj.filter((item, index) => {
if (typeof item === "object" && !(item instanceof Date)) {
args.obj = item
const match = filterTreeStructure(args)
if (Array.isArray(match) && match.length > 0) {
; (obj as unknown as Array<Array<ObjectType>>).splice(index, 1, match)
}
return match
}
return false
})
} else {
if (obj) {
let found = false
if (key in obj && (value === undefined || obj[key] === value)) {
obj.hasMatched = true
}
Object.keys(obj).forEach((key) => {
const item = (obj as ObjectType)[key]
if (typeof item === "object" && !(item instanceof Date)) {
args.obj = item as ObjectType
const match = filterTreeStructure(args)
if (Array.isArray(match) ? match.length > 0 : match) {
found = true
} else {
delete (obj as ObjectType)[key]
}
if (Array.isArray(match) && match.length > 0) {
; (obj as ObjectType)[key] = match
}
} else (obj as ObjectType).hasMatched || delete (obj as ObjectType)[key]
})
return (obj.hasMatched as boolean) || found
}
return false
}
}
export function aggregate(
data: any,
aggregator: string,
): { [key: string]: Array<string> } {
let aggregated: { [key: string]: Array<string> } = {}
data.forEach((item: any) => {
const key = item[aggregator]
let aggregatedArray: Array<string> | undefined = aggregated[key]
if (!aggregatedArray) {
aggregatedArray = []
aggregated[key] = aggregatedArray
}
aggregatedArray.push(item)
})
return aggregated
}
export function generateCategories(
data: any,
categories: Array<string> | undefined,
): { [key: string]: { [key: string]: Array<string> } } {
const groups: { [key: string]: { [key: string]: Array<string> } } = {}
if (categories && data) {
categories.forEach((key) => {
let group: { [key: string]: Array<string> } = aggregate(data, key)
groups[key] = group
})
}
return groups
}
export function toCamelCase(
str: string,
separater: string,
includeFirst: boolean,
) {
const strParts = str.split(separater || " ")
return strParts
.map((part, i) =>
i === 0 && includeFirst
? part.charAt(0).toUpperCase() + part.slice(1)
: part,
)
.join("")
}
export function generateRandomId(length: number = 8) {
return Math.random()
.toString(36)
.substring(2, length + 2)
}
export function copyOrPrompt(text?: string, cb?: FunctionType) {
if (copyToClipboard(text)) {
cb && cb()
} else {
prompt("Clipboard (Select: ⌘+a > Copy: ⌘+c)", text)
}
}
export function copyToClipboard(text?: string) {
const isNotSafari = typeof (window as any).safari === "undefined"
if (isNotSafari) {
text && navigator.clipboard.writeText(text)
return true
} else {
return false
}
}
export function matchArrayFilters(
searchList: Array<any> | undefined,
filters: Array<any> | false | undefined,
match: string,
type?: string,
) {
if (filters && searchList) {
return type && type === "starts"
? searchList.filter(
(item) =>
filters.findIndex((al) =>
item[match].toLowerCase().startsWith(al.toLowerCase()),
) > -1,
)
: searchList.filter(
(item) =>
filters.findIndex(
(al) => item[match].toLowerCase() === al.value.toLowerCase(),
) > -1,
)
}
return searchList
}
export function importComponent(
name: string,
hierarchy: string,
fallback: FunctionType,
) {
return lazy(() =>
import(`../components/${hierarchy}/${name}/${name}.tsx`).catch(fallback),
)
}
export function getStylesFromClass(className: string): Record<string, string> {
const styleSheet = Array.from(document.styleSheets).find((sheet) =>
Array.from(sheet.cssRules).some(
(rule) =>
rule instanceof CSSStyleRule && rule.selectorText === `.${className}`,
),
)
if (styleSheet) {
const styleRule = Array.from(styleSheet.cssRules).find(
(rule) =>
rule instanceof CSSStyleRule && rule.selectorText === `.${className}`,
) as CSSStyleRule
if (styleRule) {
const styles: Record<string, string> = {}
for (let i = 0; i < styleRule.style.length; i++) {
const prop = styleRule.style[i]
styles[prop] = styleRule.style.getPropertyValue(prop)
}
return styles
}
}
return {}
}
export function debounce<T extends (...args: any[]) => void>(
func: T,
wait?: number,
immediate: boolean = false,
): (...args: Parameters<T>) => void {
let timeout: NodeJS.Timeout
return function (...args: Parameters<T>): void {
const later = () => {
timeout = undefined!
if (!immediate) {
func(...args)
}
}
clearTimeout(timeout)
if (immediate && !timeout) {
func(...args)
}
timeout = setTimeout(later, wait || 1000)
}
}
export function isMobile(): boolean {
let check = false
; (function (a: string) {
if (
/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(
a,
) ||
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(
a.substr(0, 4),
)
)
check = true
})(
(navigator.userAgent ||
navigator.vendor ||
("opera" in window && window.opera)) as string,
)
return check
}
export function getCookie(cookieName: string) {
return (
document.cookie
.match("(^|;)\\s*" + cookieName + "\\s*=\\s*([^;]+)")
?.pop() || ""
)
}
export function setCookie(cname: string, cvalue: string, exdays: number) {
const d = new Date()
d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000)
let expires = "expires=" + d.toUTCString()
document.cookie = cname + "=" + cvalue + ";" + expires + ";Path=/"
}
export function clearCookie(cname: string) {
document.cookie = cname + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"
}
export function pad(num: number, separator?: string) {
return ("" + num).padStart(2, "0") + (separator ? separator : "")
}
export function toReadable(str?: string) {
return str
?.replace(/([a-z])([A-Z])/g, "$1 $2")
.split(" ")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(" ")
}
export function generateFileKey(file: File | { name: string }) {
return "size" in file
? `${file.name}_${file.size}_${file.type}_${file.lastModified}`
: file.name + "-preexisting-" + Date.now()
}
export function convertToBytes(input: string): number {
const trimmedInput = input.trim().toLowerCase()
try {
if (trimmedInput.endsWith("kb")) {
const number = parseFloat(trimmedInput.slice(0, -2))
return number * 1024
} else if (trimmedInput.endsWith("mb")) {
const number = parseFloat(trimmedInput.slice(0, -2))
return number * 1024 * 1024
} else if (trimmedInput.endsWith("bytes")) {
const number = parseFloat(trimmedInput.slice(0, -5))
return number
} else if (!isNaN(parseFloat(trimmedInput))) {
return parseFloat(trimmedInput)
} else {
return -1
}
} catch (error) {
return -1
}
}
export function isImage(type: string) {
return !!type && validImageMimeTypes.indexOf(type) > -1
}
export const stringifyOnce: StringifyOnce = (obj, replacer, indent) => {
const printedObjects: any[] = []
const printedObjectKeys: string[] = []
function printOnceReplacer(key: string, value: any): any {
if (printedObjects.length > 2000) {
// browsers will not print more than 20K, I don't see the point to allow 2K.. algorithm will not be fast anyway if we have too many objects
return "object too long"
}
let printedObjIndex: number | false = false
printedObjects.forEach((obj, index) => {
if (obj === value) {
printedObjIndex = index
}
})
if (key === "") {
// root element
printedObjects.push(obj)
printedObjectKeys.push("root")
return value
} else if (printedObjIndex !== false && typeof value === "object") {
if (printedObjectKeys[printedObjIndex] === "root") {
return "(pointer to root)"
} else {
return (
"(see " +
(!!value && !!value.constructor
? value.constructor.name.toLowerCase()
: typeof value) +
" with key " +
printedObjectKeys[printedObjIndex] +
")"
)
}
} else {
const qualifiedKey = key || "(empty key)"
printedObjects.push(value)
printedObjectKeys.push(qualifiedKey)
if (replacer) {
return replacer(key, value)
} else {
return value
}
}
}
return JSON.stringify(obj, printOnceReplacer, indent)
}

298
src/hooks.ts Normal file
View File

@@ -0,0 +1,298 @@
import { useCallback, useContext, useEffect, useState } from "react"
import { useNavigate } from "react-router-dom"
import { v4 as uuid } from "uuid"
import {
AlertProps,
ArAlertType,
ArThemes,
DrawerProps,
FunctionType,
ModalProps,
PanelContent,
User,
} from "@armco/types"
import { SESSION_TOKEN_NAME } from "@armco/configs/constants"
import { ENDPOINTS, IAM } from "@armco/configs/endpoints"
import { ArContext, SlotterContext } from "./contexts"
import { clearCookie, setCookie } from "./helper"
import { get, post } from "./network"
export function useSlotted(componentName: string) {
const { slotted, setSlotted } = useContext(SlotterContext)
slotted?.indexOf(componentName) === -1 &&
setSlotted &&
setSlotted([...slotted, componentName])
}
export function useStateWithHistory<T>(
initialState?: T,
): [T | undefined, FunctionType, FunctionType, FunctionType, boolean, boolean] {
const [past, setPast] = useState<T[]>([])
const [present, setPresent] = useState<T | undefined>()
const [future, setFuture] = useState<T[]>([])
useEffect(() => {
!present && setPresent(initialState)
// eslint-disable-next-line
}, [initialState])
const undo = useCallback(() => {
if (past.length === 0) return
const newPast = [...past]
const newPresent = newPast.pop()
setPast(newPast)
present && setFuture([present, ...future])
setPresent(newPresent)
}, [future, past, present])
const redo = useCallback(() => {
if (future.length === 0) return
const newFuture = [...future]
const newPresent = newFuture.shift()
past && present && setPast([...past, present])
setFuture(newFuture)
setPresent(newPresent)
}, [future, past, present])
const updatePresent = useCallback(
(newState: any, skipHistory?: boolean) => {
!skipHistory && past && present && setPast([...past, present])
setPresent(newState)
!skipHistory && setFuture([])
},
[past, present],
)
return [
present,
updatePresent,
undo,
redo,
past.length > 0,
future.length > 0,
]
}
export const useTheme = (): {
theme: ArThemes
setTheme: (theme: ArThemes) => void
} => {
const context = useContext(ArContext)
if (!context) {
throw new Error("useTheme must be used within an ArProvider")
}
return { theme: context.theme, setTheme: context.setTheme }
}
export const useModalState = (): {
modalState?: ModalProps
setModalState: (modalState: ModalProps | undefined) => void
} => {
const context = useContext(ArContext)
if (!context) {
throw new Error("useModalState must be used within an ArProvider")
}
return {
modalState: context.modalState,
setModalState: context.setModalState,
}
}
export const useNotification = (): {
notification?: AlertProps
notify: (notification: AlertProps | undefined) => void
} => {
const context = useContext(ArContext)
if (!context) {
throw new Error("useNotification must be used within an ArProvider")
}
return {
notification: context.notification,
notify: context.notify,
}
}
export const useDrawerState = (): {
drawerState?: DrawerProps
setDrawerState: (drawerState: DrawerProps) => void
} => {
const context = useContext(ArContext)
if (!context) {
throw new Error("useDrawerState must be used within an ArProvider")
}
return {
drawerState: context.drawerState,
setDrawerState: context.setDrawerState,
}
}
export const useLoggedIn = (): {
isLoggedIn?: boolean
setLoggedIn: (isLoggedIn: boolean) => void
} => {
const context = useContext(ArContext)
if (!context) {
throw new Error("useLoggedIn must be used within an ArProvider")
}
return {
isLoggedIn: context.isLoggedIn,
setLoggedIn: context.setLoggedIn,
}
}
export const useUser = (): {
user?: User | null
setUser: (user: User | null) => void
clearUser: () => void
} => {
const context = useContext(ArContext)
if (!context) {
throw new Error("useUser must be used within an ArProvider")
}
return {
user: context.user,
setUser: context.setUser,
clearUser: context.clearUser,
}
}
export const usePanelContent = (
isLeft: boolean,
): {
panelContent?: PanelContent
setPanelContent: (panelContent: PanelContent) => void
} => {
const context = useContext(ArContext)
if (!context) {
throw new Error("usePanelContent must be used within an ArProvider")
}
return {
panelContent: isLeft ? context.leftPanelContent : context.rightPanelContent,
setPanelContent: isLeft
? context.setLeftPanelContent
: context.setRightPanelContent,
}
}
export function useClearSession() {
const { setLoggedIn } = useLoggedIn()
const { clearUser } = useUser()
return () => {
setLoggedIn(false)
clearUser()
clearCookie(SESSION_TOKEN_NAME)
}
}
export function useAuth() {
const { setUser } = useUser()
const { isLoggedIn, setLoggedIn } = useLoggedIn()
const { notify } = useNotification()
const clearSession = useClearSession()
const navigate = useNavigate()
const { setPanelContent: setRightPanelContent } = usePanelContent(false)
const postAuthSuccess = useCallback(
(
response: { status: number; body: any },
shouldNotify?: boolean,
shouldLoginParent?: boolean,
) => {
if (response && response.body && response.status === 200) {
const user = response.body.user as User
if (user?.username) {
if (!user.name && user.firstName) {
user.name = `${user.firstName}${
user.lastName ? " " + user.lastName : ""
}`
}
!isLoggedIn && setLoggedIn(true)
setUser(user)
setCookie("auth-session-user", user.username, 30)
shouldNotify &&
notify({
show: true,
message: "Logged in successfully!",
type: ArAlertType.SUCCESS,
uid: uuid(),
})
if (shouldLoginParent) {
window.parent.postMessage(
{ event: "LOGGED_IN", user: response.body },
"*",
)
} else {
setRightPanelContent({ componentName: "" })
window.location.pathname === "/" && navigate(`/${user.username}`)
}
} else {
notify({
message: "Malformed user details, try again or contact support!",
type: ArAlertType.ERROR,
uid: uuid(),
})
}
} else {
clearSession()
notify({
message: "Unknown error occurred on fetching user details!",
type: ArAlertType.ERROR,
uid: uuid(),
})
}
},
[],
)
const postAuthFailure = useCallback(
(
error: { status: number },
shouldNotify?: boolean,
shouldLogoutParent?: boolean,
) => {
if (!error.status || error.status === 403) {
shouldNotify &&
notify({
message: "Unable to fetch user details, logging out...",
type: ArAlertType.ERROR,
uid: uuid(),
})
console.error(
"Attempt fetching user details at page load failed",
error,
)
clearSession()
if (shouldLogoutParent) {
window.parent.postMessage({ event: "NOT_LOGGED_IN" }, "*")
} else {
setRightPanelContent({ componentName: "" })
window.location.pathname !== "/" && navigate("/")
}
}
},
[],
)
return {
check: () => {
return get(
IAM[process.env.NODE_ENV] +
ENDPOINTS.USERS.ROOT +
ENDPOINTS.USERS.CHECK,
)
},
postAuthSuccess,
postAuthFailure,
login: (credentials: { [key: string]: string | number | File }) => {
return post(
IAM[process.env.NODE_ENV] + ENDPOINTS.AUTH.ROOT + ENDPOINTS.AUTH.LOGIN,
credentials,
)
},
}
}

11
src/index.ts Normal file
View File

@@ -0,0 +1,11 @@
export * from "./dateformat"
export * from "./domHelper"
export * from "./helper"
export * from "./network"
export * from "./validators"
export * from "./recursionHelper"
export * from "./chartGenerators"
export * from "./hooks"
export * from "./contexts"
export * from "./providers"
export * from "./HOC"

252
src/network.ts Normal file
View File

@@ -0,0 +1,252 @@
import { FunctionType, ObjectType } from "@armco/types"
import { HOST, STATIC_HOST } from "@armco/configs/endpoints"
import { SESSION_TOKEN_NAME } from "@armco/configs/constants"
import { getCookie } from "./helper"
interface Options extends RequestInit {
// headers?: {
// body?: object
// Origin?: string
// "Content-Type"?: string
// }
// method?: string
// mode?: string
// credentials?: string
headers?: any
toggleLoader?: Function
extras?: ObjectType
}
interface RetryOptions {
retryDescriptor?: number[]
maxAttempts?: number
onRetry?: (attempt: number, waitTime: number) => void
onSuccess?: () => void
onFailure?: (error: Error) => void
}
class Error {
error?: string
message?: string
status: number
extras?: ObjectType
constructor(message: string, status: number, extras?: ObjectType) {
this.message = message
this.status = status
this.extras = extras
}
}
const MAX_ATTEMPTS_LIMIT = 10
export async function get(
url: string,
queryParams?: object,
options?: Options,
) {
const urlString = stringifyUrl(url, queryParams)
options = {
method: "GET",
mode: "cors",
credentials: "include",
...options,
}
return crud(urlString, options)
}
export async function getStatic(
url: string,
queryParams?: object | null,
options?: Options | null,
) {
let urlString = stringifyUrl(url, queryParams)
const environment = process.env.NODE_ENV || "development"
const host = urlString.startsWith("http")
? ""
: STATIC_HOST[environment as keyof object]
urlString = host ? host + urlString : urlString
options = {
method: "GET",
mode: "cors",
credentials: "include",
...options,
}
return crud(urlString, options)
}
export async function post(
url: string,
data: object,
queryParams?: object,
options?: Options,
noStringify?: boolean,
noHeaders?: boolean,
) {
const urlString = stringifyUrl(url, queryParams)
options = {
method: "POST",
// @ts-ignore
body: noStringify ? data : JSON.stringify(data),
mode: "cors",
credentials: "include",
}
!noHeaders &&
options &&
(options.headers = { "Content-Type": "application/json" })
// @ts-ignore
return crud(urlString, options)
}
export async function upload(
url: string,
file: File,
queryParams?: object,
options?: Options,
) {
let urlString = stringifyUrl(url, queryParams)
const environment = process.env.NODE_ENV || "development"
const host = urlString.startsWith("http")
? ""
: STATIC_HOST[environment as keyof object]
urlString = host ? host + urlString : urlString
const formData = new FormData()
formData.append("file", file)
options = {
method: "POST",
mode: "cors",
body: formData,
credentials: "include",
...options,
}
return crud(urlString, options)
}
export async function put(url: string, data: object, queryParams?: object) {
const urlString = stringifyUrl(url, queryParams)
const options: Options = {
method: "PUT",
body: JSON.stringify(data),
mode: "cors",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
}
return crud(urlString, options)
}
export async function deleteRec(url: string, queryParams: object) {
const urlString = stringifyUrl(url, queryParams)
const options = {
method: "DELETE",
noInject: true,
}
return crud(urlString, options)
}
export async function crud(urlString: string, options: Options) {
const environment = process.env.NODE_ENV || "development"
const host = urlString.startsWith("http")
? ""
: HOST[environment as keyof object]
const extras = options?.extras
urlString = host ? host + urlString : urlString
if (!options.headers) {
options.headers = {}
}
options.toggleLoader && options.toggleLoader({ [urlString]: true })
options.headers["Origin"] =
window.location.protocol + "//" + window.location.host
options.headers[SESSION_TOKEN_NAME] = getCookie(SESSION_TOKEN_NAME)
const response = await fetch(urlString, options)
const { ok, status, headers } = response
if (ok) {
if (headers.get("content-type")) {
if (headers.get("content-type")!.indexOf("application/json") !== -1) {
const body = await response.json()
options.toggleLoader && options.toggleLoader({ [urlString]: false })
return { status, body, headers }
} else if (
headers.get("content-type")!.indexOf("application/zip") !== -1 ||
headers.get("content-type")!.indexOf("image/png") !== -1 ||
headers.get("content-type")!.indexOf("application/pdf") !== -1 ||
headers.get("content-type")!.indexOf("video/mp4") !== -1 ||
headers.get("content-type")!.indexOf("image/gif") !== -1
) {
const body = await response.blob()
options.toggleLoader && options.toggleLoader({ [urlString]: false })
return { status, body, headers }
}
}
const body = await response.text()
options.toggleLoader && options.toggleLoader({ [urlString]: false })
return { status, body, headers }
}
const err = await response.json()
options.toggleLoader && options.toggleLoader({ [urlString]: false })
console.log(err)
throw new Error(err.error || err.message, status, extras)
}
export function stringifyUrl(url: string, queryParams?: any) {
if (!queryParams) {
return url || ""
}
const arrLength = Object.keys(queryParams).length
return url && arrLength
? Object.keys(queryParams)
.filter((k) => queryParams[k] !== undefined)
.reduce(
(acc, key, index) =>
acc.concat(
`${encodeURIComponent(key)}=${encodeURIComponent(
queryParams[key],
).replace(/'/g, "%27")}` + (index < arrLength - 1 ? "&" : ""),
),
url + "?",
)
: ""
}
export async function retry(
fn: FunctionType,
retryOptions: RetryOptions | undefined = {},
) {
let {
retryDescriptor = [1, 3, 5],
maxAttempts = 5,
onRetry,
onSuccess,
onFailure,
} = retryOptions
maxAttempts = Math.min(maxAttempts, MAX_ATTEMPTS_LIMIT)
let attempts = 0
const attempt = async () => {
try {
const result = await fn()
onSuccess && onSuccess()
return result
} catch (error) {
if (attempts < Math.min(retryDescriptor.length, maxAttempts)) {
const waitTime = retryDescriptor[attempts] * 1000
attempts++
onRetry && onRetry(attempts, waitTime)
console.warn(`Retrying in ${waitTime / 1000} seconds...`)
await new Promise((resolve) => setTimeout(resolve, waitTime))
return attempt()
} else {
const errorObj = new Error(
"Max retries reached",
500,
error as ObjectType,
)
onFailure && onFailure(errorObj)
throw errorObj
}
}
}
return attempt()
}

56
src/providers.tsx Normal file
View File

@@ -0,0 +1,56 @@
import { ReactNode, useState } from "react"
import {
AlertProps,
ArThemes,
DrawerProps,
ModalProps,
PanelContent,
User,
} from "@armco/types"
import { ArContext } from "./contexts"
import { isMobile } from "./helper"
export const ArProvider = ({ children }: { children: ReactNode }) => {
const [theme, setTheme] = useState<ArThemes>(ArThemes.LIGHT1)
const [isLoggedIn, setLoggedIn] = useState<boolean>()
const [user, setUser] = useState<User | null>()
const [modalState, setModalState] = useState<ModalProps | undefined>(
undefined,
)
const [notification, notify] = useState<AlertProps | undefined>(undefined)
const [drawerState, setDrawerState] = useState<DrawerProps>({
collapsed: isMobile(),
})
const [leftPanelContent, setLeftPanelContent] = useState<
PanelContent | undefined
>()
const [rightPanelContent, setRightPanelContent] = useState<
PanelContent | undefined
>()
return (
<ArContext.Provider
value={{
isLoggedIn,
setLoggedIn,
theme,
setTheme,
modalState,
setModalState,
notification,
notify,
drawerState,
setDrawerState,
user,
setUser,
clearUser: () => setUser(null),
leftPanelContent,
setLeftPanelContent,
rightPanelContent,
setRightPanelContent,
}}
>
{children}
</ArContext.Provider>
)
}

71
src/react-app-env.d.ts vendored Normal file
View File

@@ -0,0 +1,71 @@
/// <reference types="node" />
/// <reference types="react" />
/// <reference types="react-dom" />
declare namespace NodeJS {
interface ProcessEnv {
readonly NODE_ENV: "development" | "production"
readonly PUBLIC_URL: string
}
}
declare module "*.avif" {
const src: string
export default src
}
declare module "*.bmp" {
const src: string
export default src
}
declare module "*.gif" {
const src: string
export default src
}
declare module "*.jpg" {
const src: string
export default src
}
declare module "*.jpeg" {
const src: string
export default src
}
declare module "*.png" {
const src: string
export default src
}
declare module "*.webp" {
const src: string
export default src
}
declare module "*.svg" {
import * as React from "react"
export const ReactComponent: React.FunctionComponent<
React.SVGProps<SVGSVGElement> & { title?: string }
>
const src: string
export default src
}
declare module "*.module.css" {
const classes: { readonly [key: string]: string }
export default classes
}
declare module "*.module.scss" {
const classes: { readonly [key: string]: string }
export default classes
}
declare module "*.module.sass" {
const classes: { readonly [key: string]: string }
export default classes
}

72
src/recursionHelper.tsx Normal file
View File

@@ -0,0 +1,72 @@
import { v4 as uuid } from "uuid"
import { FunctionType, ObjectType, RecusionConditionTypes } from "@armco/types"
export interface RecursionArgs {
data: any
preop?: FunctionType
postop?: FunctionType
isBrute?: boolean
condition?: ObjectType
iterateOn?: string
}
export function recur(args: RecursionArgs) {
const { condition, data, isBrute, preop, postop, iterateOn } = args
if (isBrute) {
if (Array.isArray(data)) {
data.forEach((item) => {
recur({ ...args, data: item })
})
} else if (typeof data === "object") {
const preopResult = preop && preop(data)
Object.values(data).forEach((item: any) => {
recur({ ...args, data: item })
})
return (postop && postop(data)) || preopResult
}
} else {
if (Array.isArray(data)) {
data.forEach((item) => {
recur({ ...args, data: item })
})
} else if (
typeof data === "object" &&
(!condition || evaluateCondition(data, condition))
) {
const preopResult = preop && preop(data)
if (iterateOn) {
if (data[iterateOn]) {
recur({ ...args, data: data[iterateOn] })
}
} else {
Object.values(data).forEach((item) => {
recur({ ...args, data: item })
})
}
return (postop && postop(data)) || preopResult
}
}
return null
}
export function injectIds(args: RecursionArgs) {
args.postop = (item) => !item.id && (item.id = uuid())
recur(args)
}
export function evaluateCondition(data: ObjectType, condition: ObjectType): boolean {
if (!data || !condition) {
return false
}
if (condition.type === RecusionConditionTypes.KEY_EXISTS) {
return !!(condition.key && (condition.key as string) in data)
} else if (condition.type === RecusionConditionTypes.KEY_VALUE) {
return !!(
condition.key &&
condition.value &&
data[condition.key as string] === condition.value
)
}
return false
}

13
src/validators.ts Normal file
View File

@@ -0,0 +1,13 @@
import { ObjectType } from "@armco/types"
export function validateTask(taskObj: ObjectType) {
return (
taskObj &&
taskObj.name &&
taskObj.client &&
taskObj.target &&
(taskObj.target as ObjectType).endpoint &&
taskObj.schedule &&
(taskObj.schedule as ObjectType).cron
)
}

27
tsconfig.json Normal file
View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"outDir": "build",
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
, "../Calendar/src/dateHelper.ts" ]
}

42
vite-dev.config.ts Normal file
View File

@@ -0,0 +1,42 @@
import { resolve } from "node:path"
import { glob } from "glob"
import { defineConfig } from "vitest/config"
import react from "@vitejs/plugin-react"
import dts from "vite-plugin-dts"
import { externalizeDeps } from "vite-plugin-externalize-deps"
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(), dts({ outDir: "build/types" }), externalizeDeps()],
build: {
outDir: "build",
sourcemap: true,
lib: {
entry: glob.sync(resolve(__dirname, "src/**/*.{ts,tsx}")),
},
rollupOptions: {
treeshake: true,
external: [
new RegExp("^react.*"),
new RegExp("^@armco/.*"),
"@armco/icon",
"uuid",
"d3",
],
output: [
{
format: "es",
dir: "build/es",
entryFileNames: "[name].js",
chunkFileNames: "[name].js",
},
{
format: "cjs",
dir: "build/cjs",
entryFileNames: "[name].js",
chunkFileNames: "[name].js",
},
],
},
},
})

41
vite.config.ts Normal file
View File

@@ -0,0 +1,41 @@
import { resolve } from "node:path"
import { glob } from "glob"
import { defineConfig } from "vitest/config"
import react from "@vitejs/plugin-react"
import dts from "vite-plugin-dts"
import { externalizeDeps } from "vite-plugin-externalize-deps"
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(), dts({ outDir: "build/types" }), externalizeDeps()],
build: {
outDir: "build",
lib: {
entry: glob.sync(resolve(__dirname, "src/**/*.{ts,tsx}")),
},
rollupOptions: {
treeshake: true,
external: [
new RegExp("^react.*"),
new RegExp("^@armco/.*"),
"@armco/icon",
"uuid",
"d3",
],
output: [
{
format: "es",
dir: "build/es",
entryFileNames: "[name].js",
chunkFileNames: "[name].js",
},
{
format: "cjs",
dir: "build/cjs",
entryFileNames: "[name].js",
chunkFileNames: "[name].js",
},
],
},
},
})