npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@micropasts/colour-palette

v0.1.3

Published

Lightweight, framework-agnostic image colour palette extractor built with ColorThief and Tailwind CSS v4.

Downloads

411

Readme

Colour Palette (@micropasts/colour-palette)

A lightweight, framework-agnostic image colour palette extractor and pigment inspector built with ColorThief and Tailwind CSS v4. Designed for museums, archives, libraries, and digital heritage platforms to extract dominant colours and palettes from artwork images, photographs, and canvases in HEX, RGB, and HSL formats with one-click string copying.

  • Live Demo: https://micropasts.github.io/colour-palette/
  • Repository: https://github.com/MicroPasts/colour-palette
  • Author: Daniel Pett (MicroPasts)

Table of Contents


Features

  • Fast Client-Side Quantization: Powered by colorthief v3.5.0 (getColorSync & getPaletteSync) with zero server round-trips and a minimal bundle footprint.
  • Dominant & Palette Swatches: Displays both the primary dominant colour and a configurable number of palette swatches (2 to 20 colours).
  • Multiple Colour Formats & Clipboard Copying: Switch between HEX, RGB, and HSL representations on the fly. Click any individual swatch to copy its value, or use Copy all strings to copy the full comma-separated palette.
  • Flexible Image Inputs: Load images via URL (imageUrl / loadImage()), pass existing <img> or <canvas> elements (image / setImageElement()), or upload local files via the built-in picker.
  • Configurable Toolbar Controls: Independently show or hide the image file picker (showImageSelect), colour count selector (showColourCount), and theme toggle (showThemeSwitcher).
  • Built-In Input Sanitization: Validates URLs against an http: / https: / blob: allowlist, checks uploaded files against raster MIME types (JPEG, PNG, WebP, GIF, AVIF), verifies file header magic bytes, enforces file size limits, and revokes object URLs on cleanup.
  • Configurable Proxy Routing: Rewrite image URLs through custom prefixes or resolver functions via proxyRoutes and proxyUrl.
  • Scoped Dark & Light Themes: Isolated .dark class theming with bundled Tailwind CSS v4 utilities.

Installation

From npm

npm install @micropasts/colour-palette

From GitHub Packages

Add a .npmrc file in your project root:

@micropasts:registry=https://npm.pkg.github.com

Then install:

npm install @micropasts/colour-palette

Quick Start

Vanilla JS / ES Modules

import { ColourPalette } from '@micropasts/colour-palette';
import '@micropasts/colour-palette/style.css';

const palette = new ColourPalette('#colour-palette', {
  imageUrl: 'https://example.org/iiif/object-123/full/600,/0/default.jpg',
  theme: 'dark',
  colourCount: 8,
  colourFormat: 'hex',
});

Ensure your HTML contains the target mount element:

<div id="colour-palette"></div>

Call palette.destroy() when removing the component (such as when unmounting a single-page application view) to release event listeners and revoke any temporary blob: object URLs.

Passing an Existing Image or Canvas Element

import { ColourPalette } from '@micropasts/colour-palette';
import '@micropasts/colour-palette/style.css';

const palette = new ColourPalette('#colour-palette', {
  theme: 'light',
  colourCount: 6,
});

const img = document.querySelector('#artefact-photo');
if (img.complete && img.naturalWidth) {
  palette.setImageElement(img);
} else {
  img.addEventListener('load', () => palette.setImageElement(img), { once: true });
}

Embedded / Locked Widget Mode

Hide the file picker, colour count dropdown, and theme switcher when embedding a fixed palette card alongside an artefact record:

import { ColourPalette } from '@micropasts/colour-palette';
import '@micropasts/colour-palette/style.css';

new ColourPalette('#colour-palette', {
  imageUrl: '/images/artefact-preview.jpg',
  theme: 'dark',
  colourCount: 6,
  colourFormat: 'hex',
  showImageSelect: false,
  showColourCount: false,
  showThemeSwitcher: false,
});

Direct Extraction Without Mounting the UI

If you only need the extracted colour data from an already-loaded <img> or <canvas> element without rendering the widget:

import { extractColours } from '@micropasts/colour-palette';

