Repository: JoseRFelix/react-toggle-dark-mode Branch: master Commit: a3cc623a837a Files: 18 Total size: 25.0 KB Directory structure: gitextract_1hconnob/ ├── .changeset/ │ ├── README.md │ └── config.json ├── .github/ │ └── workflows/ │ └── main.yml ├── .gitignore ├── .husky/ │ └── pre-commit ├── CHANGELOG.md ├── LICENSE ├── README.md ├── example/ │ ├── .npmignore │ ├── index.html │ ├── index.tsx │ ├── package.json │ └── tsconfig.json ├── package.json ├── pnpm-workspace.yaml ├── src/ │ └── index.tsx ├── test/ │ └── index.test.tsx └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .changeset/README.md ================================================ # Changesets Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works with multi-package repos, or single-package repos to help you version and publish your code. You can find the full documentation for it [in our repository](https://github.com/changesets/changesets) We have a quick list of common questions to get you started engaging with this project in [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) ================================================ FILE: .changeset/config.json ================================================ { "$schema": "https://unpkg.com/@changesets/config@3.1.2/schema.json", "changelog": "@changesets/cli/changelog", "commit": false, "fixed": [], "linked": [], "access": "public", "baseBranch": "main", "updateInternalDependencies": "patch", "ignore": ["example"] } ================================================ FILE: .github/workflows/main.yml ================================================ name: CI on: [push] jobs: build: runs-on: ubuntu-latest steps: - name: Begin CI... uses: actions/checkout@v4 - name: Setup pnpm uses: pnpm/action-setup@v4 - name: Use Node 20 uses: actions/setup-node@v4 with: node-version: 20.x cache: pnpm - name: Setup Bun uses: oven-sh/setup-bun@v2 - name: Install dependencies run: pnpm install --frozen-lockfile env: CI: true - name: Lint run: pnpm lint env: CI: true - name: Test run: pnpm test env: CI: true - name: Build run: pnpm build env: CI: true react-compatibility: runs-on: ubuntu-latest strategy: fail-fast: false matrix: react-version: [16.14.0, 17.0.2, 18.3.1, 19.0.0] steps: - name: Begin compatibility checks... uses: actions/checkout@v4 - name: Setup pnpm uses: pnpm/action-setup@v4 - name: Use Node 20 uses: actions/setup-node@v4 with: node-version: 20.x cache: pnpm - name: Setup Bun uses: oven-sh/setup-bun@v2 - name: Install dependencies run: pnpm install --frozen-lockfile env: CI: true - name: Test React ${{ matrix.react-version }} compatibility run: pnpm add -Dw react@${{ matrix.react-version }} react-dom@${{ matrix.react-version }} --ignore-scripts - name: Run tests run: pnpm test env: CI: true - name: Build with matrix React version run: pnpm build env: CI: true ================================================ FILE: .gitignore ================================================ *.log .DS_Store node_modules .pnpm-store .cache dist .parcel-cache ================================================ FILE: .husky/pre-commit ================================================ pnpm lint ================================================ FILE: CHANGELOG.md ================================================ # react-toggle-dark-mode ## 2.0.0 ### Major Changes - Modernize build setup and harden DarkModeSwitch for React 16–19 ### Changed - Migrated project tooling from Yarn to pnpm. - Updated root scripts and package metadata for pnpm-based workflows. - Switched CI to modern GitHub Actions (`checkout@v4`, `setup-node@v4`, Node 20) and pnpm caching. - Added a React compatibility CI matrix for React 16, 17, 18, and 19. - Replaced `react-spring` import usage with `@react-spring/web`. - Updated dependencies/devDependencies across root and example app (React 19, newer TypeScript/tooling). - Modernized example app bootstrapping to `createRoot` and module script loading. - Updated README install instructions to show pnpm usage. - Added `.pnpm-store` to `.gitignore`. ### Improved - Refactored `DarkModeSwitch` animation property merging to avoid mutating defaults. - Improved prop typing (button-oriented props) and event handling in `DarkModeSwitch`. - Improved accessibility defaults (`role="switch"`, `aria-checked`, default label behavior). - Strengthened test suite with coverage for: - animation-property merge behavior - non-mutation of defaults - accessibility attributes - unique mask IDs across multiple component instances ### Removed - Removed legacy Yarn lockfiles (`yarn.lock`, `example/yarn.lock`). ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2020 Jose Felix Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================

React Toggle Dark Mode

