### Installing and Importing a Gentelella Fork Source: https://gentelella.colorlib.com/docs/deployment How to install your fork via NPM and import its components and SCSS. Ensure the package name matches your fork's name. ```javascript npm install your-gentelella-fork ``` ```javascript import { mountShell, showModal } from 'your-gentelella-fork'; import 'your-gentelella-fork/scss/v4/main.scss'; ``` -------------------------------- ### Install Gentelella via Git Clone Source: https://gentelella.colorlib.com/docs Clone the Gentelella repository and install its dependencies to set up the project locally. This method is suitable for starting from the template. ```bash git clone https://github.com/ColorlibHQ/gentelella.git cd gentelella npm install ``` -------------------------------- ### Run the Development Server Source: https://gentelella.colorlib.com/docs Start the development server using npm. This command boots Vite with hot module replacement for live updates on SCSS, JS, and HTML changes in the src/ directory. ```bash npm run dev ``` -------------------------------- ### Build and Preview PWA Locally Source: https://gentelella.colorlib.com/docs/pwa Run these commands to build the project and preview it locally. Use this environment to verify PWA installation criteria and service worker behavior in Chrome DevTools. ```bash npm run build npm run preview ``` -------------------------------- ### Side-by-Side Deployment Structure Source: https://gentelella.colorlib.com/docs/migration-v2 Illustrates a directory structure for running both v2 and v4 builds concurrently during a migration. This setup facilitates A/B testing and phased cutovers. ```bash deploys/ ├── v2/ # current production └── v4-beta/ # new build ``` -------------------------------- ### Checkbox and Radio Button Examples Source: https://gentelella.colorlib.com/docs/forms Basic implementation for checkboxes and radio buttons using the '.form-check' class for proper styling. ```html ``` -------------------------------- ### Input with Prefix and Suffix Example Source: https://gentelella.colorlib.com/docs/forms Use the '.input-affix' class to add static text or icons before or after an input field. The leading affix should have the '.prefix' class. ```html
$ .00
``` -------------------------------- ### Install Gentelella npm Package Source: https://gentelella.colorlib.com/docs/typescript Command to install the Gentelella library as an npm dependency in your project. ```bash npm install gentelella ``` -------------------------------- ### Import and Use Gentelella v4 Components Source: https://gentelella.colorlib.com/docs/typescript Example of importing core Gentelella v4 components and SCSS into a TypeScript project and initializing the shell. ```typescript import { mountShell, showModal, showToast } from 'gentelella'; import 'gentelella/scss/v4/main.scss'; import type { Action } from 'gentelella/v4/modal'; mountShell(); const actions: Action[] = [ { label: 'OK', variant: 'primary', action: () => {} } ]; showModal({ title: 'Hello', actions }); ``` -------------------------------- ### Install Gentelella via npm Package Source: https://gentelella.colorlib.com/docs Install Gentelella as a package into your existing project to use its helpers and styles. This is for integrating Gentelella's components into your application. ```bash npm install gentelella ``` ```javascript import { mountShell, showModal, showToast } from 'gentelella'; import 'gentelella/scss/v4/main.scss'; ``` -------------------------------- ### Select Input Example Source: https://gentelella.colorlib.com/docs/forms Standard HTML select element for dropdowns. For multi-select functionality, a custom control is available. ```html
``` -------------------------------- ### Implement Optimistic UI Update Source: https://gentelella.colorlib.com/docs/data-adapter Implement an optimistic UI update pattern for actions like moving an item between columns. This example shows how to update the UI immediately and revert on failure. ```javascript // optimistic async function move(id, column) { const card = cards.find(c => c.id === id); card.column = column; render(); try { await adapter.update(id, { column }); } catch (e) { card.column = previousColumn; render(); showToast('Move failed', { variant: 'error' }); } } ``` -------------------------------- ### Inbox Data Adapter Setup Source: https://gentelella.colorlib.com/docs/data-adapter Sets up the data adapter for the inbox, choosing between an HTTP adapter for API calls or a seed adapter for local data. Requires `useApiMode`, `seedAdapter`, and `httpAdapter` imports. ```javascript import { useApiMode, seedAdapter, httpAdapter } from './data-adapter.js'; const SEED = [/* ... */]; const adapter = useApiMode() ? httpAdapter('/api/messages') : seedAdapter(SEED, filterByFolder); async function loadFolder(folder) { const messages = await adapter.list({ folder }); renderList(messages); } async function markRead(id) { await adapter.update(id, { unread: false }); // optimistically update DOM } ``` -------------------------------- ### Textarea Input Example Source: https://gentelella.colorlib.com/docs/forms Suitable for multi-line text input. Control the height by setting the 'rows' attribute. ```html
``` -------------------------------- ### Adding Type Definitions for New Modules Source: https://gentelella.colorlib.com/docs/typescript Example of how to declare types for a new JavaScript module in a TypeScript project using a declaration file. ```typescript declare module 'gentelella/v4/reports' { export interface ReportConfig { range: 'day' | 'week' | 'month'; metric: string; } export function initReports(): void; export function buildReport(config: ReportConfig): Promise; } ``` -------------------------------- ### Conditional API Mode Based on Hostname Source: https://gentelella.colorlib.com/docs/data-adapter Provides an example of setting the `window.__GENTELELLA_API__` flag conditionally, enabling API mode for all hostnames except 'localhost'. ```html ``` -------------------------------- ### HTTP Error Handling with httpAdapter Source: https://gentelella.colorlib.com/docs/data-adapter The `httpAdapter` throws `HttpError` for non-2xx responses. This example shows how to catch and handle specific HTTP error statuses. ```javascript import { HttpError } from './v4/data-adapter.js'; try { await adapter.update(id, patch); } catch (e) { if (e instanceof HttpError && e.status === 404) { showToast('Item not found', { variant: 'error' }); } else if (e instanceof HttpError && e.status >= 500) { showToast('Server error — try again', { variant: 'error' }); } else { throw e; } } ``` -------------------------------- ### Get Data Adapter for Custom Page Source: https://gentelella.colorlib.com/docs/data-adapter Initializes the data adapter for a custom page. It conditionally uses `httpAdapter` if `useApiMode` is true, otherwise it uses `seedAdapter` with the defined `SEED`. ```javascript const adapter = useApiMode() ? httpAdapter('/api/customers') : seedAdapter(SEED); ``` -------------------------------- ### Bind Custom Shortcut to Open Command Palette Source: https://gentelella.colorlib.com/docs/palette Listen for a keydown event and open the command palette programmatically. This example binds Ctrl+P or Cmd+P to trigger the palette. ```javascript import { openCommandPalette, closeCommandPalette } from '/src/v4/command-palette.js'; // Bind to a different shortcut document.addEventListener('keydown', (e) => { if (e.key === 'p' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); openCommandPalette(); } }); ``` -------------------------------- ### Module Augmentation for Shell Module Source: https://gentelella.colorlib.com/docs/typescript Example of using module augmentation to add types for the `v4/shell` module, specifically for the `mountShell` function. ```typescript declare module 'gentelella/v4/shell' { /** Mount the admin shell. Reads body data attributes. */ export function mountShell(): void; } ``` -------------------------------- ### Standard Form Input Example Source: https://gentelella.colorlib.com/docs/forms Use this for standard text-based inputs like email. Ensure the 'required' attribute is used for mandatory fields. The '.form-help' class provides subtle guidance below the input. ```html
We'll never share your email.
``` -------------------------------- ### Import Individual ES-Module Helpers via CDN Source: https://gentelella.colorlib.com/docs Import individual ES-module helpers like modal and toast directly from the CDN. Ensure the paths under src/v4/ are stable. This method is useful for leveraging specific functionalities without a full installation. ```html ``` -------------------------------- ### GitHub Actions Workflow for GitHub Pages Deployment Source: https://gentelella.colorlib.com/docs/deployment A GitHub Actions workflow to deploy a static site to GitHub Pages. It checks out the code, sets up Node.js, installs dependencies, builds the project with a base path, uploads the build artifact, and deploys to GitHub Pages. ```yaml # .github/workflows/deploy.yml name: Deploy on: push: branches: [master] jobs: deploy: runs-on: ubuntu-latest permissions: pages: write id-token: write steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: { node-version: '20', cache: 'npm' } - run: npm ci - run: BASE_PATH=/${{ github.event.repository.name }}/ npm run build - uses: actions/upload-pages-artifact@v3 with: { path: dist } - uses: actions/deploy-pages@v4 ``` -------------------------------- ### PWA Manifest Configuration Source: https://gentelella.colorlib.com/docs/pwa This JSON defines the web app manifest for Gentelella v4. Configure name, icons, theme color, and shortcuts for PWA installation and behavior. ```json { "name": "Gentelella v4 — Admin Dashboard", "short_name": "Gentelella", "description": "Modern admin dashboard template — vanilla JS, real ECharts and DataTables, no Bootstrap, no jQuery.", "icons": [ { "src": "images/android-chrome-192x192.svg", "sizes": "192x192", "type": "image/svg+xml", "purpose": "any" }, { "src": "images/android-chrome-512x512.svg", "sizes": "512x512", "type": "image/svg+xml", "purpose": "any" }, { "src": "images/android-chrome-512x512.svg", "sizes": "512x512", "type": "image/svg+xml", "purpose": "maskable" } ], "theme_color": "#1ABB9C", "background_color": "#f5f7fb", "display": "standalone", "orientation": "any", "scope": "./", "start_url": "production/index.html", "id": "gentelella-v4", "lang": "en", "categories": ["productivity", "business", "developer"], "shortcuts": [ { "name": "Dashboard", "url": "production/index.html" }, { "name": "Inbox", "url": "production/inbox.html" }, { "name": "Calendar", "url": "production/calendar.html" }, { "name": "Settings", "url": "production/settings.html" } ] } ``` -------------------------------- ### Service Worker Implementation Source: https://gentelella.colorlib.com/docs/pwa Defines caching strategies for HTML (network-first) and hashed assets (cache-first). It precaches an offline page and handles installation, activation, and fetch events. ```javascript const CACHE = 'gentelella-v4-r2'; const SCOPE = self.registration?.scope || self.location.origin + '/'; const OFFLINE_URL = new URL('production/offline.html', SCOPE).href; const PRECACHE = [OFFLINE_URL]; self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE) .then((c) => c.addAll(PRECACHE).catch(() => {})) .then(() => self.skipWaiting()) ); }); self.addEventListener('activate', (event) => { event.waitUntil( caches.keys() .then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))) .then(() => self.clients.claim()) ); }); self.addEventListener('fetch', (event) => { const req = event.request; if (req.method !== 'GET') return; const url = new URL(req.url); if (url.origin !== self.location.origin) return; // skip cross-origin // HTML — network first, fallback to cache, then offline page if (req.mode === 'navigate' || req.headers.get('accept')?.includes('text/html')) { event.respondWith( fetch(req) .then((res) => { caches.open(CACHE).then((c) => c.put(req, res.clone())).catch(() => {}); return res; }) .catch(async () => (await caches.match(req)) || (await caches.match(OFFLINE_URL)) || Response.error() ) ); return; } // Hashed assets — cache first if (/ /(js|assets|images|fonts) //.test(url.pathname)) { event.respondWith( caches.match(req).then((hit) => hit || fetch(req).then((res) => { caches.open(CACHE).then((c) => c.put(req, res.clone())).catch(() => {}); return res; })) ); } }); ``` -------------------------------- ### AWS S3 Sync for Static Assets and HTML Source: https://gentelella.colorlib.com/docs/deployment Syncs the build output directory to an S3 bucket with different caching strategies for hashed assets and HTML files. Hashed assets are cached aggressively, while HTML, service workers, and manifest files are not cached to ensure users get the latest versions. ```bash npm run build # Long-cache hashed assets aws s3 sync dist/ s3://your-bucket/ --delete \ --cache-control "public, max-age=31536000, immutable" \ --exclude "*.html" --exclude "sw.js" --exclude "site.webmanifest" # No-cache for HTML so users always get fresh references aws s3 sync dist/ s3://your-bucket/ \ --cache-control "public, max-age=0, must-revalidate" \ --include "*.html" --include "sw.js" --include "site.webmanifest" ``` -------------------------------- ### Pre-deploy Checklist Source: https://gentelella.colorlib.com/docs/deployment Run these commands to ensure code quality, build the project, and perform a basic sanity check on the output directory before deployment. Verify file sizes and contents. ```bash npm run lint ``` ```bash npm run build ``` ```bash ls -la dist/ ``` ```bash du -sh dist/ ``` -------------------------------- ### Run Production Builds Source: https://gentelella.colorlib.com/docs Use these commands to create production-ready, minified, and hashed assets. For debugging, use the non-minified build. Preview the production build locally. ```bash # Production — minified, hashed assets, what you'd deploy npm run build # Non-minified build, useful for debugging npm run build:dev # Preview the production build locally (serves dist/ on port 9174) npm run preview ``` -------------------------------- ### Preview Production Build Source: https://gentelella.colorlib.com/docs/faq After building for production, use `npm run preview` to serve the static files from the `dist/` directory. This is useful for testing the production build locally. ```bash npm run build && npm run preview ``` -------------------------------- ### Initialize Command Palette Source: https://gentelella.colorlib.com/docs/palette Sets up the global keybinding (Ctrl/Cmd+K) to open/close the command palette and repurposes the topbar search box as an opener. Ensures idempotency with a `_wired` flag. ```javascript export function initCommandPalette() { if (initCommandPalette._wired) return; initCommandPalette._wired = true; document.addEventListener('keydown', (e) => { const isK = e.key === 'k' || e.key === 'K'; if (isK && (e.metaKey || e.ctrlKey)) { e.preventDefault(); host ? close() : open(); } }); // Repurpose the topbar search box const search = document.querySelector('.search-box input'); if (search) { const opener = (e) => { e.preventDefault(); search.blur(); open(); }; search.addEventListener('focus', opener); search.addEventListener('click', opener); search.setAttribute('readonly', ''); search.setAttribute('aria-label', 'Open command palette'); } } ``` -------------------------------- ### Build for Production Source: https://gentelella.colorlib.com/docs/faq Run the `npm run build` command to create a production-ready build of the project. The output will be placed in the `dist/` directory. ```bash npm run build ``` -------------------------------- ### Get Selected Row Count Source: https://gentelella.colorlib.com/docs/tables Read the number of selected rows by querying for `tr.selected` elements within the table's tbody. ```javascript const selected = table.querySelectorAll('tbody tr.selected').length; ``` -------------------------------- ### Show Modal with Type Hints Source: https://gentelella.colorlib.com/docs/typescript Demonstrates how to import and use the `showModal` function from a local file, with inline type hints for parameters. ```typescript import { showModal } from './v4/modal.js'; showModal({ title: 'Hello', // ┃ // ┗━ string | undefined body: '...', // ┃ // ┗━ string | HTMLElement | undefined actions: [ // ┃ // ┗━ Action[] { label: 'OK', variant: 'primary', action: () => true } // ┃ // ┗━ "primary" | "outline" | "ghost" | "danger" | undefined ] }); ``` -------------------------------- ### Build Gentelella for Production Source: https://gentelella.colorlib.com/docs/deployment Run these commands to create production-ready static files. Use `npm run build` for a minified, hashed build suitable for deployment. `npm run build:dev` creates a non-minified version for debugging. For subpath deployments, prefix the build command with `BASE_PATH=/your/subpath/`. ```bash # Minified, hashed, sourcemap-hidden — what you'd deploy npm run build # Non-minified — useful for debugging the production output npm run build:dev # Build at a subpath (e.g. https://example.com/admin/) BASE_PATH=/admin/ npm run build ``` -------------------------------- ### Implement Kanban Drag-and-Drop Source: https://gentelella.colorlib.com/docs/kanban Sets up event listeners for dragstart, dragend, dragover, and drop events on the board container for drag-and-drop functionality. Uses event delegation for efficiency. ```javascript let draggedId = null; function setupDnD(boardEl) { // ─── 1. Start drag ──────────────────────── boardEl.addEventListener('dragstart', (e) => { const card = e.target.closest('.kanban-card'); if (!card) return; draggedId = parseInt(card.dataset.id, 10); card.classList.add('dragging'); // Firefox needs data set on dataTransfer to actually drag. e.dataTransfer.setData('text/plain', String(draggedId)); }); // ─── 2. End drag (cleanup) ──────────────── boardEl.addEventListener('dragend', (e) => { const card = e.target.closest('.kanban-card'); if (card) card.classList.remove('dragging'); document.querySelectorAll('.kanban-column-body.drop-target') .forEach((el) => el.classList.remove('drop-target')); draggedId = null; }); // ─── 3. Allow drop on column bodies ──────── boardEl.addEventListener('dragover', (e) => { const col = e.target.closest('.kanban-column-body'); if (col) { e.preventDefault(); // Required to allow drop col.classList.add('drop-target'); } }); // ─── 4. Drop ─────────────────────────────── boardEl.addEventListener('drop', (e) => { const col = e.target.closest('.kanban-column-body'); if (!col || draggedId === null) return; e.preventDefault(); const newColumn = col.dataset.drop; const card = cards.find((c) => c.id === draggedId); if (!card) return; card.col = newColumn; render(); // Repaint everything showToast(`Moved to ${columnTitle(newColumn)}`, { variant: 'success' }); }); } ``` -------------------------------- ### Write ECharts Factory Function Source: https://gentelella.colorlib.com/docs/echarts Define a factory function for a new chart type. This example creates a 'quick-spark' line chart with predefined data and styling. ```javascript function quickSpark(echarts, el, t) { const chart = echarts.init(el); chart.setOption({ ...baseOption(t), grid: { left: 0, right: 0, top: 4, bottom: 0 }, xAxis: { show: false, type: 'category' }, yAxis: { show: false, type: 'value' }, series: [{ type: 'line', data: [12, 14, 18, 22, 28, 32, 40], smooth: true, lineStyle: { color: t.primary, width: 2 }, itemStyle: { color: t.primary }, symbol: 'none', areaStyle: { color: hexToRgba(t.primary, 0.15) } }] }); return chart; } ``` -------------------------------- ### Production Build Commands Source: https://gentelella.colorlib.com/docs/getting-started Commands to create minified, hashed assets for deployment, non-minified builds for debugging, and previewing the production build locally. ```bash npm run build # Non-minified build, useful for debugging npm run build:dev # Preview the production build locally (serves dist/ on port 9174) npm run preview ``` -------------------------------- ### Using statTile Helper for Dynamic Content Source: https://gentelella.colorlib.com/docs/playground Demonstrates how to use the `statTile` helper to dynamically generate KPI cards for displaying revenue and new customer statistics. Ensure the `markup.js` module is imported. ```javascript import { pageHeader, statTile, statusBadge, customerCell, activityItem, visitorRow, emptyState, banner, skeletonRows, escapeHtml } from '/src/v4/markup.js'; document.querySelector('[data-preview-stats]').innerHTML = ` ${statTile({ label: 'Revenue', value: '$48,205', color: 'teal', change: '+12%' })} ${statTile({ label: 'New customers', value: '1,284', color: 'green', change: '+8%' })} `; ``` -------------------------------- ### Get CSS Theme Tokens Source: https://gentelella.colorlib.com/docs/echarts Retrieves CSS custom properties (tokens) from the document's root element. Add new tokens here if they are introduced in `_tokens.scss`. ```javascript const tokens = () => { const cs = getComputedStyle(document.documentElement); return { primary: cs.getPropertyValue('--primary').trim(), primaryDk: cs.getPropertyValue('--primary-dk').trim(), azure: cs.getPropertyValue('--azure').trim(), blue: cs.getPropertyValue('--blue').trim(), yellow: cs.getPropertyValue('--yellow').trim(), green: cs.getPropertyValue('--green').trim(), red: cs.getPropertyValue('--red').trim(), purple: cs.getPropertyValue('--purple').trim(), text: cs.getPropertyValue('--text').trim(), textMuted: cs.getPropertyValue('--text-muted').trim(), borderLight: cs.getPropertyValue('--border-color-light').trim(), bgSurface: cs.getPropertyValue('--bg-surface').trim() }; }; ``` ```javascript return { // ...existing tokens... accentCoral: cs.getPropertyValue('--accent-coral').trim() }; ``` -------------------------------- ### Data Adapter Methods Source: https://gentelella.colorlib.com/docs/data-adapter Demonstrates the common methods available on both HTTP and seed data adapters for managing data items. ```javascript // Both have the same methods: const items = await adapter.list({ folder: 'inbox' }); const item = await adapter.get(id); const created = await adapter.create({ subject: 'Hi' }); const updated = await adapter.update(id, { unread: false }); const removed = await adapter.remove(id); ``` -------------------------------- ### Chart Initialization and Factory Source: https://gentelella.colorlib.com/docs/typescript Initializes charts and provides a factory map for chart configurations. ```APIDOC ## Chart Initialization ### Description Initializes charts on the page and provides a factory map for configuring different chart types. ### Functions #### initCharts * **Description**: Initializes all charts on the page. * **Signature**: `initCharts(): void` * **Module**: `gentelella/v4/charts` ### Constants #### charts * **Description**: A factory map for chart configurations. * **Type**: `object` * **Module**: `gentelella/v4/charts` ``` -------------------------------- ### Publishing a Gentelella Fork to NPM Source: https://gentelella.colorlib.com/docs/deployment Commands to update version, lint, and publish your fork. The `prepublishOnly` hook ensures the build is run before publishing. ```bash # Update version in package.json npm run lint # must pass npm publish # prepublishOnly runs `npm run build` first ``` -------------------------------- ### Add New Accent Token Source: https://gentelella.colorlib.com/docs/theming Define a new CSS variable, like `--accent-coral`, in `_tokens.scss` for custom styling. This example shows how to set it for both light and dark themes. ```scss /* _tokens.scss */ :root { --accent-coral: #FF6B6B; } :root[data-theme="dark"] { --accent-coral: #FF8787; } ``` ```css /* _components.scss (or wherever you need it) */ .my-component { background: var(--accent-coral); } ``` -------------------------------- ### Initialize Component Playground Script Source: https://gentelella.colorlib.com/docs/playground This script iterates through component cards, extracts original HTML, builds a source panel with reset and copy buttons, and enables live editing. It uses debounced input for preview updates and clipboard API for copying. ```javascript document.querySelectorAll('[data-source]').forEach((card) => { const preview = card.querySelector('[data-preview]'); if (!preview) return; const originalHtml = preview.innerHTML.trim(); const label = card.dataset.sourceLabel || ''; const code = indent(originalHtml); // Build the source panel (label, Reset/Copy buttons, editable
)
  const block = document.createElement('div');
  block.className = 'pg-source';
  // ... see the source for the full markup
  block.querySelector('.pg-code').textContent = code;
  card.appendChild(block);

  // Live edit, debounced 250ms
  block.querySelector('.pg-code').addEventListener('input', (e) => {
    clearTimeout(editTimer);
    editTimer = setTimeout(() => {
      preview.innerHTML = e.target.textContent;
    }, 250);
  });

  // Copy to clipboard
  block.querySelector('.pg-copy').addEventListener('click', async () => {
    await navigator.clipboard.writeText(code);
    showToast('Copied to clipboard', { variant: 'success' });
  });
});
```

--------------------------------

### Table Initialization

Source: https://gentelella.colorlib.com/docs/typescript

Initializes tables on the page.

```APIDOC
## initTables