const img = document.querySelector('#artefact-photo');
const { dominant, palette } = extractColours(img, { colourCount: 8 });

console.log('Dominant:', dominant.hex);
console.log('Palette:', palette.map((swatch) => swatch.hex));

Using Custom Proxy Routes

When loading images from origins lacking Access-Control-Allow-Origin headers or rewriting local development URLs, configure proxyRoutes or proxyUrl:

const palette = new ColourPalette('#colour-palette', {
  imageUrl: 'http://localhost:8000/images/finds/1704.jpg',
  proxyRoutes: {
    'http://localhost:8000/images': '/images',
  },
});

You can also pass a resolver function (url) => string:

const palette = new ColourPalette('#colour-palette', {
  imageUrl: 'https://example.org/images/object.jpg',
  proxyRoutes: (url) => `/api/image-proxy?url=${encodeURIComponent(url)}`,
});

Framework Integration Examples

UMD Script Tag

<link rel="stylesheet" href="./node_modules/@micropasts/colour-palette/dist/colour-palette.css" />
<div id="colour-palette"></div>

<script src="./node_modules/@micropasts/colour-palette/dist/colour-palette.umd.cjs"></script>
<script>
  const palette = new MicroPastsColourPalette.ColourPalette('#colour-palette', {
    imageUrl: './examples/portrait.jpg',
    theme: 'dark',
  });
</script>

React

import { useEffect, useRef } from 'react';
import { ColourPalette } from '@micropasts/colour-palette';
import '@micropasts/colour-palette/style.css';

export function ArtefactColourPalette({ imageUrl, theme = 'dark', colourCount = 8 }) {
  const containerRef = useRef(null);
  const instanceRef = useRef(null);

  useEffect(() => {
    if (!containerRef.current) return;
    instanceRef.current = new ColourPalette(containerRef.current, {
      theme,
      colourCount,
    });

    return () => {
      instanceRef.current?.destroy();
      instanceRef.current = null;
    };
  }, []);

  useEffect(() => {
    instanceRef.current?.setTheme(theme);
  }, [theme]);

  useEffect(() => {
    instanceRef.current?.setColourCount(colourCount);
  }, [colourCount]);

  useEffect(() => {
    if (imageUrl) instanceRef.current?.loadImage(imageUrl);
  }, [imageUrl]);

  return <div ref={containerRef} />;
}

Vue 3

<script setup>
import { onMounted, onBeforeUnmount, ref, watch } from 'vue';
import { ColourPalette } from '@micropasts/colour-palette';
import '@micropasts/colour-palette/style.css';

const props = defineProps({
  imageUrl: { type: String, default: '' },
  theme: { type: String, default: 'dark' },
  colourCount: { type: Number, default: 8 },
});

const container = ref(null);
let palette = null;

onMounted(() => {
  palette = new ColourPalette(container.value, {
    imageUrl: props.imageUrl,
    theme: props.theme,
    colourCount: props.colourCount,
  });
});

watch(() => props.imageUrl, (url) => url && palette?.loadImage(url));
watch(() => props.theme, (theme) => palette?.setTheme(theme));
watch(() => props.colourCount, (count) => palette?.setColourCount(count));

onBeforeUnmount(() => palette?.destroy());
</script>

<template>
  <div ref="container" />
</template>

Configuration Options

| Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | imageUrl | string | '' | URL of an image to load and extract on mount. | | image | HTMLImageElement \| HTMLCanvasElement | null | Existing DOM image or canvas element to extract on mount. Takes precedence over imageUrl if both are supplied. | | colourCount | number | 8 | Initial number of palette colours to extract (clamped between 2 and 20). | | colourCounts | number[] | [5, 8, 12] | Preset options rendered in the colour count selector dropdown. Automatically includes colourCount if not already present. | | colourFormat | 'hex' \| 'rgb' \| 'hsl' | 'hex' | Active display and copy format for extracted swatches. | | theme | 'dark' \| 'light' | 'dark' | Initial scoped theme for the widget container. | | showImageSelect | boolean | true | Shows or hides the Select image file input button in the toolbar. | | showInput | boolean \| null | null | Backwards-compatible alias for showImageSelect. | | showColourCount | boolean | true | Shows or hides the colour count selector dropdown in the toolbar. | | showThemeSwitcher | boolean | true | Shows or hides the Theme toggle button in the toolbar. | | maxFileSize | number | 15728640 (15 MB) | Maximum allowed byte size for local files selected via the file input. | | proxyRoutes | object \| function | null | Rewrites image URLs using { prefix: replacement } mappings or a (url) => string resolver function. | | proxyUrl | string | '' | Fallback prefix URL prepended to encodeURIComponent(url) when no proxyRoutes rule matches. | | onExtract | function | null | Called as (result) whenever a palette is extracted, receiving { dominant, palette }. | | onCopy | function | null | Called as (copiedText, swatchOrSwatches) when a user clicks a swatch or Copy all strings. | | onError | function | null | Called as (error) when URL validation, file validation, image loading, or pixel extraction fails. |


Instance Methods

| Method | Signature | Description | | :--- | :--- | :--- | | loadImage | loadImage(url) | Resolves url through resolveUrl(), validates the protocol, and loads the image with crossOrigin = 'anonymous'. | | setImageElement | setImageElement(el) | Extracts colours from an existing HTMLImageElement or HTMLCanvasElement. | | setColourCount | setColourCount(count) | Updates the target swatch count (clamped 2–20), syncs the toolbar selector, and re-runs extraction on the active image. | | setFormat | setFormat('hex' \| 'rgb' \| 'hsl') | Switches the active colour format and re-renders the dominant and palette swatches. | | setTheme | setTheme('dark' \| 'light') | Sets the scoped theme on the root widget container. | | toggleTheme | toggleTheme() | Toggles between 'dark' and 'light' themes. | | getColours | getColours(format?) | Returns an array of formatted colour strings (string[]) for the current palette in the requested format (defaults to active colourFormat). Returns [] if no image has been extracted yet. | | resolveUrl | resolveUrl(url) | Resolves an image URL through configured proxyRoutes or proxyUrl. | | destroy | destroy() | Revokes any active blob: object URLs, removes DOM event listeners, destroys toolbar/swatch sub-components, and clears the mount container. |


Data Structures & Callbacks

Each swatch object returned in result.dominant and result.palette (or passed to onExtract and onCopy) has the following shape:

{
  index: 1,                        // 0 for dominant, 1..N for palette swatches
  hex: '#2F4858',                  // Uppercase HEX string
  rgb: 'rgb(47, 72, 88)',          // CSS rgb() string
  hsl: 'hsl(203, 30%, 26%)',       // CSS hsl() string
  values: {
    hex: '#2F4858',
    rgb: 'rgb(47, 72, 88)',
    hsl: 'hsl(203, 30%, 26%)',
  },
  isDark: true,                    // Luminance flag from ColorThief
  textClass: 'text-white',         // Contrast-safe Tailwind text class ('text-white' or 'text-slate-900')
}

Input Sanitization & CORS

  • URL Validation: loadImage() and setImageElement() validate URLs via the URL API, permitting only http:, https:, blob:, and validated raster data:image/*;base64,... strings. Unsupported protocols (such as javascript: or file:) trigger onError and display an inline error banner.
  • File Upload Validation: Local files chosen through the file input are checked against an explicit raster MIME allowlist (image/jpeg, image/png, image/webp, image/gif, image/avif), verified against binary magic-byte signatures, and bounded by maxFileSize. SVG uploads are rejected by default.
  • CORS Requirement: When extracting colours from remote URLs, the browser reads pixel data via an internal HTML5 <canvas>. Remote servers must respond with appropriate Access-Control-Allow-Origin headers (or be routed through a same-origin proxy via proxyRoutes / proxyUrl), otherwise the browser's canvas taint security will prevent extraction.

Local Development & GitHub Pages Build

# Install dependencies
npm install

# Start local Vite dev server
npm run dev

# Build npm library bundle (ES, UMD, and bundled Tailwind CSS) into dist/
npm run build

# Build static demo site into docs/ for GitHub Pages
npm run build:docs

# Preview production build locally
npm run preview

# Run unit tests
npm test

License

This project is licensed under the MIT license.