Version License: MIT PRs Welcome Bundle size

> 🌃 Animated dark mode toggle as seen in blogs! Supports React 16.14+ through 19. ![Interactive sun and moon transition](./docs/demo.gif) ## Prerequisites - node >=20 ## Installation ```shell npm i react-toggle-dark-mode ``` or with pnpm: ```shell pnpm add react-toggle-dark-mode ``` ## Usage ```jsx import * as React from 'react'; import { createRoot } from 'react-dom/client'; import { DarkModeSwitch } from 'react-toggle-dark-mode'; const App = () => { const [isDarkMode, setDarkMode] = React.useState(false); const toggleDarkMode = (checked: boolean) => { setDarkMode(checked); }; return ( ); }; const rootElement = document.getElementById('root'); if (!rootElement) { throw new Error('Unable to find root element'); } createRoot(rootElement).render(); ``` ## API ### DarkModeSwitch #### Props | Name | Type | Default Value | Description | | ------------------- | -------------------------------------------------- | ------------------------------- | -------------------------------------------------------------------------------------------- | | onChange | \(checked: boolean\) => void | | Event that triggers when icon is clicked. | | checked | boolean | false | Current icon state. | | style | React.CSSProperties | | CSS properties object applied to the button wrapper. | | size | number \| string | 24 | SVG size. | | animationProperties | Partial animation properties object | defaultProperties \(see below\) | Override only the fields you want; missing fields are merged with defaults. | | moonColor | string | white | Color of the moon. | | sunColor | string | black | Color of the sun. | | aria-label | string | Toggle dark mode | Accessible label for the control. Ignored when `aria-labelledby` is provided. | | aria-labelledby | string | | Links the control to an external label element. | | onClick | \(event: React.MouseEvent\)=>void | | Optional button click handler. Call `event.preventDefault()` to prevent toggling on click. | All valid button attributes (except `children`) are forwarded to the underlying button element. ### Default Animation Properties ```javascript const defaultProperties = { dark: { circle: { r: 9, }, mask: { cx: '50%', cy: '23%', }, svg: { transform: 'rotate(40deg)', }, lines: { opacity: 0, }, }, light: { circle: { r: 5, }, mask: { cx: '100%', cy: '0%', }, svg: { transform: 'rotate(90deg)', }, lines: { opacity: 1, }, }, springConfig: { mass: 4, tension: 250, friction: 35 }, }; ``` ## Contributors Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):

Jose Felix