### Description
Initializes tables on the page.

### Signature
`initTables(): void`

### Module
`gentelella/v4/tables`
```

--------------------------------

### Build and Deploy to Cloudflare Pages with Wrangler

Source: https://gentelella.colorlib.com/docs/deployment

Build the project and then deploy the output directory to Cloudflare Pages using the Wrangler CLI. Ensure your project is configured with a build script and the output directory is set to 'dist'.

```bash
# Build, then deploy via Wrangler
npm run build
npx wrangler pages deploy dist --project-name=your-project
```

--------------------------------

### Netlify Configuration for Static Site Deployment

Source: https://gentelella.colorlib.com/docs/deployment

Configuration for Netlify's continuous deployment. Specifies the build command, publish directory, and Node.js version. Includes headers for service workers and aggressively cached assets.

```toml
[build]
  command = "npm run build"
  publish = "dist"

[build.environment]
  NODE_VERSION = "20"

# Service-worker scope must match the deployed path
[[headers]]
  for = "/sw.js"
  [headers.values]
    Cache-Control = "no-cache"
    Service-Worker-Allowed = "/"

# Cache hashed assets aggressively
[[headers]]
  for = "/js/*"
  [headers.values]
    Cache-Control = "public, max-age=31536000, immutable"

[[headers]]
  for = "/assets/*"
  [headers.values]
    Cache-Control = "public, max-age=31536000, immutable"

