ziko
Version:
a versatile javaScript framework offering a rich set of UI components, advanced mathematical utilities, reactivity, animations, client side routing and graphics capabilities
1,555 lines (1,485 loc) • 256 kB
JavaScript
/*
Project: ziko.js
Author: Zakaria Elalaoui
Date : Tue Aug 12 2025 11:00:20 GMT+0100 (UTC+01:00)
Git-Repo : https://github.com/zakarialaoui10/ziko.js
Git-Wiki : https://github.com/zakarialaoui10/ziko.js/wiki
Released under MIT License
*/
function composeClass(Class, mixin) {
const descriptors = Object.getOwnPropertyDescriptors(mixin);
class Composed extends Class {
constructor(...args) {
super(...args);
for (const key of Reflect.ownKeys(descriptors)) {
const desc = descriptors[key];
if (typeof desc.value === 'function') {
this[key] = desc.value.bind(this);
}
}
}
}
for (const key of Reflect.ownKeys(descriptors)) {
const desc = descriptors[key];
if ('get' in desc || 'set' in desc) {
Object.defineProperty(Composed.prototype, key, desc);
} else if (typeof desc.value !== 'function') {
Object.defineProperty(Composed.prototype, key, desc);
}
}
return Composed;
}
function composeInstance(instance, mixin) {
const descriptors = Object.getOwnPropertyDescriptors(mixin);
for (const key of Reflect.ownKeys(descriptors)) {
const desc = descriptors[key];
if ('get' in desc || 'set' in desc) {
Object.defineProperty(instance, key, desc);
} else if (typeof desc.value === 'function') {
instance[key] = desc.value.bind(instance);
} else {
instance[key] = desc.value;
}
}
}
function compose(target, ...mixin) {
if (typeof target === 'function') {
return mixin.forEach(item =>composeClass(target, item));
} else if (typeof target === 'object') {
mixin.forEach(item =>composeInstance(target, item));
} else {
throw new TypeError("compose: target must be a class or instance");
}
}
const __ExtractAll__ =(obj)=> {
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (!["__ExtractAll__","__RemoveAll__","ExtractAll","RemoveAll"].includes(key)) {
globalThis[key] = obj[key];
}
}
};
const __RemoveAll__ =(obj)=> {
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key !== '__RemoveAll__') {
delete globalThis[key];
}
}
};
const { PI: PI$1, E } = Math;
const EPSILON=Number.EPSILON;
var __Const__ = /*#__PURE__*/Object.freeze({
__proto__: null,
E: E,
EPSILON: EPSILON,
PI: PI$1
});
const {PI, cos: cos$1, sin: sin$1, tan: tan$1, acos: acos$1, asin: asin$1, atan: atan$1, cosh: cosh$1, sinh: sinh$1, tanh: tanh$1, acosh: acosh$1, asinh: asinh$1, atanh: atanh$1, log} = Math;
let Fixed={
cos: cos$1,
sin: sin$1,
tan: tan$1,
sinc: x => sin$1(PI*x)/(PI*x),
sec: x => 1/cos$1(x),
csc: x => 1/sin$1(x),
cot: x => 1/tan$1(x),
acos: acos$1,
asin: asin$1,
atan: atan$1,
acot: x => PI/2-atan$1(x),
cosh: cosh$1,
sinh: sinh$1,
tanh: tanh$1,
coth: n => (1/2*log((1+n)/(1-n))),
acosh: acosh$1,
asinh: asinh$1,
atanh: atanh$1,
};
Fixed = new Proxy(Fixed, {
get(target, prop) {
if(prop in target){
return x => + target[prop](x).toFixed(15);
}
return undefined;
}
});
class ZikoMath {}
/** @module Math */
/**
* map a function to ...X
* @param {function} fun
* @param {...any} X
* @returns {any|any[]}
*/
const mapfun$1=(fun,...X)=>{
const Y=X.map(x=>{
if(x===null)return fun(null);
if(["number","string","boolean","bigint","undefined"].includes(typeof x))return fun(x);
if(x instanceof Array)return x.map(n=>mapfun$1(fun,n));
if(ArrayBuffer.isView(x))return x.map(n=>fun(n));
if(x instanceof Set)return new Set(mapfun$1(fun,...[...x]));
if(x instanceof Map)return new Map([...x].map(n=>[n[0],mapfun$1(fun,n[1])]));
if(x instanceof Matrix){
return new Matrix(x.rows,x.cols,mapfun$1(x.arr.flat(1)))
}
if(x instanceof Complex){
const [a,b,z,phi]=[x.a,x.b,x.z,x.phi];
switch(fun){
case Math.log:return complex(ln(z),phi); // Done
case Math.exp:return complex(e(a)*cos(b),e(a)*sin(b)); // Done
case Math.abs:return z; // Done
case Math.sqrt:return complex(sqrt(z)*cos(phi/2),sqrt(z)*sin(phi/2)); // Done
case Fixed.cos:return complex(cos(a)*cosh(b),-(sin(a)*sinh(b)));
case Fixed.sin:return complex(sin(a)*cosh(b),cos(a)*sinh(b));
case Fixed.tan:{
const DEN=cos(2*a)+cosh(2*b);
return complex(sin(2*a)/DEN,sinh(2*b)/DEN);
}
case Fixed.cosh:return complex(cosh(a)*cos(b),sinh(a)*sin(b));
case Fixed.sinh:return complex(sinh(a)*cos(b),cosh(a)*sin(b));
case Fixed.tanh:{
const DEN=cosh(2*a)+cos(2*b);
return complex(sinh(2*a)/DEN,sin(2*b)/DEN)
}
default : return fun(x)
}
}
else if(x instanceof Object){
return fun(Object) || Object.fromEntries(Object.entries(x).map(n=>n=[n[0],mapfun$1(fun,n[1])]))
}
});
return Y.length==1?Y[0]:Y;
};
const _add=(a,b)=>{
if(typeof(a)==="number"){
if (typeof b == "number") return a + b;
else if (b instanceof Complex)return complex(a + b.a, b.b);
else if (b instanceof Matrix) return Matrix.nums(b.rows, b.cols, a).add(b);
else if (b instanceof Array)return b.map(n=>add(n,a));
}
else if(a instanceof Complex||a instanceof Matrix){
if(b instanceof Array)return b.map(n=>a.clone.add(n));
return a.clone.add(b);
}
else if(a instanceof Array){
if(b instanceof Array){
if(a.length === b.length)return a.map((n,i)=>add(n,b[i]))
}
else {
return a.map(n=>add(n,b));
}
}
};
const _sub=(a,b)=>{
if(typeof(a)==="number"){
if (typeof b == "number") return a - b;
else if (b instanceof Complex)return complex(a - b.a, -b.b);
else if (b instanceof Matrix) return Matrix.nums(b.rows, b.cols, a).sub(b);
else if (b instanceof Array)return b.map(n=>sub(n,a));
}
else if(a instanceof Complex||a instanceof Matrix){
if(b instanceof Array)return b.map(n=>a.clone.sub(n));
return a.clone.sub(b);
}
else if(a instanceof Array){
if(b instanceof Array){
if(b instanceof Array){
if(a.length === b.length)return a.map((n,i)=>sub(n,b[i]))
}
}
else {
return a.map(n=>sub(n,b));
}
}
};
const _mul=(a,b)=>{
if(typeof(a)==="number"){
if (typeof b == "number") return a * b;
else if (b instanceof Complex)return complex(a * b.a,a * b.b);
else if (b instanceof Matrix) return Matrix.nums(b.rows, b.cols, a).mul(b);
else if (b instanceof Array)return b.map(n=>mul(a,n));
}
else if(a instanceof Complex||a instanceof Matrix){
if(b instanceof Array)return b.map(n=>a.clone.mul(n));
return a.clone.mul(b);
}
else if(a instanceof Array){
if(b instanceof Array){
if(b instanceof Array){
if(a.length === b.length)return a.map((n,i)=>mul(n,b[i]))
}
}
else {
return a.map(n=>mul(n,b));
}
}
};
const _div=(a,b)=>{
if(typeof(a)==="number"){
if (typeof b == "number") return a / b;
else if (b instanceof Complex)return complex(a / b.a,a / b.b);
else if (b instanceof Matrix) return Matrix.nums(b.rows, b.cols, a).div(b);
else if (b instanceof Array)return b.map(n=>div(a,n));
}
else if(a instanceof Complex||a instanceof Matrix){
if(b instanceof Array)return b.map(n=>a.clone.div(n));
return a.clone.div(b);
}
else if(a instanceof Array){
if(b instanceof Array){
if(b instanceof Array){
if(a.length === b.length)return a.map((n,i)=>div(n,b[i]))
}
}
else {
return a.map(n=>div(n,b));
}
}
};
const _modulo=(a,b)=>{
if(typeof(a)==="number"){
if (typeof b == "number") return a % b;
else if (b instanceof Complex)return complex(a % b.a,a % b.b);
else if (b instanceof Matrix) return Matrix.nums(b.rows, b.cols, a).modulo(b);
else if (b instanceof Array)return b.map(n=>div(a,n));
}
else if(a instanceof Complex||a instanceof Matrix){
if(b instanceof Array)return b.map(n=>a.clone.div(n));
return a.clone.div(b);
}
else if(a instanceof Array){
if(b instanceof Array);
else {
return a.map(n=>add(n,b));
}
}
};
const add=(a,...b)=>{
var res=a;
for(let i=0;i<b.length;i++)res=_add(res,b[i]);
return res;
};
const sub=(a,...b)=>{
var res=a;
for(let i=0;i<b.length;i++)res=_sub(res,b[i]);
return res;
};
const mul=(a,...b)=>{
var res=a;
for(let i=0;i<b.length;i++)res=_mul(res,b[i]);
return res;
};
const div=(a,...b)=>{
var res=a;
for(let i=0;i<b.length;i++)res=_div(res,b[i]);
return res;
};
const modulo=(a,...b)=>{
var res=a;
for(let i=0;i<b.length;i++)res=_modulo(res,b[i]);
return res;
};
const zeros=(n)=>new Array(n).fill(0);
const ones=(n)=>new Array(n).fill(1);
const nums=(num,n)=>new Array(n).fill(num);
const norm=(value, min, max)=>{
if (typeof value === "number") return min !== max ? (value - min) / (max - min) : 0;
else if (value instanceof Matrix) return new Matrix(value.rows, value.cols, norm(value.arr.flat(1), min, max));
else if (value instanceof Complex) return new Complex(norm(value.a, min, max), norm(value.b, min, max));
else if (value instanceof Array) {
if (value.every((n) => typeof (n === "number"))) {
return value.map((n) => norm(n, min, max));
} else {
let y = new Array(value.length);
for (let i = 0; i < value.length; i++) {
y[i] = norm(value[i]);
}
}
}
};
const lerp=(value, min, max)=>{
if (typeof value === "number") return (max - min) * value + min;
else if (value instanceof Matrix) return new Matrix(value.rows, value.cols, lerp(value.arr.flat(1), min, max));
else if (value instanceof Complex) return new Complex(lerp(value.a, min, max), lerp(value.b, min, max));
else if (value instanceof Array) {
if (value.every((n) => typeof (n === "number"))) {
return value.map((n) => lerp(n, min, max));
} else {
let y = new Array(value.length);
for (let i = 0; i < value.length; i++) {
y[i] = lerp(value[i]);
}
}
}
};
const map=(value, a, b, c, d)=>{
if (typeof value === "number") return lerp(norm(value, a, b), c, d);
else if (value instanceof Matrix) return new Matrix(value.rows, value.cols, map(value.arr.flat(1), a, b, c, d));
else if (value instanceof Complex) return new Complex(map(value.a, b, c, d), map(value.b, a, b, c, d));
else if (value instanceof Array) {
if (value.every((n) => typeof (n === "number"))) {
return value.map((n) => map(n, a, b, c, d));
} else {
let y = new Array(value.length);
for (let i = 0; i < value.length; i++) {
y[i] = map(value[i], a, b, c, d);
}
}
}
};
const clamp=(x, a , b)=>{
const [min_value,max_value]=[min(a,b),max(a,b)];
if (typeof x === "number") return min(max(x, min_value), max_value);
else if (x instanceof Matrix) return new Matrix(x.rows, x.cols, clamp(x.arr.flat(1), min_value, max_value));
else if (x instanceof Complex) return new Complex(clamp(x.a, min_value, max_value), clamp(x.b, min_value, max_value));
else if (x instanceof Array) {
if (x.every((n) => typeof (n === "number"))) {
return x.map((n) => clamp(n, min_value, max_value));
} else {
let y = new Array(x.length);
for (let i = 0; i < x.length; i++) {
y[i] = clamp(x[i], min_value, max_value);
}
}
}
};
const arange=(a, b, step , include = false)=>{
let tab = [];
if(a<b){
for (let i = a; include?i<=b:i<b; i += step) tab.push((i * 10) / 10);
}
else {
for(let i = a; include?i>=b:i>b; i -= step) tab.push((i * 10) / 10);
}
return tab;
};
const linspace=(a,b,n=abs(b-a)+1,endpoint=true)=>{
if(Math.floor(n)!==n)return;
if([a,b].every(n=>typeof n==="number")){
const [max,min]=[a,b].sort((a,b)=>b-a);
var Y = [];
let step ;
endpoint ? step = (max - min) / (n - 1) : step = (max - min) / n;
for (var i = 0; i < n; i++) {
a<b?Y.push(min+step*i):Y.push(max-step*i);
}
return Y
}
if([a,b].some(n=>n instanceof Complex)){
const z1=complex(a);
const z2=complex(b);
n=n||Math.abs(z1.a-z2.a)+1;
const X=linspace(z1.a,z2.a,n,endpoint);
const Y=linspace(z1.b,z2.b,n,endpoint);
let Z=new Array(n).fill(null);
Z=Z.map((n,i)=>complex(X[i],Y[i]));
return Z;
}
};
const logspace=(a,b,n=b-a+1,base=E,endpoint=true)=>{
return linspace(a,b,n,endpoint).map(n=>pow(base,n))
};
const geomspace=(a,b,n=abs(b-a)+1,endpoint=true)=>{
if(Math.floor(n)!==n)return;
if([a,b].every(n=>typeof n==="number")){
const [max,min]=[a,b].sort((a,b)=>b-a);
let base;
endpoint ? base = sqrtn(max/min,n-1) : base = sqrtn(max/min,n) ;
const Y = [min];
for (let i = 1; i < n; i++) {
Y.push(Y[i-1]*base);
}
return a<b?Y:Y.reverse()
}
if([a,b].some(n=>n instanceof Complex)){
const z1=complex(a);
const z2=complex(b);
n=n||Math.abs(z1.a-z2.a)+1;
let base;
endpoint ? base = sqrtn(z2.div(z1),n-1) : base = sqrtn(z2.div(z1),n) ;
const Y = [z1];
for (let i = 1; i < n; i++) {
Y.push(mul(Y[i-1],base));
}
return Y;
}
};
/** @module Math */
/**
* Converts degrees to radians.
* @param {...number} deg - Degrees to convert.
* @returns {number|number[]} Returns an array of radians corresponding to the input degrees.
*/
const deg2rad = (...deg) => mapfun(x => x * Math.PI / 180, ...deg);
/**
* Converts radians to degrees.
* @param {...number} rad - Radians to convert.
* @returns {number|number[]} Returns an array of degrees corresponding to the input radians.
*/
const rad2deg = (...rad) => mapfun(x => x / Math.PI * 180, ...rad);
// Mixed calcul
const sum=(...x)=>{
if(x.every(n=>typeof n==="number")){
let s = x[0];
for (let i = 1; i < x.length; i++) s += x[i];
return s;
}
const Y=[];
for(let i=0;i<x.length;i++){
if(x[i] instanceof Array)Y.push(sum(...x[i]));
else if(x[i] instanceof Object){
Y.push(sum(...Object.values(x[i])));
}
}
return Y.length===1?Y[0]:Y;
};
const prod=(...x)=>{
if(x.every(n=>typeof n==="number")){
let p = x[0];
for (let i = 1; i < x.length; i++) p *= x[i];
return p;
}
const Y=[];
for(let i=0;i<x.length;i++){
if(x[i] instanceof Array)Y.push(prod(...x[i]));
else if(x[i] instanceof Object){
Y.push(prod(...Object.values(x[i])));
}
}
return Y.length===1?Y[0]:Y;
};
const min=(...num)=>{
if(num.every(n=>typeof n==="number"))return Math.min(...num);
const Y=[];
for(let i=0;i<num.length;i++){
if(num[i] instanceof Array)Y.push(min(...num[i]));
else if(num[i] instanceof Object){
Y.push(
Object.fromEntries(
[Object.entries(num[i]).sort((a,b)=>a[1]-b[1])[0]]
)
);
}
}
return Y.length===1?Y[0]:Y;
};
const max=(...num)=>{
if(num.every(n=>typeof n==="number"))return Math.max(...num);
const Y=[];
for(let i=0;i<num.length;i++){
if(num[i] instanceof Array)Y.push(min(...num[i]));
else if(num[i] instanceof Object){
Y.push(
Object.fromEntries(
[Object.entries(num[i]).sort((a,b)=>b[1]-a[1])[0]]
)
);
}
}
return Y.length===1?Y[0]:Y;
};
const accum=(...num)=>{
if(num.every(n=>typeof n==="number")){
let acc = num.reduce((x, y) => [...x, x[x.length - 1] + y], [0]);
acc.shift();
return acc;
}
const Y=[];
for(let i=0;i<num.length;i++){
if(num[i] instanceof Array)Y.push(accum(...num[i]));
else if(num[i] instanceof Object){
Y.push(null
// Object.fromEntries(
// [Object.entries(num[i]).sort((a,b)=>b[1]-a[1])[0]]
// )
);
}
}
return Y.length===1?Y[0]:Y;
};
//moy
//med
//variance
//std
//mode
//acccum
//min2max
//max2min
//percentile
/** @module Math */
/**
* Checks if a value is within the specified range.
* @function
* @param {number} x - The value to check.
* @param {number} a - The start of the range.
* @param {number} b - The end of the range.
* @returns {boolean} Returns true if the value is within the range [a, b], otherwise false.
*/
const inRange = (x, a, b) => {
const [min, max] = [Math.min(a, b), Math.max(a, b)];
return x >= min && x <= max;
};
/**
* Checks if two numbers are approximately equal within a given error margin.
* @param {number} a - The first number.
* @param {number} b - The second number.
* @param {number} [Err=0.0001] - The maximum acceptable difference between the two numbers.
* @returns {boolean} Returns true if the two numbers are approximately equal within the specified error margin, otherwise false.
*/
const isApproximatlyEqual = (a, b, Err = 0.0001) => {
return Math.abs(a - b) <= Err;
};
/** @module Math */
/**
* Computes the cartesian product of two arrays.
* @param {Array} a - The first array.
* @param {Array} b - The second array.
* @returns {Array} Returns an array representing the cartesian product of the input arrays.
*/
const cartesianProduct = (a, b) => a.reduce((p, x) => [...p, ...b.map((y) => [x, y])], []);
/**
* Computes the greatest common divisor (GCD) of two numbers.
* @param {number} n1 - The first number.
* @param {number} n2 - The second number.
* @returns {number} Returns the greatest common divisor of the two input numbers.
*/
const pgcd = (n1, n2) => {
let i,
pgcd = 1;
if (n1 == floor(n1) && n2 == floor(n2)) {
for (i = 2; i <= n1 && i <= n2; ++i) {
if (n1 % i == 0 && n2 % i == 0) pgcd = i;
}
return pgcd;
} else console.log("error");
};
/**
* Computes the least common multiple (LCM) of two numbers.
* @param {number} n1 - The first number.
* @param {number} n2 - The second number.
* @returns {number} Returns the least common multiple of the two input numbers.
*/
const ppcm = (n1, n2) => {
let ppcm;
if (n1 == floor(n1) && n2 == floor(n2)) {
ppcm = n1 > n2 ? n1 : n2;
while (true) {
if (ppcm % n1 == 0 && ppcm % n2 == 0) break;
++ppcm;
}
return ppcm;
} else console.log("error");
};
const Utils$1={
add,
sub,
mul,
div,
modulo,
zeros,
ones,
nums,
norm,
lerp,
map,
clamp,
arange,
linspace,
logspace,
geomspace,
sum,
prod,
accum,
cartesianProduct,
ppcm,
pgcd,
deg2rad,
rad2deg,
inRange,
isApproximatlyEqual
};
var __Utils__ = /*#__PURE__*/Object.freeze({
__proto__: null,
Utils: Utils$1,
add: add,
arange: arange,
cartesianProduct: cartesianProduct,
clamp: clamp,
deg2rad: deg2rad,
div: div,
geomspace: geomspace,
inRange: inRange,
isApproximatlyEqual: isApproximatlyEqual,
lerp: lerp,
linspace: linspace,
logspace: logspace,
map: map,
mapfun: mapfun$1,
modulo: modulo,
mul: mul,
norm: norm,
nums: nums,
ones: ones,
pgcd: pgcd,
ppcm: ppcm,
prod: prod,
rad2deg: rad2deg,
sub: sub,
sum: sum,
zeros: zeros
});
const powerSet=originalSet=>{
const subSets = [];
const NUMBER_OF_COMBINATIONS = 2 ** originalSet.length;
for (let i = 0; i < NUMBER_OF_COMBINATIONS; i += 1) {
const subSet = [];
for (let j = 0; j < originalSet.length; j += 1) {
if (i & (1 << j)) {
subSet.push(originalSet[j]);
}
}
subSets.push(subSet);
}
return subSets;
};
// const subSet = (...arr) => {
// let list = arange(0, 2 ** arr.length, 1);
// let bin = list.map((n) => n.toString(2).padStart(arr.length, '0')).map((n) => n.split("").map((n) => +n));
// let sub = bin.map((n) => n.map((m, i) => (m === 1 ? arr[i] : null))).map((n) => n.filter((x) => x !== null));
// return sub;
// };
const subSet = null;
const Base={
_mode:Number,
_map:function(func,number,toBase){
if (number instanceof Matrix)
return new Matrix(
number.rows,
number.cols,
number.arr.flat(1).map(n=>func(n,toBase))
);
else if (number instanceof Complex) return new Complex(func(number.a,toBase),func(number.b,toBase));
else if (number instanceof Array) return number.map((n) =>func(n,toBase));
},
dec2base(dec,base){
base<=10?this._mode=Number:this._mode=String;
//this._mode=String
if (typeof dec === "number") return this._mode((dec >>> 0).toString(base));
return this._map(this.dec2base,dec,base)
},
dec2bin(dec){
return this.dec2base(dec,2);
},
dec2oct(dec){
return this.dec2base(dec,8);
},
dec2hex(dec){
return this.dec2base(dec,16);
},
bin2base(bin, base) {
return this.dec2base(this.bin2dec(bin),base)
},
bin2dec(bin){
return this._mode("0b"+bin);
},
bin2oct(bin){
return this.bin2base(bin,8);
},
bin2hex(bin){
return this.bin2base(bin,16);
},
oct2dec(oct){
return this._mode("0o"+oct);
},
oct2bin(oct){
return this.dec2bin(this.oct2dec(oct))
},
oct2hex(oct){
return this.dec2hex(this.oct2dec(oct))
},
oct2base(oct, base) {
return this.dec2base(this.oct2dec(oct),base)
},
hex2dec(hex){
return this._mode("0x"+hex);
},
hex2bin(hex){
return this.dec2bin(this.hex2dec(hex))
},
hex2oct(hex){
return this.dec2oct(this.hex2dec(hex))
},
hex2base(hex, base) {
return this.dec2base(this.hex2dec(hex),base)
},
IEEE32toDec(Bin){
let IEEE32=Bin.split(" ").join("").padEnd(32,"0");
let s=IEEE32[0];
let e=2**(+("0b"+IEEE32.slice(1,9))-127);
let m=IEEE32.slice(9,32).split("").map(n=>+n);
let M=m.map((n,i)=>n*(2**(-i-1))).reduce((a,b)=>a+b,0);
let dec=(-1)**s*(1+M)*e;
return dec
},
IEEE64toDec(Bin){
let IEEE64=Bin.split(" ").join("").padEnd(64,"0");
let s=IEEE64[0];
let e=2**(+("0b"+IEEE64.slice(1,12))-1023);
let m=IEEE64.slice(13,64).split("").map(n=>+n);
let M=m.map((n,i)=>n*(2**(-i-1))).reduce((a,b)=>a+b,0);
let dec=(-1)**s*(1+M)*e;
return dec;
}
};
const Logic$1={
_mode:Number,
_map:function(func,a,b){
if (a instanceof Matrix)
return new Matrix(
a.rows,
a.cols,
a.arr.flat(1).map((n) => func(n, b))
);
else if (a instanceof Complex) return new Complex(func(a.a, b), func(a.b, b));
else if (a instanceof Array) return a.map((n) => func(n, b));
},
not:function(input){
if(["number","boolean"].includes(typeof input)) return Logic$1._mode(!input);
else return this._map(this.not,input)
},
and:function(a, ...b){
if(["number","boolean"].includes(typeof a))return Logic$1._mode(b.reduce((n, m) => (n &= m), a));
else return this._map(this.and,a,b)
},
or:function(a, ...b) {
if(["number","boolean"].includes(typeof a)) return Logic$1._mode(b.reduce((n, m) => (n |= m), a));
else return this._map(this.or,a,b);
},
nand:function(a, ...b) {
return this.not(this.and(a, b));
},
nor:function(a, ...b) {
return this.not(this.or(a, b));
},
xor:function(a,...b){
let arr=[a,...b];
if(["number","boolean"].includes(typeof a))return this._mode(arr.reduce((length,cur)=>{
if(+cur===1)length+=1;
return length;
},0)===1);
else return this._map(this.xor,a,b);
},
xnor:function(a,...b){
return Logic$1.not(Logic$1.xor(a,b))
}
};
class Permutation {
static withDiscount(arr, l = arr.length) {
if (l === 1) return arr.map((n) => [n]);
const permutations = [];
let smallerPermutations;
smallerPermutations = this.withDiscount(arr, l - 1);
arr.forEach((currentOption) => {
smallerPermutations.forEach((smallerPermutation) => {
permutations.push([currentOption].concat(smallerPermutation));
});
});
return permutations;
}
static withoutDiscount(arr) {
const l = arr.length;
if (l === 1) return arr.map((n) => [n]);
const permutations = [];
const smallerPermutations = this.withoutDiscount(arr.slice(1));
const firstOption = arr[0];
for (let i = 0; i < smallerPermutations.length; i++) {
const smallerPermutation = smallerPermutations[i];
for (let j = 0; j <= smallerPermutation.length; j++) {
const permutationPrefix = smallerPermutation.slice(0, j);
const permutationSuffix = smallerPermutation.slice(j);
permutations.push(permutationPrefix.concat([firstOption], permutationSuffix));
}
}
return permutations;
}
}
class Combinaison {
static withDiscount(comboOptions, comboLength) {
if (comboLength === 1) {
return comboOptions.map((comboOption) => [comboOption]);
}
const combos = [];
comboOptions.forEach((currentOption, optionIndex) => {
const smallerCombos = this.withDiscount(comboOptions.slice(optionIndex), comboLength - 1);
smallerCombos.forEach((smallerCombo) => {
combos.push([currentOption].concat(smallerCombo));
});
});
return combos;
}
static withoutDiscount(comboOptions, comboLength) {
if (comboLength === 1) {
return comboOptions.map((comboOption) => [comboOption]);
}
const combos = [];
comboOptions.forEach((currentOption, optionIndex) => {
const smallerCombos = this.withoutDiscount(comboOptions.slice(optionIndex + 1), comboLength - 1);
smallerCombos.forEach((smallerCombo) => {
combos.push([currentOption].concat(smallerCombo));
});
});
return combos;
}
}
const combinaison=(comboOptions, comboLength, discount=false)=>Combinaison[discount?"withDiscount":"withoutDiscount"](comboOptions, comboLength);
var __Discrect__ = /*#__PURE__*/Object.freeze({
__proto__: null,
Base: Base,
Combinaison: Combinaison,
Logic: Logic$1,
Permutation: Permutation,
combinaison: combinaison,
powerSet: powerSet,
subSet: subSet
});
class Random {
static float(a = 1, b) {
return b ? Math.random() * (b - a) + a : a * Math.random();
}
static int(a, b) {
return Math.floor(this.float(a, b));
}
static char(upperCase){
upperCase=upperCase??this.bool();
const Char=String.fromCharCode(this.int(97,120));
return upperCase?Char.toUpperCase():Char;
}
static bool(){
return [false,true][Math.floor(Math.random()*2)];
}
static string(length,upperCase){
return length instanceof Array?
new Array(this.int(...length)).fill(0).map(() => this.char(upperCase)).join(""):
new Array(length).fill(0).map(() => this.char(upperCase)).join("");
}
static bin() {
return this.int(2);
}
static oct() {
return this.int(8);
}
static dec() {
return this.int(8);
}
static hex() {
return this.int(16);
}
static choice(choices = [1, 2, 3], p = new Array(choices.length).fill(1 / choices.length)) {
let newchoice = new Array(100);
p=Utils$1.accum(...p).map(n=>n*100);
newchoice.fill(choices[0], 0, p[0]);
for (let i = 1; i < choices.length; i++) newchoice.fill(choices[i], p[i - 1], p[i]);
return newchoice[this.int(newchoice.length - 1)];
}
static shuffleArr(arr){
return arr.sort(()=>0.5-Math.random())
}
static shuffleMatrix(M){
const {rows,cols,arr}=M;
return matrix(rows,cols,arr.flat().sort(()=>0.5-Math.random()))
}
static floats(n, a, b) {
return new Array(n).fill(0).map(() => this.float(a, b));
}
static ints(n, a, b) {
return new Array(n).fill(0).map(() => this.int(a, b));
}
static bools(n){
return new Array(n).fill(0).map(() => this.bool());
}
static bins(n) {
return new Array(n).fill(0).map(() => this.int(2));
}
static octs(n) {
return new Array(n).fill(0).map(() => this.int(8));
}
static decs(n) {
return new Array(n).fill(0).map(() => this.int(10));
}
static hexs(n) {
return new Array(n).fill(0).map(() => this.int(16));
}
static choices(n, choices, p) {
return new Array(n).fill(0).map(() => this.choice(choices, p));
}
static perm(...arr) {
// permutation
return arr.permS[this.int(arr.length)];
}
static color() {
return "#" + Base.dec2hex(this.float(16777216)).padStart(6,0);
}
static colors(n) {
return new Array(n).fill(null).map(()=>this.color());
}
static complex(a = [0,1], b = [0,1]) {
return a instanceof Array?
new Complex(
this.float(a[0], a[1]),
this.float(b[0], b[1])
):
new Complex(
...this.floats(2,a,b)
)
}
static complexInt(a = [0,1], b = [0,1]) {
return new Complex(
this.int(a[0], a[1]),
this.int(b[0], b[1])
);
}
static complexBin() {
return new Complex(...this.bins(2));
}
static complexOct() {
return new Complex(...this.octs(2));
}
static complexDec() {
return new Complex(...this.decs(10));
}
static complexHex() {
return new Complex(...this.octs(2));
}
static complexes(n, a = 0, b = 1) {
return new Array(n).fill(0).map(() => this.complex(a, b));
}
static complexesInt(n, a = 0, b = 1) {
return new Array(n).fill(0).map(() => this.complexInt(a, b));
}
static complexesBin(n) {
return new Array(n).fill(0).map(() => this.complexBin());
}
static complexesOct(n) {
return new Array(n).fill(0).map(() => this.complexOct());
}
static complexesDec(n) {
return new Array(n).fill(0).map(() => this.complexDec());
}
static complexesHex(n) {
return new Array(n).fill(0).map(() => this.complexHex());
}
static matrix(r,c,min,max){
return matrix(r,c,this.floats(r*c,min,max))
}
static matrixInt(r,c,min,max){
return matrix(r,c,this.ints(r*c,min,max))
}
static matrixBin(r,c){
return matrix(r,c,this.bins(r*c))
}
static matrixOct(r,c){
return matrix(r,c,this.octs(r*c))
}
static matrixDec(r,c){
return matrix(r,c,this.decs(r*c))
}
static matrixHex(r,c){
return matrix(r,c,this.hex(r*c))
}
static matrixColor(r,c){
return matrix(r,c,this.colors(r*c))
}
static matrixComplex(r,c,a,b){
return matrix(r,c,this.complexes(r*c,a,b))
}
static matrixComplexInt(r,c,a,b){
return matrix(r,c,this.complexesInt(r*c,a,b))
}
static matrixComplexBin(r,c){
return matrix(r,c,this.complexesBin(r*c))
}
static matrixComplexOct(r,c){
return matrix(r,c,this.complexesBin(r*c))
}
static matrixComplexDec(r,c){
return matrix(r,c,this.complexesBin(r*c))
}
static matrixComplexHex(r,c){
return matrix(r,c,this.complexesBin(r*c))
}
}
var __Random__ = /*#__PURE__*/Object.freeze({
__proto__: null,
Random: Random
});
const preload=(url)=>{
const xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.send();
if (xhr.status === 200) {
return xhr.responseText;
} else {
throw new Error(`Failed to fetch data from ${url}. Status: ${xhr.status}`);
}
};
async function fetchdom(url='https://github.com/zakarialaoui10'){
const data=await fetch(url);
const html=await data.text();
const dom= new DOMParser().parseFromString(html,'text/xml');
return dom.documentElement
}
function fetchdomSync(url='https://github.com/zakarialaoui10'){
const data=preload(url);
const dom= new DOMParser().parseFromString(data,'text/xml');
return dom.documentElement;
}
globalThis.fetchdom=fetchdom;
globalThis.fetchdomSync=fetchdomSync;
var Api = /*#__PURE__*/Object.freeze({
__proto__: null,
preload: preload
});
const csv2arr = (csv, delimiter = ",")=>csv.trim().trimEnd().split("\n").map(n=>n.split(delimiter));
const csv2matrix = (csv, delimiter = ",")=>new Matrix(csv2arr(csv,delimiter));
const csv2object = (csv, delimiter = ",") => {
const [header, ...rows] = csv2arr(csv,delimiter);
const result = rows.map(row => {
const obj = {};
header.forEach((key, index) => {
obj[key] = row[index];
});
return obj;
});
return result;
};
const csv2json = (csv, delimiter = ",") => JSON.stringify(csv2object(csv,delimiter));
const csv2sql=(csv, Table)=>{
const lines = csv.trim().trimEnd().split('\n').filter(n=>n);
const columns = lines[0].split(',');
let sqlQuery = `INSERT INTO ${Table} (${columns.join(', ')}) Values `;
let sqlValues = [];
for (let i = 1; i < lines.length; i++) {
const values = lines[i].split(',');
sqlValues.push(`(${values})`);
}
return sqlQuery+sqlValues.join(",\n");
};
const _objects2arr=data=>data instanceof Array?[Object.keys(data[0]),...data.map(n=>Object.values(n))]:[Object.keys(data)];
const _objects2csv=(data,delimiter)=>_objects2arr(data).map(n=>n.join(delimiter)).join("\n");
const json2arr=json=>json instanceof Object?_objects2arr(json):_objects2arr(JSON.parse(json));
const json2csv=(json,delimiter=",")=>json instanceof Object?_objects2csv(json,delimiter):_objects2csv(JSON.parse(json),delimiter);
const json2csvFile=(json,delimiter)=>{
const str=json2csv(json,delimiter);
const blob=new Blob([str], { type: 'text/csv;charset=utf-8;' });
return {
str,
blob,
url:URL.createObjectURL(blob)
}
};
const _processObject=(obj, indent)=>{
const yml = [];
if (Array.isArray(obj)) {
obj.forEach(item => {
if (typeof item === 'object' && item !== null) {
yml.push(`${indent}-`);
const nestedLines = _processObject(item, `${indent} `);
yml.push(...nestedLines);
} else yml.push(`${indent}- ${item}`);
});
} else {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
if (typeof value === 'object' && value !== null) {
yml.push(`${indent}${key}:`);
const nestedLines = _processObject(value, `${indent} `);
yml.push(...nestedLines);
} else {
yml.push(`${indent}${key}: ${value}`);
}
}
}
}
return yml;
};
const _object2yml=(object,indent="")=>_processObject(object,indent).join('\n');
const json2yml=(json,indent)=>json instanceof Object?_object2yml(json,indent):_object2yml(JSON.parse(json),indent);
const json2ymlFile=(json,indent)=>{
const str=json2yml(json,indent);
const blob=new Blob([str], { type: 'text/yml;charset=utf-8;' });
return {
str,
blob,
url:URL.createObjectURL(blob)
}
};
const json2xml=(json, indent = 1)=>{
let xml = '';
for (const key in json) {
if (json.hasOwnProperty(key)) {
const value = json[key];
xml += '\n' + ' '.repeat(indent) + `<${key}>`;
(typeof value === 'object') ? xml += json2xml(value, indent + 2) : xml += `${value}`;
xml += `</${key}>`;
}
}
return xml.trim();
};
const json2xmlFile=(json,indent)=>{
const str=json2xml(json,indent);
const blob=new Blob([str], { type: 'text/xml;charset=utf-8;' });
return {
str,
blob,
url:URL.createObjectURL(blob)
}
};
class ZikoUINode {
constructor(node){
this.cache = {
node
};
}
isZikoUINode(){
return true
}
get node(){
return this.cache.node;
}
}
globalThis.node = (node) => new ZikoUINode(node);
const DomMethods = {
append(...ele) {
__addItem__.call(this, "append", "push", ...ele);
return this;
},
prepend(...ele) {
this.__addItem__.call(this, "prepend", "unshift", ...ele);
return this;
},
insertAt(index, ...ele) {
if (index >= this.element.children.length) this.append(...ele);
else
for (let i = 0; i < ele.length; i++) {
if (["number", "string"].includes(typeof ele[i])) ele[i] = text(ele[i]);
this.element?.insertBefore(ele[i].element, this.items[index].element);
this.items.splice(index, 0, ele[i]);
}
return this;
},
remove(...ele) {
const remove = (ele) => {
if (typeof ele === "number") ele = this.items[ele];
if (ele?.isZikoUIElement) this.element?.removeChild(ele.element);
this.items = this.items.filter((n) => n !== ele);
};
for (let i = 0; i < ele.length; i++) remove(ele[i]);
for (let i = 0; i < this.items.length; i++)
Object.assign(this, { [[i]]: this.items[i] });
// Remove from item
return this;
},
clear(){
this?.items?.forEach(n=>n.unrender());
this.element.innerHTML = "";
return this;
},
render(target = this.target) {
if(this.isBody)return ;
if(target?.isZikoUIElement)target=target.element;
this.target=target;
this.target?.appendChild(this.element);
return this;
},
unrender(){
if(this.cache.parent)this.cache.parent.remove(this);
else if(this.target?.children?.length && [...this.target?.children].includes(this.element)) this.target.removeChild(this.element);
return this;
},
renderAfter(t = 1) {
setTimeout(() => this.render(), t);
return this;
},
unrenderAfter(t = 1) {
setTimeout(() => this.unrender(), t);
return this;
},
after(ui){
if(ui?.isZikoUIElement) ui=ui.element;
this.element?.after(ui);
return this;
},
before(ui){
if(ui?.isZikoUIElement) ui=ui.element;
this.element?.before(ui);
return this;
}
};
function __addItem__(adder, pusher, ...ele) {
if (this.cache.isFrozzen) {
console.warn("You can't append new item to frozzen element");
return this;
}
for (let i = 0; i < ele.length; i++) {
if (["number", "string"].includes(typeof ele[i])) ele[i] = text(ele[i]);
if (
typeof globalThis?.Node === "function" &&
ele[i] instanceof globalThis?.Node
)
ele[i] = new this.constructor(ele[i]);
if (ele[i]?.isZikoUIElement) {
ele[i].cache.parent = this;
this.element[adder](ele[i].element);
ele[i].target = this.element;
this.items[pusher](ele[i]);
} else if (ele[i] instanceof Object) {
if (ele[i]?.style) this.style(ele[i]?.style);
if (ele[i]?.attr) {
Object.entries(ele[i].attr).forEach((n) =>
this.setAttr("" + n[0], n[1]),
);
}
}
}
this.maintain();
return this;
}
const IndexingMethods = {
at(index) {
return this.items.at(index);
},
forEach(callback) {
this.items.forEach(callback);
return this;
},
map(callback) {
return this.items.map(callback);
},
find(condition) {
return this.items.filter(condition);
},
};
const Events$1 = {
'Click' : [
'Click',
'DblClick'
],
'Ptr' : [
'PtrMove',
'PtrDown',
'PtrUp',
'PtrLeave',
'PtrEnter',
'PtrOut',
'PtrCancel'
],
'Mouse' : [
'MouseMove',
'MouseDown',
'MouseUp',
'MouseEnter',
'MouseLeave',
'MouseOut'
],
// 'Touch' : [],
'Key' : [
'KeyDown',
'KeyPress',
'KeyUp'
],
'Clipboard':[
'Copy',
'Cut',
'Paste'
],
'Focus':[
'focus',
'blur'
],
'Drag':[
"Drag",
"DragStart",
"DragEnd",
"Drop"
],
'Wheel': [
'Wheel'
]
// 'Media':[
// ],
// 'Hash':[
// "HashChange"
// ]
};
const getEvent=(event = "")=>{
if(event.startsWith("Ptr"))return `pointer${event.split("Ptr")[1].toLowerCase()}`;
return event.toLowerCase()
};
function event_controller(e, event_name, details_setter, customizer, push_object){
this.cache.currentEvent = event_name;
this.cache.event = e;
details_setter?.call(this);
customizer?.hasOwnProperty("prototype") ? customizer?.call(this) : customizer?.call(null, this);
// if(customizer?.hasOwnProperty("prototype")) customizer?.call(this)
// else customizer?.call(null, this)
if(this.cache.preventDefault[event_name]) e.preventDefault();
if(this.cache.stopPropagation[event_name]) e.stopPropagation();
if(this.cache.stopImmediatePropagation[event_name]) e.stopImmediatePropagation();
if(this.cache.stream.enabled[event_name]&&push_object)this.cache.stream.history[event_name].push(push_object);
this.cache.callbacks[event_name]?.map(n=>n(this));
}
class __ZikoEvent__ {
constructor(target = null, Events = [], details_setter, customizer){
this.target = target;
this.cache = {
currentEvent : null,
event: null,
options : {},
preventDefault : {},
stopPropagation : {},
stopImmediatePropagation : {},
event_flow : {},
paused : {},
stream : {
enabled : {},
clear : {},
history : {}
},
callbacks : {},
__controllers__:{}
};
if(Events)this._register_events(Events, details_setter, customizer);
}
_register_events(Events, details_setter, customizer, REGISTER_METHODES = true){
const events = Events?.map(n=>getEvent(n));
events?.forEach((event,i)=>{
Object.assign(this.cache.preventDefault, {[event] : false});
Object.assign(this.cache.options, {[event] : {}});
Object.assign(this.cache.paused, {[event] : false});
Object.assign(this.cache.stream.enabled, {[event] : false});
Object.assign(this.cache.stream.clear, {[event] : false});
Object.assign(this.cache.stream.history, {[event] : []});
Object.assign(this.cache.__controllers__, {[event] : e=>event_controller.call(this, e, event, details_setter, customizer)});
if(REGISTER_METHODES)Object.assign(this, { [`on${Events[i]}`] : (...callbacks)=> this.__onEvent(event, this.cache.options[event], {}, ...callbacks)});
});
return this;
}
get targetElement(){
return this.target?.element;
}
get isParent(){
return this.target?.element === this.event.srcElement;
}
get item(){
return this.target.find(n=>n.element == this.event?.srcElement)?.[0];
}
get currentEvent(){
return this.cache.currentEvent;
}
get event(){
return this.cache.event;
}
setTarget(UI){
this.target=UI;
return this;
}
__handle(event, handler, options, dispose){
this.targetElement?.addEventListener(event, handler, options);
return this;
}
__onEvent(event, options, dispose, ...callbacks){
if(callbacks.length===0){
console.log("00");
if(this.cache.callbacks[event]){
console.log("Call");
// this.cache.callbacks.map(n=>e=>n.call(this,e));
this.cache.callbacks[event].map(n=>e=>n.call(this,e));
}
else {
return this;
}
}
else this.cache.callbacks[event] = callbacks.map(n=>e=>n.call(this,e));
this.__handle(event, this.cache.__controllers__[event],options, dispose);
return this;
}
#override(methode, overrides, defaultValue){
if(defaultValue === "default") Object.assign(this.cache[methode], {...this.cache[methode], ...overrides});
const all = defaultValue === "default"
? this.cache[methode]
: Object.fromEntries(Object.keys(this.cache.preventDefault).map(n=>[n,defaultValue]));
Object.assign(this.cache[methode], {...all,...overrides});
return this
}
preventDefault(overrides = {}, defaultValue = "default"){
this.#override("preventDefault", overrides, defaultValue);
// const all=Object.fromEntries(Object.keys(this.cache.preventDefault).map(n=>[n,defaultValue]))
// Object.assign(this.cache.preventDefault, {...all,...overrides});
return this;
}
stopPropagation(overrides = {}, defaultValue = "default"){
this.#override("stopPropagation", overrides, defaultValue);
return this;
}
stopImmediatePropagation(overrides = {}, defaultValue = "default"){
this.#override("stopImmediatePropagation", overrides, defaultValue);
return this;
}
setEventOptions(event, options){
this.pause({[event] : true, }, "default");
Object.assign(this.cache.options[getEvent(event)], options);
this.resume({[event] : true, }, "default");
return this;
}
pause(overrides = {}, defaultValue = "default"){
const all = defaultValue === "default"
? this.cache.stream.enabled
: Object.entries(Object.keys(this.cache.stream.enabled).map(n=>[n,defaultValue]));
overrides={...all,...overrides};
for(let key in overrides){
if(overrides[key]){
this.targetElement?.removeEventListener(key, this.cache.__controllers__[key], this.cache.options[key]);
this.cache.paused[key]=true;
}
}
return this;
}
resume(overrides = {}, defaultValue = "default"){
const all = defaultValue === "default"
? this.cache.stream.enabled
: Object.entries(Object.keys(this.cache.stream.enabled).map(n=>[n,defaultValue]));
overrides={...all,...overrides};
for(let key in overrides){
if(overrides[key]){
this.targetElement?.addEventListener(key,this.cache.__controllers__[key], this.cache.options[key]);
this.cache.paused[key]=false;
}
}
return this;
}
stream(overrides = {}, defaultValue = "default"){
this.cache.stream.t0=Date.now();
const all=Object.fromEntries(Object.keys(this.cache.stream.enabled).map(n=>[n,defaultValue]));
overrides={...all,...overrides};
Object.assign(this.cache.stream.enabled,overrides);
return this;
}
clear(){
return this;
}
dispose(overrides = {}, defaultValue = "default"){
this.pause(overrides, defaultValue);
return this;
}
}
class ZikoEventClick extends __ZikoEvent__{
constructor(target, customizer){
super(target, Events$1.Click, details_setter$a, customizer);
}
}
function details_setter$a(){
if(this.curr