Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@

## Key constraint: bundle size

Every picker must stay under 3 KB gzipped (enforced by `size-limit` in package.json). This shapes all code decisions: `Object.assign` over spread (smaller output), keyCodes over key strings, no dependencies, manually optimized algorithms. Always run `npm run size` after changes that add code.
Every picker must stay under 3.1 KB gzipped (enforced by `size-limit` in package.json). This shapes all code decisions: `Object.assign` over spread (smaller output), keyCodes over key strings, no dependencies, manually optimized algorithms. Always run `npm run size` after changes that add code.
Comment thread
omgovich marked this conversation as resolved.
Resolved
Comment thread
omgovich marked this conversation as resolved.
Resolved

## Architecture

A ~2.8 KB color picker component library for React. Zero dependencies.
A ~3.1 KB color picker component library for React. Zero dependencies.

### Internal color model: HSVA

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@

## Features

- 🗜 **Small**: Just 2,8 KB gzipped ([13x lighter](#why-react-colorful) than **react-color**).
- 🗜 **Small**: Just 3,1 KB gzipped ([12x lighter](#why-react-colorful) than **react-color**).
- 🌳 **Tree-shakeable**: Only the parts you use will be imported into your app's bundle.
- 🚀 **Fast**: Built with hooks and functional components only.
- 🛡 **Bulletproof**: Written in strict TypeScript and has 100% test coverage.
Expand Down
7 changes: 7 additions & 0 deletions demo/src/components/DevTools.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,13 @@ export const DevTools = (): JSX.Element => {
PickerComponent={RgbColorPicker}
initialColor={{ r: 60, g: 80, b: 120 }}
/>

<PickerPreview<RgbColor>
shadow
title="RGB (Shadow DOM)"
PickerComponent={RgbColorPicker}
initialColor={{ r: 60, g: 80, b: 120 }}
/>
</div>
);
};
5 changes: 4 additions & 1 deletion demo/src/components/PickerPreview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,20 @@ import Frame from "react-frame-component";
import { HexColorInput } from "../../../src";
import { ColorPickerBaseProps, AnyColor } from "../../../src/types";
import { PreviewContainer, PreviewDemo, PreviewOutput, PreviewTitle } from "../styles";
import { ShadowDom } from "./ShadowDom";

interface Props<T extends AnyColor> {
title: string;
frame?: boolean;
shadow?: boolean;
PickerComponent: React.ComponentType<Partial<ColorPickerBaseProps<T>>>;
initialColor?: T;
}

export function PickerPreview<T extends AnyColor>({
title,
frame,
shadow,
PickerComponent,
initialColor,
}: Props<T>): JSX.Element {
Expand All @@ -25,7 +28,7 @@ export function PickerPreview<T extends AnyColor>({
setColor(color);
};

const Wrapper = frame ? Frame : React.Fragment;
const Wrapper = frame ? Frame : shadow ? ShadowDom : React.Fragment;

return (
<PreviewContainer>
Expand Down
18 changes: 18 additions & 0 deletions demo/src/components/ShadowDom.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import React, { useState, useCallback } from "react";
import ReactDOM from "react-dom";

interface Props {
children: React.ReactNode;
}

export const ShadowDom = ({ children }: Props): JSX.Element => {
const [root, setRoot] = useState<ShadowRoot | null>(null);

const hostRef = useCallback((host: HTMLDivElement | null) => {
if (host && !host.shadowRoot) {
setRoot(host.attachShadow({ mode: "open" }));
}
}, []);

return <div ref={hostRef}>{root && ReactDOM.createPortal(children, root)}</div>;
Comment thread
omgovich marked this conversation as resolved.
Resolved
};
10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "react-colorful",
"version": "5.7.0",
"description": "🎨 A tiny (2,8 KB) color picker component for React and Preact apps. Fast, well-tested, dependency-free, mobile-friendly and accessible",
"description": "🎨 A tiny (3,1 KB) color picker component for React and Preact apps. Fast, well-tested, dependency-free, mobile-friendly and accessible",
"source": "src/index.ts",
"main": "dist/index.js",
"module": "dist/index.module.js",
Expand Down Expand Up @@ -36,7 +36,7 @@
"path": "dist/index.module.js",
"name": "HexColorPicker",
"import": "{ HexColorPicker }",
"limit": "3.1 KB"
"limit": "3.12 KB"
},
{
"path": "dist/index.module.js",
Expand Down Expand Up @@ -96,7 +96,7 @@
"path": "dist/index.module.js",
"name": "RgbaColorPicker",
"import": "{ RgbaColorPicker }",
"limit": "3 KB"
"limit": "3.1 KB"
},
{
"path": "dist/index.module.js",
Expand All @@ -108,7 +108,7 @@
"path": "dist/index.module.js",
"name": "RgbaStringColorPicker",
"import": "{ RgbaStringColorPicker }",
"limit": "3.2 KB"
"limit": "3.21 KB"
},
{
"path": "dist/index.module.js",
Expand Down Expand Up @@ -197,4 +197,4 @@
"typescript": "^4.2.3",
"use-throttled-effect": "0.0.7"
}
}
}
41 changes: 29 additions & 12 deletions src/hooks/useStyleSheet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,42 @@ import { getNonce } from "../utils/nonce";
// Bundler is configured to load this as a processed minified CSS-string
import styles from "../css/styles.css";

const styleElementMap: Map<Document, HTMLStyleElement> = new Map();
type Root = Document | ShadowRoot;

// `WeakMap` lets detached shadow roots / iframe documents be garbage-collected
// once nothing else references them. Available in IE11 for the operations we use
// (`has`, `set` as a statement — we don't chain or pass an iterable constructor).
const styleElementMap: WeakMap<Root, HTMLStyleElement> = new WeakMap();

/**
* Injects CSS code into the document's <head>
* Injects CSS code into the closest root node (Document or ShadowRoot)
* so the picker is styled correctly when mounted inside a shadow tree
* or a separate document (e.g. an iframe).
*/
export const useStyleSheet = (nodeRef: RefObject<HTMLDivElement>): void => {
useIsomorphicLayoutEffect(() => {
const parentDocument = nodeRef.current ? nodeRef.current.ownerDocument : document;
const node = nodeRef.current;
if (typeof document === "undefined" || !node) return;

// `getRootNode()` returns the closest ShadowRoot if the picker lives in one,
// otherwise the owning Document. Falls back to `ownerDocument` for IE11,
// which has neither `getRootNode` nor Shadow DOM. For disconnected nodes
// `getRootNode()` can return an arbitrary ancestor (e.g. an Element), so
// we discriminate via `head`/`host` and fall back to `ownerDocument`.
const raw = node.getRootNode ? node.getRootNode() : node.ownerDocument;
const root = (raw && ("head" in raw || "host" in raw) ? raw : node.ownerDocument) as Root;
if (styleElementMap.has(root)) return;

if (typeof parentDocument !== "undefined" && !styleElementMap.has(parentDocument)) {
const styleElement = parentDocument.createElement("style");
styleElement.innerHTML = styles;
styleElementMap.set(parentDocument, styleElement);
// Document has `head`; ShadowRoot doesn't — use it to pick the injection target.
const target = "head" in root ? root.head : root;
const styleElement = (target.ownerDocument || document).createElement("style");
styleElement.innerHTML = styles;

// Conform to CSP rules by setting `nonce` attribute to the inline styles
const nonce = getNonce();
if (nonce) styleElement.setAttribute("nonce", nonce);
// Conform to CSP rules by setting `nonce` attribute to the inline styles
const nonce = getNonce();
if (nonce) styleElement.setAttribute("nonce", nonce);

parentDocument.head.appendChild(styleElement);
}
styleElementMap.set(root, styleElement);
target.appendChild(styleElement);
}, []);
};
25 changes: 25 additions & 0 deletions tests/shadowDom.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import React from "react";
import { render, cleanup } from "@testing-library/react";
import { HexColorPicker } from "../src";

const hosts = [];

afterEach(() => {
cleanup();
while (hosts.length) hosts.pop().remove();
});

it("Injects styles into the closest ShadowRoot when mounted inside one", () => {
const host = document.createElement("div");
document.body.appendChild(host);
hosts.push(host);

const shadow = host.attachShadow({ mode: "open" });
const mount = document.createElement("div");
shadow.appendChild(mount);

render(<HexColorPicker color="#F00" />, { container: mount });

// `useStyleSheet` runs in a layout effect, so the <style> is present synchronously.
expect(shadow.querySelector("style")).not.toBeNull();
Comment thread
omgovich marked this conversation as resolved.
Resolved
});
Loading