[[headers]]
  for = "/images/*"
  [headers.values]
    Cache-Control = "public, max-age=31536000, immutable"
```

--------------------------------

### Execute Other Project Scripts

Source: https://gentelella.colorlib.com/docs

A collection of utility scripts for analyzing bundles, capturing screenshots, linting, and formatting code. The screenshots script is used for generating README and documentation preview images.

```bash
npm run analyze       Build + open the bundle treemap (rollup-plugin-visualizer)
npm run screenshots   Boot Playwright + capture 44 PNGs to docs/screenshots/
npm run lint          ESLint across src/
npm run format        Prettier write across src/
```

--------------------------------

### Update Service Worker Cache Version

Source: https://gentelella.colorlib.com/docs/pwa

Bump the CACHE constant in sw.js on every release to invalidate the cache and ensure users get the latest version. The activate handler automatically removes old caches.

```javascript
const CACHE = 'gentelella-v4-r3';   // was 'gentelella-v4-r2'
```

--------------------------------

### Create New HTML Page for Reports

Source: https://gentelella.colorlib.com/docs/adding-pages

Drop this HTML file into the `production/` directory. Ensure the `data-page` attribute matches the key you will add to the `NAV` array in the next step.

```html




  
  
  Reports | Gentelella 2026 v4
  
  
  
  
  



  

