### Install Zikojs
Source: https://github.com/zakarialaoui10/zikojs/blob/main/README.dep.md
This command installs the Zikojs library using npm. It is the first step to include Zikojs in your project.
```bash
npm install ziko
```
--------------------------------
### File-Based Routing Setup
Source: https://github.com/zakarialaoui10/zikojs/blob/main/README.dep.md
Sets up file-based routing for single-page applications using Zikojs. It dynamically imports all JavaScript files from a specified directory (e.g., './src/pages/**/*.js'), automatically generating routes based on file paths.
```javascript
import { FileBasedRouting } from "ziko";
FileBasedRouting(import.meta.glob("./src/pages/**/*.js"))
```
--------------------------------
### Declarative UI with Zikojs Hyperscript
Source: https://github.com/zakarialaoui10/zikojs/blob/main/README.md
Shows how to create UI elements declaratively using Zikojs' Hyperscript-based approach. This example defines a 'Hello' component that displays text and adds an onClick event to change the text color randomly.
```javascript
import { p, text, Random } from 'ziko'
const Hello = name => p(
text("Hello ", name)
).onClick(e => e.target.style({color : Random.color()}))
```
--------------------------------
### Custom Markdown Parser Usage (Mdzjs)
Source: https://github.com/zakarialaoui10/zikojs/blob/main/README.dep.md
Example of using Zikojs' custom markdown parser, Mdzjs. It shows how to include frontmatter (like title) and import Zikojs components within markdown files, allowing for rich content generation.
```markdown
---
title : Article 1
---
import InteractiveBlock from "./InteractiveBlock";
# Hello World this is markdown heading
```
--------------------------------
### State Management with Zikojs Hooks
Source: https://github.com/zakarialaoui10/zikojs/blob/main/README.md
Illustrates Zikojs' built-in state management using 'useState' and 'useDerived' hooks. This example creates a timer that displays elapsed time in an HH:MM:SS format, updating every second.
```javascript
import { tags } from 'ziko/ui'
import { useState, useDerived } from 'ziko/hooks'
const [timer, setTimer] = useState(0);
const converToHMS = seconds => `${Math.floor(seconds / 3600)} : ${Math.floor((seconds % 3600) / 60)} : ${seconds % 60} `
const [time] = useDerived(t => converToHMS(t) , [timer] )
tags.p('Elapsed Time : ', time)
let i = 1;
setInterval(()=>{
setTimer(i);
i++
}, 1000)
```
--------------------------------
### Create Heading Elements (JavaScript)
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIElements/Primitves/text.html
Provides examples for creating different levels of heading elements (h1 to h6) using ZikoJS. Each function takes a single string argument representing the text content of the heading.
```javascript
h1(text : string)
h2(text : string)
h3(text : string)
h4(text : string)
h5(text : string)
h6(text : string)
```
--------------------------------
### Flexible Math Functions with Zikojs
Source: https://github.com/zakarialaoui10/zikojs/blob/main/README.md
Demonstrates Zikojs' flexible math utilities, particularly the 'mapfun' function, which applies mathematical operations to complex data structures. This example shows the 'cos' function handling various input types and how to create custom flexible math functions.
```javascript
import { cos, PI, mapfun } from "ziko";
const result = cos(PI, PI / 2, PI / 4, [PI / 6, PI / 3], {
x: PI / 2,
y: PI / 4,
z: [0, PI / 12],
}
);
/*
result =>
[
-1,
0,
0.707106781186548,
[0.866025403784439, 0.5],
{
x: 0,
y: 0.707106781186548,
z: [1, 0.965925826289068],
},
];
*/
// console.log(result)
const parabolic_func = (a, b, c, x) => a * x ** 2 + b * x + c;
const map_parabolic_func =
(a, b, c) =>
(...X) =>
mapfun((n) => parabolic_func(a, b, c, n), ...X);
const a = -1.5,
b = 2,
c = 3;
const X = [0, 1, 2, 3];
console.log(parabolic_func(a, b, c)(X));
// [3,3,1,3]
```
--------------------------------
### Create Heading Elements (H1-H6) with ZikoJS
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIElements/Primitves/text.md
Provides examples for creating different levels of heading elements (h1 through h6) using their respective ZikoJS functions. Each function takes a string argument representing the heading text.
```javascript
const heading1 = h1("Main Title");
const heading2 = h2("Section Title");
const heading3 = h3("Subsection Title");
const heading4 = h4("Level 4 Heading");
const heading5 = h5("Level 5 Heading");
const heading6 = h6("Level 6 Heading");
```
--------------------------------
### JavaScript Screen Observer Class and Watcher Function
Source: https://github.com/zakarialaoui10/zikojs/blob/main/src/reactivity/observer/screen.js.txt
Defines the ZikoScreenObserver class for tracking screen position. It includes getters for screen coordinates, mapped values, and screen center. The `start` method sets up a time loop to detect changes and trigger a callback. The `watchScreen` function is a factory for creating observers.
```javascript
import { useTimeLoop } from "../../Time";
import {
map,
complex,
} from "../../Math";
class ZikoScreenObserver {
constructor(callback=e=>console.log({x:e.x,y:e.y})) {
this.previousX = globalThis?.screenX;
this.previousY = globalThis?.screenY;
this.view=[-1,-1,1,1];
this.start(callback);
}
get xMin(){
return this.view[0];
}
get yMin(){
return this.view[1];
}
get xMax(){
return this.view[2];
}
get yMax(){
return this.view[3];
}
get x(){
return globalThis?.screenX;
}
get y(){
return globalThis?.screenY;
}
get scx(){
return screen.availWidth/2;
}
get scy(){
return screen.availHeight/2;
}
get wcx(){
return screenX+globalThis?.innerWidth/2;
}
get wcx_v(){
return map(this.wcx,0,screen.availWidth,this.view[0],this.view[2]);
}
get wcy(){
return screenY+globalThis?.innerHeight/2;
}
get wcy_v(){
return -map(this.wcy,0,screen.availHeight,this.view[1],this.view[3]);
}
get dx(){
return map(this.x,0,screen.availWidth,this.xMin,this.xMax);
}
get dy(){
return map(this.y,0,screen.availHeight,this.yMin,this.yMax);
}
start(callback){
this.loop = useTimeLoop(()=>{
let currentX = globalThis?.screenX;
let currentY = globalThis?.screenY;
if (this.previousX !== currentX || this.previousY !== currentY) {
callback(this)
this.previousX = currentX;
this.previousY = currentY;
}
},1000/60,0,Infinity,true);
return this;
}
}
const watchScreen=(callback)=>new ZikoScreenObserver(callback);
// globalThis.watchScreen=watchScreen;
export{
watchScreen
}
```
--------------------------------
### Creating Custom Functions with ZikoJS `mapfun`
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/Math/1- functions.md
Illustrates how to create custom, reusable functions in zikojs using the `mapfun` utility. This example defines a parabolic function and then uses `mapfun` to apply it to various data structures, similar to how built-in functions operate.
```javascript
import {mapfun} from "ziko";
// Define a standard parabolic function
const parabolic_func = (a, b, c, x) => a * (x ** 2) + b * x + c;
// Create a zikojs-compatible function using mapfun
const parabol = (a, b, c, ...X) => mapfun(n => parabolic_func(a, b, c, n), ...X);
const a = -1.5, b = 2, c = 3;
const X0 = [0, 1, 2, 3];
const X1 = { x10: 0, x11: 1, x12: 2, x13: 3 };
console.log(parabol(a, b, c, X0));
// Output: [3, 3, 1, -3]
console.log(parabol(a, b, c, X1));
// Output: { x10: 3, x11: 3, x12: 1, x13: -3 }
console.log(parabol(a, b, c, X0, X1));
/* Output:
[
[3, 3, 1, -3],
{ x10: 3, x11: 3, x12: 1, x13: -3 }
]
*/
```
--------------------------------
### Manage Reactive State with ZikoJS useState Hook
Source: https://context7.com/zakarialaoui10/zikojs/llms.txt
Implements a core state management hook using a subscriber pattern for reactive UI updates. Provides methods to get, set, pause, resume, and force state changes. Depends on 'ziko/hooks'.
```javascript
import { useState } from 'ziko/hooks'
const [getValue, setValue, controller] = useState(0)
// Get current value
const currentValue = getValue().value // 0
// Set new value
setValue(10)
setValue(prev => prev + 1) // Functional update
// Controller methods
controller.pause() // Pause updates
controller.resume() // Resume updates
controller.force(100) // Force update even if paused
controller.clear() // Clear all subscribers
// Complete example with UI
const [count, setCount] = useState(0)
tags.div(
tags.p("Count: ", count),
tags.button("Increment").onClick(() => setCount(n => n + 1)),
tags.button("Decrement").onClick(() => setCount(n => n - 1))
).render(document.body)
```
--------------------------------
### Get UI Element Content (JavaScript)
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/1- ZikoUIElement.md
Retrieves the HTML or Text content of a UI element. This is useful for accessing and manipulating the inner content of elements.
```javascript
let htmlContent = uiElement.html(); // Get HTML content
let textContent = uiElement.text(); // Get Text content
```
--------------------------------
### ZikoJS: RTL/LTR Style Switching
Source: https://github.com/zakarialaoui10/zikojs/blob/main/src/ui/constructors/_m.js.txt
The `get #SwitchedStyleRTL_LTR` private getter calculates and returns an object containing style properties swapped for RTL/LTR layout. This is used by `useRtl` and `useLtr` methods. It handles margins, paddings, text alignment, float, border-radius, and flexbox justify-content. It does not have external dependencies beyond standard browser DOM APIs.
```javascript
class Ziko{
get #SwitchedStyleRTL_LTR(){
const CalculedStyle = globalThis.getComputedStyle(this.element);
const SwitchedStyle = {}
if(CalculedStyle.marginRight!=="0px")Object.assign(SwitchedStyle, {marginLeft: CalculedStyle.marginRight});
if(CalculedStyle.marginLeft!=="0px")Object.assign(SwitchedStyle, {marginRight: CalculedStyle.marginLeft});
if(CalculedStyle.paddingRight!=="0px")Object.assign(SwitchedStyle, {paddingLeft: CalculedStyle.paddingRight});
if(CalculedStyle.paddingLeft!=="0px")Object.assign(SwitchedStyle, {paddingRight: CalculedStyle.paddingLeft});
if(CalculedStyle.left!=="0px")Object.assign(SwitchedStyle, {right: CalculedStyle.left});
if(CalculedStyle.right!=="0px")Object.assign(SwitchedStyle, {left: CalculedStyle.right});
if(CalculedStyle.textAlign === "right")Object.assign(SwitchedStyle, {textAlign: "left"});
if(CalculedStyle.textAlign === "left")Object.assign(SwitchedStyle, {textAlign: "right"});
if(CalculedStyle.float === "right")Object.assign(SwitchedStyle, {float: "left"});
if(CalculedStyle.float === "left")Object.assign(SwitchedStyle, {float: "right"});
if(CalculedStyle.borderRadiusLeft!=="0px")Object.assign(SwitchedStyle, {right: CalculedStyle.borderRadiusRight});
if(CalculedStyle.borderRadiusRight!=="0px")Object.assign(SwitchedStyle, {right: CalculedStyle.borderRadiusLeft});
if(["flex","inline-flex"].includes(CalculedStyle.display)){
if(CalculedStyle.justifyContent === "flex-end")Object.assign(SwitchedStyle, {justifyContent: "flex-start"});
if(CalculedStyle.justifyContent === "flex-start")Object.assign(SwitchedStyle, {justifyContent: "flex-end"});
}
return SwitchedStyle;
}
}
```
--------------------------------
### Single Page Application Routing with Zikojs
Source: https://github.com/zakarialaoui10/zikojs/blob/main/README.md
Demonstrates how to set up a single-page application (SPA) with file-based routing using Zikojs. This code snippet initializes the routing by importing all `.js` files from the `./pages` directory.
```javascript
import { FileBasedRouting } from "ziko";
FileBasedRouting(import.meta.glob("./pages/**/*.js"))
```
--------------------------------
### Styling UI Elements with ZikoJS (JavaScript)
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/1- ZikoUIElement.md
Demonstrates different ways to apply styles to UI elements using ZikoJS. Method 1 uses a style object, Method 2 uses individual style setters, and Method 3 hints at dynamic updates.
```javascript
// Method 1: Using a style object
let txt1 = text("Hello World !");
txt1.style({
color: "darkblue",
background: "gold"
});
// Method 2: Using individual style setters
let txt2 = text("Hello World !");
txt2.st.color("darkblue");
txt2.st.background("darkblue");
// Method 3: Dynamic Update (Conceptual)
let txt3 = text("Hello World !");
// ... further dynamic styling operations would follow here
```
--------------------------------
### Create UIElement Instance
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/1- ZikoUIElement.md
Demonstrates how to instantiate a new UIElement. The `element` parameter can be either an HTML tag string or an existing DOM element. This is the primary way to begin working with UI elements in zikojs.
```javascript
const UI = new UIElement(element);
// element can be an HTML tag string or a DOM element.
```
--------------------------------
### Discrete Mathematics Utilities in JavaScript
Source: https://context7.com/zakarialaoui10/zikojs/llms.txt
Offers utilities for base conversions (decimal, binary, hexadecimal), combinatorics (combinations and permutations), and set operations like generating the power set and subsets.
```javascript
import { Base, Permutation, Combinaison, powerSet, subSet } from 'ziko'
// Base conversions
Base.dec2bin(10) // "1010"
Base.dec2hex(255) // "FF"
Base.bin2dec("1010") // 10
Base.hex2dec("FF") // 255
// Combinatorics
Combinaison(5, 2) // C(5,2) = 10
Permutation(5, 2) // P(5,2) = 20
Combinaison(10, 3) // C(10,3) = 120
// Set operations
powerSet([1, 2, 3])
// [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]
subSet([1,2,3,4], 2)
// All 2-element subsets: [[1,2], [1,3], [1,4], [2,3], [2,4], [3,4]]
```
--------------------------------
### Traditional SPA Routing with ZikoJS
Source: https://context7.com/zakarialaoui10/zikojs/llms.txt
Sets up traditional Single-Page Application routing with manual route definitions and support for dynamic parameters. It utilizes the `SPA` module from `ziko` and requires a target DOM element.
```javascript
import { SPA } from 'ziko'
// Define routes and their components
const HomePage = () => tags.div(tags.h1("Home"))
const AboutPage = () => tags.div(tags.h1("About"))
const UserPage = (id) => tags.div(tags.h1(`User ${id}`))
const NotFoundPage = () => tags.div(tags.h1("404 Not Found"))
SPA({
target: document.body,
routes: {
"/": HomePage,
"/about": AboutPage,
"/user/:id": (params) => UserPage(params.id),
"404": NotFoundPage
},
wrapper: tags.section()
})
```
--------------------------------
### File-based Routing with ZikoJS
Source: https://context7.com/zakarialaoui10/zikojs/llms.txt
Implements Next.js-style file-based routing by automatically discovering routes from the file structure. It supports dynamic parameters and a 404 handler. Requires `ziko` library.
```javascript
import { FileBasedRouting } from 'ziko'
// main.js - automatically discovers routes from file structure
FileBasedRouting(import.meta.glob('./pages/**/*.js'))
// File structure determines routes:
// pages/index.js -> maps to "/"
// pages/about.js -> maps to "/about"
// pages/user/[id]/index.js -> maps to "/user/:id"
// pages/404.js -> 404 handler
// Example page: pages/user/[id]/index.js
import { tags } from 'ziko'
export default function UserPage({ params }) {
return tags.div(
tags.h1(`User Profile: ${params.id}`),
tags.p(`Viewing user with ID: ${params.id}`)
)
}
```
--------------------------------
### Create Text and Paragraph Elements in JavaScript
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIelements.md
Demonstrates how to create and style text elements, and group them within a paragraph element using ZikoJS.
```javascript
const t1 = text("Hello World")
const t2 = text("Hello from Zikojs").style({
color: "darkblue"
})
const para = p(
t1,
t2
)
```
--------------------------------
### JavaScript Definition Term Element Creation
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIElements/Primitves/text.html
Shows the creation of definition term elements using 'dfnText'. This function accepts multiple string or number arguments, joins them into a single string, and wraps it in a '' tag, signifying the first occurrence of a term.
```javascript
function dfnText(...str) {
return `${str.join('')}`;
}
const definitionTerm = dfnText("JavaScript", " is a programming language.");
console.log(definitionTerm); // Output: "JavaScript is a programming language."
```
--------------------------------
### Create Flexbox Layouts with ZikoJS Flex
Source: https://context7.com/zakarialaoui10/zikojs/llms.txt
Constructs flexbox layouts with chainable methods for positioning and styling. Facilitates responsive design by managing child element alignment and spacing. Requires the 'ziko' library.
```javascript
import { Flex } from 'ziko'
// Centered container
Flex(
tags.h1("Title"),
tags.p("Content")
)
.vertical(0, 0) // Center horizontally and vertically
.style({
width: '200px',
height: '200px',
border: '1px solid blue'
})
// Responsive horizontal layout
Flex(
tags.div("Item 1"),
tags.div("Item 2"),
tags.div("Item 3")
)
.horizontal('space-between', 'center')
.gap('10px')
.wrap(true)
```
--------------------------------
### Create and Style Paragraph with Event Listener in JavaScript using zikojs
Source: https://github.com/zakarialaoui10/zikojs/wiki/UI/UI-Overview
This snippet demonstrates how to create a paragraph element with text content, apply inline styles, and attach a pointer enter event listener to its children using the zikojs library. It highlights the dynamic nature of UI manipulation provided by zikojs.
```javascript
para=p(
text("hello"),
text("world")
)
.style({
color:"darkblue"
})
.forEach(n=>n.onPtrEnter(e=>{
console.log(e.target.element.textContent)
}));
```
--------------------------------
### Create a Collapsible Element in JavaScript
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIelements.md
Shows how to create a collapsible (accordion) element with a summary and content using ZikoJS.
```javascript
let summary = text("What is ZikoGL");
let content = p(
text(" ZikoGL is a ...")
)
Collapsible(
summary,
content
)
```
--------------------------------
### Create Tabbed Content Elements in JavaScript
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIelements.md
Illustrates the creation of tabbed content with controllers and corresponding content sections, including a vertical layout option, using ZikoJS.
```javascript
let Controllers = [
btn(1),
btn(2),
btn(3)
];
let Contents = [
p("Content 1 ..."),
p("Content 2 ..."),
p("Content 3 ...")
]
Tabs(
Controllers,
Contents
).vertical()
```
--------------------------------
### Create Button Element (JavaScript)
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIElements/Primitves/misc.md
The `btn` constructor creates a button element. It optionally accepts a string for the button's text content. This is a simple utility for generating interactive button elements.
```javascript
btn(textContent? : string)
```
--------------------------------
### UI Element CSS Transitions and Transformations (JavaScript)
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/1- ZikoUIElement.md
Provides methods for applying CSS transitions and transformations like translate, rotate, scale, and flip effects with optional timing.
```javascript
let styleInstance = uiElement.st;
// Translate
styleInstance.translate(10, 20, 5, 500); // dx, dy, dz, transitionTimming
styleInstance.translateX(50, 300); // dx, transitionTimming
styleInstance.translateY(-30, 400);
styleInstance.translateZ(100, 600);
// Rotate
styleInstance.rotateX(45, 500);
styleInstance.rotateY(90, 600);
styleInstance.rotateZ(180, 700);
// Scale
styleInstance.scale(1.5, 0.8, 400); // sx, sy, transitionTimming
styleInstance.scaleX(2, 500);
styleInstance.scaleY(0.5, 600);
// Perspective
styleInstance.perspective(800, 1000);
// Flip effects
styleInstance.flipeX(800);
styleInstance.flipeY(900);
styleInstance.flipeZ(1000);
// Fade effects
styleInstance.fadeIn(500);
styleInstance.fadeOut(700);
```
--------------------------------
### Create HTML and SVG Elements with ZikoJS Tags
Source: https://context7.com/zakarialaoui10/zikojs/llms.txt
Dynamically generates HTML and SVG elements using a proxy-based tag system. Supports attributes, children, and integration with reactive state. No external dependencies beyond the 'ziko' library.
```javascript
import { tags } from 'ziko'
const { div, p, span, button, svg, path } = tags
// Simple element creation
div("Hello world")
// With attributes and children
div({ class: "container", id: "main" },
p("Paragraph text"),
span("Inline text")
)
// SVG elements work the same way
svg({
viewBox: "0 0 24 24",
fill: "none",
width: 24,
height: 24
},
path({ d: "m14 12 4 4 4-4" })
)
// State integration with reactive updates
const [count, setCount] = useState(0)
button(count).onClick(() => setCount(n => n + 1))
```
--------------------------------
### Equivalent HTML Structure for zikojs Paragraph Creation
Source: https://github.com/zakarialaoui10/zikojs/wiki/UI/UI-Overview
This HTML snippet represents the output generated by the zikojs code. It shows a paragraph with inline styling and JavaScript to replicate the event handling logic for pointer enter events on child elements.
```html
hello
world
```
--------------------------------
### JavaScript Superscript Element Creation
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIElements/Primitves/text.html
Demonstrates the creation of superscript elements using 'supText'. This function takes an array of string or number values, joins them, and wraps the result in a '' tag, suitable for footnotes or exponents.
```javascript
function supText(sup) {
return `${sup.join('')}`;
}
const superscript = supText(["1", "st"]);
console.log(superscript); // Output: "1st"
```
--------------------------------
### Create and Style Paragraph Element with Event Listener (JavaScript)
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/0- Overview.md
This snippet demonstrates creating a paragraph element with two text nodes using zikojs. It applies a dark blue color style and adds a 'pointerenter' event listener to each child element, logging the target's text content to the console. This showcases dynamic element creation, styling, and event handling.
```javascript
para=p(
text("hello"),
text("world")
)
.style({
color:"darkblue"
})
.forEach(n=>n.onPtrEnter(e=>{
console.log(e.target.text)
}));
```
--------------------------------
### Create Main Content Area
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIElements/Primitves/semantic.md
The `Main` function creates the primary content area of a document. It accepts multiple ZikoUIElements as arguments to populate its content. This is a fundamental element for structuring semantic HTML.
```typescript
Main(...elements : ZikoUIElements[])
```
--------------------------------
### Drawing on Canvas with Pointer Events
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/1- ZikoUIElement.md
Implements a simple paint application on a canvas element using pointer events. It captures pointer down, move, and up events to draw lines and manage the drawing state. The pointer coordinates are mapped to a custom coordinate system.
```javascript
Scene = Canvas("500px", "500px")
.onPtrDown((e) => {
e.target.ctx.beginPath();
e.target.ctx.moveTo(
map(e.dx, 0, e.target.width, e.target.Xmin, e.target.Xmax),
map(e.dy, 0, e.target.height, e.target.Ymin, e.target.Ymax),
);
})
.onPtrMove((e) => {
if (e.isDown) {
const x = map(e.mx, 0, e.target.width, e.target.Xmin, e.target.Xmax);
const y = map(e.my, 0, e.target.height, e.target.Ymax, e.target.Ymin);
e.target.append(
canvasCircle(x, y, 1).color({ fill: "#5555AA" }).fill(),
);
}
})
.onPtrUp(() => {});
```
--------------------------------
### ZikoJS mapfun with currying syntax
Source: https://github.com/zakarialaoui10/zikojs/wiki/1-Math/Math-Functions
Demonstrates the use of currying with ZikoJS's `mapfun` utility. This allows for a more functional programming approach, where parameters for the mathematical function are applied sequentially before the data structure is processed.
```javascript
import {mapfun} from "ziko";
const parabolic_func=(a,b,c,x)=>a*(x**2)+b*x+c;
const map_parabolic_func=(a,b,c)=>(...X)=>mapfun(n=>parabolic_func(a,b,c,n),...X);
const a=-1.5,b=2,c=3;
const X=[0,1,2,3];
console.log(parabolic_func(a,b,c)(X));
```
--------------------------------
### Event Handling with ZikoJS tags
Source: https://context7.com/zakarialaoui10/zikojs/llms.txt
Provides chainable methods for attaching various event listeners to DOM elements created with `ziko.tags`. Supports common pointer, keyboard, and focus events, as well as custom event emission and listening.
```javascript
import { tags } from 'ziko'
tags.button("Interactive Element")
.onClick((e) => console.log("Clicked!", e))
.onDblClick(() => console.log("Double clicked"))
.onPtrDown((e) => console.log("Pointer down at", e.clientX, e.clientY))
.onPtrMove((e) => console.log("Moving pointer"))
.onPtrUp((e) => console.log("Pointer up"))
.onKeyPress((e) => console.log("Key pressed:", e.key))
.onFocus(() => console.log("Element focused"))
.onBlur(() => console.log("Element blurred"))
// Custom events
const myElement = tags.div("Element")
myElement.on("customEvent", (detail) => {
console.log("Custom event fired:", detail)
})
myElement.emit("customEvent", { data: "test value" })
```
--------------------------------
### Create Paragraph and Blockquote Elements in ZikoJS
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIElements/Primitves/text.md
Demonstrates the creation of structural text elements: paragraphs (`p`) and blockquotes (`blockquote`). The `p` function accepts multiple UI elements to form a paragraph, while `blockquote` accepts `ZikoUIQuote` instances to create a block quotation.
```javascript
const paragraph = p(text("This is the first part."), text("This is the second part."));
const blockQuote = blockquote(quote("This is a longer quote that spans multiple lines."));
```
--------------------------------
### ZikoJS Built-in Math Functions Overview
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/Math/1- functions.md
Lists the various mathematical functions available in the zikojs library. These functions are built upon `mapfun` and JavaScript's `Math` module, offering enhanced capabilities for handling multiple arguments and complex data types.
```javascript
// ZikoJS Math Functions:
// abs(...x)
// sqrt(...x)
// pow(x, n)
// sqrtn(x, n)
// e(...x)
// ln(...x)
// cos(...x)
// sin(...x)
// tan(...x)
// sinc(...x)
// acos(...x)
// asin(...x)
// atan(...x)
// cosh(...x)
// sinh(...x)
// acosh(...x)
// asinh(...x)
// atanh(...x)
// cot(...x)
// sec(...x)
// csc(...x)
// acot(...x)
// coth(...x)
// atan2(x, y, ?rad)
// hypot(...x)
// min(...x)
// max(...x)
```
--------------------------------
### DOM Manipulation and Styling with ZikoJS tags
Source: https://context7.com/zakarialaoui10/zikojs/llms.txt
Offers comprehensive DOM manipulation methods like append, prepend, insert, remove, and clear, alongside rendering and unrendering capabilities. Also includes methods for applying styles, sizes, animations, and managing attributes on elements created with `ziko.tags`.
```javascript
import { tags } from 'ziko'
const container = tags.div()
// Append children
container.append(tags.p("First"), tags.p("Second"))
// Prepend children
container.prepend(tags.h1("Title"))
// Insert at specific index
container.insertAt(1, tags.span("Middle"))
// Remove children
container.remove(0) // Remove by index
container.clear() // Remove all children
// Rendering
container.render(document.body)
container.unrender()
// Style manipulation
tags.div("Styled Content")
.style({
color: 'red',
backgroundColor: 'blue',
padding: '10px',
border: '1px solid black'
})
.size('200px', '100px')
.animate(
[{ opacity: 0 }, { opacity: 1 }],
{ duration: 1000, iterations: 2 }
)
// Attributes
tags.input()
.setAttr({
type: "text",
placeholder: "Enter text",
id: "my-input"
})
.setContentEditable(true)
.removeAttr("placeholder")
```
--------------------------------
### Array Generation and Mapping Utilities (JavaScript)
Source: https://context7.com/zakarialaoui10/zikojs/llms.txt
Provides utilities for creating numerical ranges and transforming values between different scales. Includes functions for generating arrays like `arange`, `linspace`, and `logspace`, as well as normalization, mapping, linear interpolation, and clamping.
```javascript
import { arange, linspace, logspace, norm, lerp, map, clamp } from 'ziko'
// Array generation
arange(0, 10, 2) // [0, 2, 4, 6, 8]
linspace(0, 1, 5) // [0, 0.25, 0.5, 0.75, 1]
logspace(0, 2, 3) // [1, 10, 100]
// Normalization and mapping
norm(5, 0, 10) // 0.5 (normalize to [0,1])
map(0.5, 0, 1, 0, 100) // 50 (map from [0,1] to [0,100])
lerp(0, 100, 0.5) // 50 (linear interpolation)
clamp(150, 0, 100) // 100 (clamp to range [0,100])
// Practical example: mapping mouse position to color
tags.div().onPtrMove(e => {
const normalized = norm(e.clientX, 0, window.innerWidth)
const hue = map(normalized, 0, 1, 0, 360)
e.target.style({ backgroundColor: `hsl(${hue}, 70%, 50%)` })
})
```
--------------------------------
### UI Element Style Manipulation (JavaScript)
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/1- ZikoUIElement.md
Enables direct styling of UI elements using a style object or individual style properties. It also provides methods for visibility, sizing, and applying various CSS properties.
```javascript
// Set styles using an object
uiElement.style({
color: 'darkblue',
background: 'gold',
fontSize: '16px'
});
// Set size (width, height)
uiElement.size(300, 150);
// Show/hide element
uiElement.st.show();
uiElement.st.hide();
// Access style instance for more granular control
let styleInstance = uiElement.st;
// Get all styles
let allStyles = styleInstance.styles;
// Add/delete specific styles
styleInstance.add('border', '1px solid black');
styleInstance.delete('background');
// Set specific CSS properties
styleInstance.color('red');
styleInstance.backgroundColor('lightblue');
styleInstance.display('flex');
styleInstance.margin('10px');
styleInstance.marginTop('5px');
styleInstance.marginBottom('15px');
styleInstance.marginRight('20px');
styleInstance.marginLeft('25px');
styleInstance.padding('8px');
styleInstance.paddingTop('4px');
styleInstance.paddingBottom('6px');
styleInstance.paddingRight('7px');
styleInstance.paddingLeft('9px');
styleInstance.width('100%');
styleInstance.height('auto');
styleInstance.border('2px dashed gray');
styleInstance.borderTop('1px solid blue');
styleInstance.borderBottom('1px solid green');
styleInstance.borderRight('1px solid red');
styleInstance.borderLeft('1px solid orange');
styleInstance.cursor('pointer');
styleInstance.font('14px Arial, sans-serif');
styleInstance.fontSize('20px');
styleInstance.fontFamily('Verdana, sans-serif');
// Check visibility
styleInstance.isBlock();
styleInstance.isInline();
```
--------------------------------
### Conditional Rendering with Switch in ZikoJS
Source: https://context7.com/zakarialaoui10/zikojs/llms.txt
Implements conditional rendering using the `Switch` component from `ziko`. It allows rendering different components based on a key value, with support for a default case. Requires `useState` for dynamic switching.
```javascript
import { Switch } from 'ziko'
const ViewSwitch = key => Switch({
key,
cases: {
'list': tags.ul(tags.li("Item 1"), tags.li("Item 2")),
'grid': tags.div({ class: 'grid' }, tags.div("Cell 1"), tags.div("Cell 2")),
'table': tags.table(tags.tr(tags.td("Data 1"), tags.td("Data 2"))),
default: tags.p('No view selected')
}
})
// Usage
const [viewType, setViewType] = useState('list')
tags.div(
tags.button("List").onClick(() => setViewType('list')),
tags.button("Grid").onClick(() => setViewType('grid')),
tags.button("Table").onClick(() => setViewType('table')),
ViewSwitch(viewType)
)
```
--------------------------------
### UI Element Attribute Management (JavaScript)
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/1- ZikoUIElement.md
Allows for setting, removing, and retrieving attributes of a UI element, including ID and CSS classes. This is essential for dynamic element configuration.
```javascript
// Set attributes
uiElement.setAttr('data-custom', 'value');
uiElement.setAttr({ 'aria-label': 'My Label', 'tabindex': '0' });
// Remove attributes
uiElement.removeAttr('data-custom');
uiElement.removeveAttr('aria-label', 'tabindex');
// Set ID
uiElement.setId('unique-id');
// Set and add CSS classes
uiElement.setClasses('btn', 'btn-primary'); // Overwrites existing classes
uiElement.addClasses('active', 'highlight'); // Adds to existing classes
// Get attributes, ID, and classes
let attributes = uiElement.attr;
let id = uiElement.id;
let classes = uiElement.classes;
```
--------------------------------
### DOM Manipulation for UI Elements (JavaScript)
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/1- ZikoUIElement.md
Provides methods for cloning, rendering, and removing UI elements from the DOM. It also includes functionality to control rendering and unrendering with delays.
```javascript
// Clone the UI element
let clonedElement = uiElement.clone();
// Render the UI element to the DOM
uiElement.render();
// Render after a delay
uiElement.renderAfter(1000); // Render after 1 second
// Remove the UI element from the DOM
uiElement.unrender();
// Remove after a delay
uiElement.unrenderAfter(2000); // Remove after 2 seconds
// Set the target for rendering
uiElement.setTarget('#app');
```
--------------------------------
### Create Footer Element
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIElements/Primitves/semantic.md
The `Footer` function creates the footer section of a document, typically containing copyright information or links. It accepts ZikoUIElements for its content.
```typescript
Footer(...elements : ZikoUIElements[])
```
--------------------------------
### ZikoJS: Use RTL/LTR Styles
Source: https://github.com/zakarialaoui10/zikojs/blob/main/src/ui/constructors/_m.js.txt
The `useRtl` and `useLtr` methods apply 'rtl' or 'ltr' direction styles to the element. They can optionally apply all swapped styles calculated by `#SwitchedStyleRTL_LTR` by setting `switchAll` to true. These methods are chainable and return the Ziko instance.
```javascript
useRtl(switchAll = false){
switchAll ? this.style({
...this.#SwitchedStyleRTL_LTR,
direction : "rtl"
}) : this.style({direction : "rtl"});
return this;
}
useLtr(switchAll = false){
switchAll ? this.style({
...this.#SwitchedStyleRTL_LTR,
direction : "ltr"
}) : this.style({direction : "ltr"});
return this;
}
```
--------------------------------
### Handling Click Events on Text Elements
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/1- ZikoUIElement.md
Registers a click event listener on a text element. When the element is clicked, the callback function is executed, logging the event target's value to the console. This demonstrates basic interaction handling for text elements.
```javascript
txt = text("Hello World").onClick(
e=>console.log(e.target.value)
)
```
--------------------------------
### Create Navigation Element
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIElements/Primitves/semantic.md
The `Nav` function generates a navigation block, commonly used for site menus or breadcrumbs. It accepts ZikoUIElements to structure the navigation links.
```typescript
Nav(...elements : ZikoUIElements[])
```
--------------------------------
### Custom Web Components with define_wc in ZikoJS
Source: https://context7.com/zakarialaoui10/zikojs/llms.txt
Defines reusable custom web components using `define_wc` from `ziko`. Supports shadow DOM, reactive properties with `useState`, and derived state with `useDerived`. Properties can be declared with their types.
```javascript
import { define_wc, Flex, useState, useDerived } from 'ziko'
define_wc(
"ziko-counter",
({ start = 10, color = "black" } = {}) => {
const [value, setValue] = useState(start)
const msg = useDerived(n => `..${n}..`, [value])
return Flex(
"count: ",
msg,
button("+").onClick(() => setValue(n => n + 1)),
button("-").onClick(() => setValue(n => n - 1))
).style({ color })
},
{
start: { type: Number },
color: { type: String }
}
)
// Usage in HTML
//
```
--------------------------------
### Create Various Text-Based HTML Elements in ZikoJS
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIElements/Primitves/text.md
Showcases the creation of specialized text-based HTML elements using ZikoJS functions. This includes `quote` for inline quotations, `dfnText` for definitions, `codeText` for inline code, `supText` for superscripts, `subText` for subscripts, and `abbrText` for abbreviations with tooltips.
```javascript
const quoteElement = quote("This is a quotation.");
const definitionElement = dfnText("DOM", "Document Object Model"); // First arg is term, second is definition
const codeElement = codeText("Hello");
const superscriptElement = supText("st");
const subscriptElement = subText("H2O");
const abbreviationElement = abbrText("W3C", "World Wide Web Consortium");
```
--------------------------------
### Create Aside Content
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIElements/Primitves/semantic.md
The `Aside` function creates a sidebar or supplementary content area. It can be populated with ZikoUIElements and is typically used for related links or extra information.
```typescript
Aside(...elements : ZikoUIElements[])
```
--------------------------------
### Create Link Element (JavaScript)
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIElements/Primitves/misc.md
The `link` constructor generates an anchor (hyperlink) element. It requires a URL (`href`) and can accept multiple ZikoUIElements to be placed within the link. This is useful for creating navigation elements or text links.
```javascript
link(href : string, ...elements : ZikoUIElements[])
```
--------------------------------
### Create Line Break Element (JavaScript)
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIElements/Primitves/misc.md
The `br` constructor creates a single HTML line break element. The `brs` constructor creates multiple line break elements, controlled by the `n` parameter. These are used for controlling text flow and layout.
```javascript
br()
brs(n : number)
```
--------------------------------
### Create Special HTML Element (JavaScript)
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIElements/Primitves/misc.md
The `html` constructor allows for the creation of special HTML elements. It accepts a tag name or an existing HTMLElement and an optional list of UI elements to append as children. This provides a flexible way to build complex DOM structures.
```javascript
html(tag : string | HTMLElement, ...Element : (UIElement | undefined)[])
```
--------------------------------
### ZikoJS sqrt function vs Vanilla JS Math.sqrt
Source: https://github.com/zakarialaoui10/zikojs/wiki/1-Math/Math-Functions
Compares the functionality of ZikoJS's `sqrt` function with the native JavaScript `Math.sqrt`. ZikoJS's `sqrt` can handle multiple arguments, arrays, and objects, while `Math.sqrt` is limited to single numeric inputs.
```zikojs
sqrt(9)
sqrt(4,9,16)
sqrt([4,9,16])
sqrt([4,9],16)
sqrt({x:4,y:9})
```
```javascript
Math.sqrt(9)
[Math.sqrt(4),Math.sqrt(9),Math.sqrt(16)]
[Math.sqrt(4),Math.sqrt(9),Math.sqrt(16)]
[[Math.sqrt(4),Math.sqrt(9)],Math.sqrt(16)]
{x:Math.sqrt(4),y:Math.sqrt(9)}
```
--------------------------------
### Flexible Math Functions (cos, mapfun)
Source: https://github.com/zakarialaoui10/zikojs/blob/main/README.dep.md
Demonstrates the usage of flexible math functions in Zikojs, specifically the `cos` function which is built on `mapfun`. This allows mapping mathematical operations to complex data structures like arrays and objects. It can handle multiple arguments of diverse types.
```javascript
import { cos, PI } from "ziko";
const result = cos(PI, PI / 2, PI / 4, [PI / 6, PI / 3], {
x: PI / 2,
y: PI / 4,
z: [0, PI / 12],
}
);
/*
result =>
[
-1,
0,
0.707106781186548,
[0.866025403784439, 0.5],
{
x: 0,
y: 0.707106781186548,
z: [1, 0.965925826289068],
},
];
*/
// console.log(result)
```
```javascript
import { mapfun } from "ziko";
const parabolic_func = (a, b, c, x) => a * x ** 2 + b * x + c;
const map_parabolic_func =
(a, b, c) =>
(...X) =>
mapfun((n) => parabolic_func(a, b, c, n), ...X);
const a = -1.5,
b = 2,
c = 3;
const X = [0, 1, 2, 3];
console.log(parabolic_func(a, b, c)(X));
// [3,3,1,3]
```
--------------------------------
### Currying Custom Functions with ZikoJS `mapfun`
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/Math/1- functions.md
Demonstrates the use of currying in zikojs to create functions that are partially applied. This approach allows for creating specialized versions of functions, like `map_parabolic_func`, which can then be applied to data structures.
```javascript
import {mapfun} from "ziko";
// Define a standard parabolic function
const parabolic_func = (a, b, c, x) => a * (x ** 2) + b * x + c;
// Create a curried function using mapfun
const map_parabolic_func = (a, b, c) => (...X) => mapfun(n => parabolic_func(a, b, c, n), ...X);
const a = -1.5, b = 2, c = 3;
const X = [0, 1, 2, 3];
console.log(map_parabolic_func(a, b, c)(X));
// Output: [3, 3, 1, -3]
```
--------------------------------
### Image Element
Source: https://github.com/zakarialaoui10/zikojs/blob/main/docs/api/en/1- core/UI/2- Built-In-UIElements/Primitves/media.md
Represents an image element in ZikoJS. Allows specifying source, width, and height.
```APIDOC
## Image Element
### Description
Represents an image element that can be added to the ZikoJS application.
### Method
`image(src : string, width : string | number, height : string | number)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **src** (string) - Required - The source URL or path of the image.
- **width** (string | number) - Required - The width of the image. Can be a string (e.g., '100px') or a number.
- **height** (string | number) - Required - The height of the image. Can be a string (e.g., '100px') or a number.
```