💻 📖 ⚠️
This project follows the [all-contributors](https://allcontributors.org) specification. Contributions of any kind are welcome! ## Show your support Give a ⭐️ if this project helped you! ================================================ FILE: example/.npmignore ================================================ node_modules .cache dist ================================================ FILE: example/index.html ================================================ Playground
================================================ FILE: example/index.tsx ================================================ import * as React from 'react'; import { createRoot } from 'react-dom/client'; import { DarkModeSwitch } from '../src'; function arrayN(size: number) { return new Array(size).fill(undefined); } const App = () => { const [isDarkMode, setDarkMode] = React.useState(false); const [toggleAmount, setToggleAmount] = React.useState(0); const toggleDarkMode = (checked: boolean) => { setDarkMode(checked); }; const addToggle = () => { setToggleAmount((prevValue) => prevValue + 1); }; return (
{arrayN(toggleAmount).map((_, index) => ( ))}
); }; const rootElement = document.getElementById('root'); if (!rootElement) { throw new Error('Unable to find root element'); } createRoot(rootElement).render(); ================================================ FILE: example/package.json ================================================ { "name": "example", "version": "1.0.0", "license": "MIT", "private": true, "scripts": { "start": "parcel index.html", "build": "parcel build index.html" }, "dependencies": { "react": "19.0.0", "react-dom": "19.0.0" }, "devDependencies": { "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", "parcel": "^2.16.4", "typescript": "^3.4.5" } } ================================================ FILE: example/tsconfig.json ================================================ { "compilerOptions": { "allowSyntheticDefaultImports": false, "target": "es5", "module": "commonjs", "jsx": "react", "moduleResolution": "node", "noImplicitAny": false, "noUnusedLocals": false, "noUnusedParameters": false, "removeComments": true, "strictNullChecks": true, "preserveConstEnums": true, "sourceMap": true, "lib": ["es2015", "es2016", "dom"], "baseUrl": ".", "types": ["node"] } } ================================================ FILE: package.json ================================================ { "packageManager": "pnpm@10.28.2", "version": "2.0.0", "license": "MIT", "main": "dist/index.js", "typings": "dist/index.d.ts", "private": false, "files": [ "dist", "src" ], "engines": { "node": ">=20" }, "scripts": { "start": "tsdx watch", "build": "tsdx build", "test": "tsdx test", "lint": "tsdx lint", "prepare": "husky && tsdx build" }, "peerDependencies": { "react": ">=16" }, "prettier": { "printWidth": 80, "semi": true, "singleQuote": true, "trailingComma": "es5" }, "name": "react-toggle-dark-mode", "description": "Animated dark mode toggle as seen in blogs!", "author": "Jose R. Felix (https://jfelix.info)", "module": "dist/react-toggle-dark-mode.esm.js", "repository": { "type": "git", "url": "https://github.com/JoseRFelix/react-toggle-dark-mode" }, "bugs": { "url": "https://github.com/JoseRFelix/react-toggle-dark-mode/issues" }, "homepage": "https://github.com/JoseRFelix/react-toggle-dark-mode#readme", "devDependencies": { "@types/jest": "^24.9.1", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", "bunchee": "^6.9.4", "husky": "^9.1.7", "react": "19.0.0", "react-dom": "19.0.0", "tsdx": "^2.0.0", "tslib": "^2.8.1", "typescript": "^5.9.3", "vitest": "^4.0.18", "@changesets/cli": "^2.29.8" }, "dependencies": { "@react-spring/web": "^10.0.3" } } ================================================ FILE: pnpm-workspace.yaml ================================================ packages: - . - example ================================================ FILE: src/index.tsx ================================================ import * as React from 'react'; import { useSpring, animated } from '@react-spring/web'; export const defaultProperties = { dark: { circle: { r: 9, }, mask: { cx: '50%', cy: '23%', }, svg: { transform: 'rotate(40deg)', }, lines: { opacity: 0, }, }, light: { circle: { r: 5, }, mask: { cx: '100%', cy: '0%', }, svg: { transform: 'rotate(90deg)', }, lines: { opacity: 1, }, }, springConfig: { mass: 4, tension: 250, friction: 35 }, }; let REACT_TOGGLE_DARK_MODE_GLOBAL_ID = 0; type AnimationProperties = typeof defaultProperties; type ThemeProperties = AnimationProperties['dark']; type PartialThemeProperties = { circle?: Partial; mask?: Partial; svg?: Partial; lines?: Partial; }; type DarkModeSwitchAnimationProperties = { dark?: PartialThemeProperties; light?: PartialThemeProperties; springConfig?: Partial; }; const mergeThemeProperties = ( theme: ThemeProperties, customTheme?: PartialThemeProperties ): ThemeProperties => ({ circle: { ...theme.circle, ...customTheme?.circle }, mask: { ...theme.mask, ...customTheme?.mask }, svg: { ...theme.svg, ...customTheme?.svg }, lines: { ...theme.lines, ...customTheme?.lines }, }); const resolveAnimationProperties = ( animationProperties?: DarkModeSwitchAnimationProperties ): AnimationProperties => { if (!animationProperties || animationProperties === defaultProperties) { return defaultProperties; } return { dark: mergeThemeProperties( defaultProperties.dark, animationProperties.dark ), light: mergeThemeProperties( defaultProperties.light, animationProperties.light ), springConfig: { ...defaultProperties.springConfig, ...animationProperties.springConfig, }, }; }; type ButtonProps = Omit< React.ButtonHTMLAttributes, 'onChange' | 'children' >; export interface Props extends ButtonProps { onChange: (checked: boolean) => void; checked: boolean; style?: React.CSSProperties; size?: number | string; animationProperties?: DarkModeSwitchAnimationProperties; moonColor?: string; sunColor?: string; } export const DarkModeSwitch: React.FC = ({ onChange, checked = false, size = 24, animationProperties, moonColor = 'white', sunColor = 'black', style, onClick: onClickProp, role, tabIndex, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, ...rest }) => { const [id] = React.useState(() => { REACT_TOGGLE_DARK_MODE_GLOBAL_ID += 1; return REACT_TOGGLE_DARK_MODE_GLOBAL_ID; }); const properties = React.useMemo( () => resolveAnimationProperties(animationProperties), [animationProperties] ); const { circle, svg, lines, mask } = properties[checked ? 'dark' : 'light']; const { springConfig } = properties; const svgContainerProps = useSpring({ ...svg, config: springConfig, }); const centerCircleProps = useSpring({ ...circle, config: springConfig, }); const maskedCircleProps = useSpring({ ...mask, config: springConfig, }); const linesProps = useSpring({ ...lines, config: springConfig, }); const toggle = React.useCallback( () => onChange(!checked), [checked, onChange] ); const onClick = React.useCallback( (event: React.MouseEvent) => { event.stopPropagation(); onClickProp?.(event); if (!event.defaultPrevented) { toggle(); } }, [onClickProp, toggle] ); const uniqueMaskId = `circle-mask-${id}`; return ( ); }; ================================================ FILE: test/index.test.tsx ================================================ import * as React from 'react'; import { useSpring } from '@react-spring/web'; import { renderToStaticMarkup } from 'react-dom/server'; import { describe, expect, it, vi } from 'vitest'; import { DarkModeSwitch, defaultProperties } from '../src'; vi.mock('@react-spring/web', async () => { const actual = await vi.importActual('@react-spring/web'); return { ...actual, useSpring: vi.fn((props: unknown) => props), }; }); describe('DarkModeSwitch', () => { it('renders without crashing', () => { // Keep this test React-version-agnostic for the CI matrix (16/17/18/19): // server rendering avoids client API differences like render/createRoot. const html = renderToStaticMarkup( {}} checked={false} /> ); expect(html).toContain(' { const originalDarkTransform = defaultProperties.dark.svg.transform; const originalLightRadius = defaultProperties.light.circle.r; const originalTension = defaultProperties.springConfig.tension; renderToStaticMarkup( {}} checked={false} animationProperties={{ dark: { svg: { transform: 'rotate(0deg)' } }, springConfig: { tension: 1 }, }} /> ); expect(defaultProperties.dark.svg.transform).toBe(originalDarkTransform); expect(defaultProperties.light.circle.r).toBe(originalLightRadius); expect(defaultProperties.springConfig.tension).toBe(originalTension); }); it('merges custom animation properties with defaults', () => { const springMock = vi.mocked(useSpring); springMock.mockClear(); renderToStaticMarkup( {}} checked={true} animationProperties={{ dark: { svg: { transform: 'rotate(0deg)' }, mask: { cx: '42%' }, }, springConfig: { tension: 1 }, }} /> ); const [svgProps, circleProps, maskProps, linesProps] = springMock.mock.calls.map( ([props]) => props as any ); const expectedConfig = { ...defaultProperties.springConfig, tension: 1, }; expect(springMock).toHaveBeenCalledTimes(4); expect(svgProps.transform).toBe('rotate(0deg)'); expect(svgProps.config).toEqual(expectedConfig); expect(circleProps.r).toBe(defaultProperties.dark.circle.r); expect(circleProps.config).toEqual(expectedConfig); expect(maskProps.cx).toBe('42%'); expect(maskProps.cy).toBe(defaultProperties.dark.mask.cy); expect(linesProps.opacity).toBe(defaultProperties.dark.lines.opacity); expect(linesProps.config).toEqual(expectedConfig); }); it('renders switch accessibility attributes by default', () => { const html = renderToStaticMarkup( {}} checked={true} /> ); expect(html).toContain('role="switch"'); expect(html).toContain('aria-checked="true"'); expect(html).toContain('aria-label="Toggle dark mode"'); expect(html).toContain('tabindex="0"'); }); it('supports aria-labelledby without requiring an aria-label', () => { const html = renderToStaticMarkup( {}} checked={false} aria-labelledby="dark-mode-switch-label" /> ); expect(html).toContain('aria-labelledby="dark-mode-switch-label"'); expect(html).not.toContain('aria-label="Toggle dark mode"'); }); it('generates unique mask ids across multiple instances', () => { const html = renderToStaticMarkup( <> {}} checked={false} /> {}} checked={true} /> ); const ids = html.match(/circle-mask-\d+/g) || []; const uniqueIds = Array.from(new Set(ids)); expect(uniqueIds.length).toBe(2); }); }); ================================================ FILE: tsconfig.json ================================================ { "include": ["src", "types"], "compilerOptions": { "module": "esnext", "lib": ["dom", "esnext"], "importHelpers": true, "declaration": true, "sourceMap": true, "rootDir": "./src", "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "moduleResolution": "node", "baseUrl": "./", "paths": { "*": ["src/*", "node_modules/*"] }, "jsx": "react", "esModuleInterop": true } }