Your content here

``` -------------------------------- ### Disable PWA Service Worker Registration Source: https://gentelella.colorlib.com/docs/pwa To disable the PWA's offline support while keeping it installable, remove the service worker registration block from main-v4.js. This prevents the SW from registering but allows the manifest to still function. ```javascript if ('serviceWorker' in navigator) { // ... registration code to be removed } ``` -------------------------------- ### Vite Server Configuration Source: https://gentelella.colorlib.com/docs/vite-build Configure the development server port, proxy settings, and auto-opening behavior. ```javascript server: { open: '/production/index.html', port: Number(process.env.PORT) || 9173, host: true, proxy: { '/api': { target: process.env.API_URL || 'http://localhost:8080', changeOrigin: true } } } ``` -------------------------------- ### Customize DataTables Language Options Source: https://gentelella.colorlib.com/docs/tables Translate DataTables UI strings like search prompts, pagination labels, and info messages by modifying the `language` block in `initTables`. This example shows how to set a custom placeholder and pagination symbols. ```javascript language: { search: '', // No "Search:" label searchPlaceholder: 'Search…', info: 'Showing _START_–_END_ of _TOTAL_', infoEmpty: 'No matching records', infoFiltered: '(of _MAX_ total)', zeroRecords: 'No matches found', paginate: { previous: '←', next: '→' } } ``` -------------------------------- ### Forcing API Mode with Script Tag Source: https://gentelella.colorlib.com/docs/data-adapter Demonstrates how to force API mode in production by setting a global variable `window.__GENTELELLA_API__` before loading the main module. ```html ``` -------------------------------- ### Scaffolding Command: v2 vs v4 Source: https://gentelella.colorlib.com/docs/migration-v2 v2 required manual edits to vite.config.js for new pages. v4 uses an auto-discovery and scaffolder system with commands like `npm run new`. ```bash # v2 — manual edits to vite.config.js after creating production/.html # v4 — auto-discovery + scaffolder npm run new -- reports --title "Reports" --nav-group "Admin" ``` -------------------------------- ### Data Adapter Initialization Source: https://gentelella.colorlib.com/docs/data-adapter Initializes the data adapter, choosing between an HTTP adapter for API calls or a seed adapter for in-memory data based on the API mode. ```javascript const adapter = useApiMode() ? httpAdapter('/api/messages') : seedAdapter(SEED); ``` -------------------------------- ### Vercel Configuration for Static Site Deployment Source: https://gentelella.colorlib.com/docs/deployment Configuration for Vercel deployment. Defines the build command, output directory, and caching headers for static assets and service workers. Set framework to null if not using a specific framework integration. ```json { "buildCommand": "npm run build", "outputDirectory": "dist", "framework": null, "headers": [ { "source": "/(js|assets|images|fonts)/(.*)", "headers": [ { "key": "Cache-Control", "value": "public, max-age=31536000, immutable" } ] }, { "source": "/sw.js", "headers": [ { "key": "Cache-Control", "value": "no-cache" } ] } ] } ``` -------------------------------- ### Verify Subpath Deployment Locally Source: https://gentelella.colorlib.com/docs/deployment Use the same BASE_PATH environment variable when running the preview command to test the subpath deployment locally. This ensures assets are correctly prefixed and accessible. ```bash BASE_PATH=/admin/ npm run preview ``` -------------------------------- ### Gentelella Production Build Output Structure Source: https://gentelella.colorlib.com/docs/deployment The `dist/` directory contains all static assets for deployment. It includes minified JS and CSS with content hashes for cache busting, static HTML pages, and other assets like fonts and images. The service worker (`sw.js`) is not hashed to ensure a stable URL. ```treeview dist/ ├── production/ │ ├── index.html # Operations dashboard │ ├── inbox.html # Inbox client │ ├── kanban.html # Drag-drop board │ ├── theme.html # Live theme generator │ ├── playground.html # Component playground │ ├── offline.html # SW fallback │ └── ... # 58 pages total ├── js/ │ ├── main-[hash].js # Entry chunk for index.html │ ├── inbox-[hash].js # Lazy-loaded inbox module │ ├── kanban-[hash].js │ ├── vendor-echarts-[hash].js │ ├── vendor-tables-[hash].js │ ├── vendor-maps-[hash].js │ └── ... ├── assets/ │ └── main-[hash].css # Compiled SCSS, one bundle ├── fonts/ # If any are self-hosted (default uses Google Fonts CDN) ├── images/ │ └── favicon-[hash].svg # ...and other content-hashed images ├── sw.js # Service worker (not hashed — needs stable URL) ├── site.webmanifest # PWA manifest └── stats.html # Bundle analyzer treemap ``` -------------------------------- ### Configure Bundle Analyzer Plugin Source: https://gentelella.colorlib.com/docs/vite-build This configuration snippet shows how to wire up the `rollup-plugin-visualizer` to generate a treemap of your bundle composition, which is useful for identifying unexpectedly large packages. ```javascript plugins: [ visualizer({ filename: 'dist/stats.html', open: false, gzipSize: true, brotliSize: true, template: 'treemap' }) ] ``` -------------------------------- ### Page Module Initialization Source: https://gentelella.colorlib.com/docs/typescript Initializes various page-specific modules. ```APIDOC ## Page Module Initialization ### Description Initializes specific modules for different page types. ### Functions #### initInbox * **Description**: Initializes the inbox module. * **Signature**: `initInbox(): void` #### initKanban * **Description**: Initializes the Kanban board module. * **Signature**: `initKanban(): void` #### initCalendar * **Description**: Initializes the calendar module. * **Signature**: `initCalendar(): void` #### initFileManager * **Description**: Initializes the file manager module. * **Signature**: `initFileManager(): void` #### initSettings * **Description**: Initializes the settings module. * **Signature**: `initSettings(): void` ``` -------------------------------- ### Show a Modal with Gentelella Source: https://gentelella.colorlib.com/docs/faq Import and use the `showModal` function to display a modal. Ensure the DOM is ready before calling this function. ```javascript import { showModal } from './v4/modal.js'; showModal({ title: 'Hi', body: '...', actions: [...] }); ``` -------------------------------- ### Show a Toast Notification Source: https://gentelella.colorlib.com/docs/faq Import and use the `showToast` function to display a toast message. It accepts a message and an optional configuration object. ```javascript import { showToast } from './v4/toast.js'; showToast('Saved', { variant: 'success' }); ``` -------------------------------- ### Form Controls Initialization Source: https://gentelella.colorlib.com/docs/typescript Initializes form controls on the page. ```APIDOC ## initFormControls ### Description Initializes form controls on the page. ### Signature `initFormControls(): void` ### Module `gentelella/v4/form-controls` ``` -------------------------------- ### Early-Paint Theme Script Source: https://gentelella.colorlib.com/docs/architecture This script runs synchronously before CSS to apply the user's preferred theme (from localStorage or system preference) by setting a data-theme attribute on the html element. It includes error handling for localStorage access. ```html ``` -------------------------------- ### Check Node.js and npm Versions Source: https://gentelella.colorlib.com/docs Verify that your Node.js and npm versions meet the requirements for Gentelella v4.0.0. Node.js 20 or higher and npm 10 or higher are recommended. ```bash node --version # v20.0.0 or higher npm --version # 10.0.0 or higher ``` -------------------------------- ### Build for Subpath Deployment Source: https://gentelella.colorlib.com/docs Configure the build process to deploy under a specific subpath by setting the BASE_PATH environment variable. ```bash BASE_PATH=/admin/ npm run build ``` -------------------------------- ### Access Demo Pages via CDN Source: https://gentelella.colorlib.com/docs Directly access the 58 built demo pages of Gentelella v4 through jsDelivr CDN. These URLs point to the production-ready HTML files. ```html https://cdn.jsdelivr.net/npm/gentelella@4/dist/production/index.html ``` ```html https://cdn.jsdelivr.net/npm/gentelella@4/dist/production/inbox.html ``` ```html https://cdn.jsdelivr.net/npm/gentelella@4/dist/production/kanban.html ``` -------------------------------- ### Auto-discover Vite Entries Source: https://gentelella.colorlib.com/docs/vite-build This function scans the 'production/' directory for HTML files to use as build entries. It maps 'index.html' to 'main' for backward compatibility and uses filenames for other entries. ```javascript function discoverEntries() { const dir = resolve(import.meta.dirname, 'production'); const out = {}; for (const file of readdirSync(dir)) { if (!file.endsWith('.html')) continue; // index.html → chunk name 'main' (kept for backwards compat); // everything else uses the filename stem. const stem = file === 'index.html' ? 'main' : file.replace(/\.html$/, ''); out[stem] = `production/${file}`; } return out; } // ...later in defineConfig: rollupOptions: { input: discoverEntries(), // ... } ``` -------------------------------- ### Observe Theme Changes Source: https://gentelella.colorlib.com/docs/echarts Sets up a MutationObserver to watch for changes to the `data-theme` attribute on the `` element and listens for a custom `themechange` event. Both trigger a `rebuild()` function to update charts. ```javascript const themeObserver = new MutationObserver((records) => { if (records.some((r) => r.attributeName === 'data-theme')) rebuild(); }); themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] }); document.documentElement.addEventListener('themechange', rebuild); ``` -------------------------------- ### seedAdapter - In-Memory Data Adapter Source: https://gentelella.colorlib.com/docs/data-adapter The `seedAdapter` creates an in-memory data store initialized with provided data. It supports filtering and mutations, with a `reset` method to restore the original seed. Useful for testing and development. ```APIDOC ## `seedAdapter` — in-memory ```javascript import { seedAdapter } from './v4/data-adapter.js'; const SEED = [ { id: 1, subject: 'Welcome', folder: 'inbox', unread: true }, { id: 2, subject: 'Q3 review', folder: 'inbox', unread: false } ]; const adapter = seedAdapter(SEED, (item, query) => { if (query.folder) return item.folder === query.folder; return true; }); await adapter.list(); // → both items await adapter.list({ folder: 'inbox' }); // → both (filter passes) await adapter.update(1, { unread: false }); await adapter.list(); // → item 1 is now unread:false adapter.reset(); // back to original seed ``` The optional second arg is a filter function `(item, query) => boolean` so the seed can mimic backend query params (folder, status, search). Mutations are persistent for the page lifetime but not across reloads. `adapter.reset()` restores the original seed — useful for testing. ``` -------------------------------- ### Command Palette Operations Source: https://gentelella.colorlib.com/docs/typescript Functions for initializing and controlling the command palette. ```APIDOC ## Command Palette Functions ### Description Provides functions to initialize and control the command palette interface. ### Functions #### initCommandPalette * **Description**: Initializes the command palette. * **Signature**: `initCommandPalette(): void` * **Module**: `gentelella/v4/command-palette` #### openCommandPalette * **Description**: Opens the command palette. * **Signature**: `openCommandPalette(): void` * **Module**: `gentelella/v4/command-palette` #### closeCommandPalette * **Description**: Closes the command palette. * **Signature**: `closeCommandPalette(): void` * **Module**: `gentelella/v4/command-palette` ``` -------------------------------- ### Use Data Attributes for Per-Instance Chart Source: https://gentelella.colorlib.com/docs/echarts Provide per-instance data and styling for a custom chart by setting 'data-points' and 'data-color' attributes on the host element. ```html
``` -------------------------------- ### REST Backend with httpAdapter Source: https://gentelella.colorlib.com/docs/data-adapter The `httpAdapter` facilitates interaction with a REST backend. It maps standard CRUD operations to HTTP requests. The default fetch implementation can be customized. ```javascript import { httpAdapter } from './v4/data-adapter.js'; const adapter = httpAdapter('/api/messages'); await adapter.list({ folder: 'inbox' }); // GET /api/messages?folder=inbox // → response body parsed as JSON await adapter.get(1); // GET /api/messages/1 await adapter.create({ subject: 'Hi' }); // POST /api/messages with JSON body await adapter.update(1, { unread: false }); // PATCH /api/messages/1 with JSON body await adapter.remove(1); // DELETE /api/messages/1 ``` ```javascript const adapter = httpAdapter('/api/messages', { listKey: 'messages' }); const items = await adapter.list(); // extracts data.messages ``` ```javascript const authedFetch = (url, opts = {}) => fetch(url, { ...opts, headers: { ...opts.headers, Authorization: `Bearer ${TOKEN}` } }); const adapter = httpAdapter('/api/messages', { fetch: authedFetch }); ``` -------------------------------- ### Conditional Data Fetching Logic Source: https://gentelella.colorlib.com/docs/data-adapter Shows how to use the `useApiMode` hook to conditionally execute code for hitting a real backend or using seed data. ```javascript import { useApiMode } from './v4/data-adapter.js'; if (useApiMode()) { // hit real backend } else { // use seed } ``` -------------------------------- ### Force Light Mode in HTML Source: https://gentelella.colorlib.com/docs/faq Apply this script to force the light theme. Place it after the pre-paint script in the head section of your HTML. ```html ```