npm.io
8.1.0 • Published 22h ago

magic-pill

Licence
MIT
Version
8.1.0
Deps
0
Size
196 kB
Vulns
0
Weekly
0

Magic Pill

Let it empower you.

Disclaimer

Magic Pill 8.x is usable and maintained: it gets bug fixes and security updates. Please keep in mind that its API isn't final yet, though. The next major version will rework it (with breaking changes), and the documentation is still being improved.

Thank you !!

Thank you for your patience and to all people who already have shown interest in Magic Pill, it's my very first npm package and I couldn't ask for a better reception of my package after only a few days after its initial release.

Badges

npm version npm downloads DeepScan grade Known Vulnerabilities install size

Introduction

Magic Pill is a powerful React component that lets you show contextual information to your users in multiple ways. It can function as a notification system mimicking Apple's Dynamic Island, or as a dynamic navbar for seamless navigation. Built with TypeScript for enhanced type safety and developer experience.

Features

  • Multiple modes: Notification system and Dynamic Navbar
  • Written in TypeScript with comprehensive type definitions
  • Highly customizable React component with strongly typed props
  • Fully customized styling based on CSS variables for easy theme adaptation
  • Works in any React 18+ app: Next.js (Server Components included), Vite, React Router…
  • Zero runtime dependencies: React is the only peer dependency
  • Accessible: announced by screen readers, pauses on hover and keyboard focus, respects reduced motion
  • Lightweight and efficient

Installation

npm

Magic Pill is available on npm, simply use the following command and you're ready to go!

npm install magic-pill
Requirements
  • React and React DOM 18 or later (peer dependencies).
  • Next.js is optional: Magic Pill works in any React app.
  • TypeScript is optional: the type definitions ship with the package.

No CDN build: Magic Pill is published for bundlers (Next.js, Vite, webpack…) as ES modules and CommonJS. It has no UMD build, so it can't be loaded with a plain <script> tag.

How to use it?

Import styles

For it to work properly, you need to import styles in your app (we recommend importing it into your root layout or App file).

// Import in your Next.js or React project
import "magic-pill/dist/magicpill.css";
// or, equivalently
import "magic-pill/magicpill.css";

Fonts: the stylesheet loads its fonts (Lexend and Overlock) from Google Fonts with a CSS @import. Next.js 16's default bundler, Turbopack, drops that @import. If the pill shows a generic font, load the fonts yourself (for example with next/font) or point --mp__font-text and --mp__font-accent to your own fonts (see Customization).

Usage with React/Next.js

Magic Pill is designed to be used with a Context to manage its state globally. Here's how to set it up:

MagicPill is a Client Component, so you can also render it directly from a Server Component. The Context below is what lets any part of your app change its content.

  1. First, create a context for Magic Pill (e.g., in app/contexts/magicPillContext.tsx):
"use client"
import React, { createContext, useContext, useState } from "react";
import { MagicPillType, Mode, NotificationIcon, CTAIcon, MagicPillNavbarItem } from "magic-pill";
import { updateMode, updateNotificationIcon, updateNotificationMessage, updateCTAIcon, updateCTALabel, updateCTALink, updateInfoTitle, updateInfoContent, updateInfoCloseLabel, updateNavItemLabel, updateNavItemLink, updateNavItemIcon, addNavItem, deleteNavItem } from "magic-pill";

const defaultPillData: MagicPillType = {
  mode: "navbar",
  navbar: {
    navItems: [
      {
        icon: "arrow",
        label: "mp-test",
        link: "/mp-test"
      },
      {
        icon: "cross",
        label: "demo",
        link: "/demo"
      }
    ]
  }
};

interface MagicPillContextType {
  pillData: MagicPillType;
  setPillData: (data: MagicPillType) => void;
  // Direct data manipulation methods
  updateMode: (mode: Mode) => void;
  updateNotificationIcon: (icon: NotificationIcon) => void;
  updateNotificationMessage: (message: string) => void;
  updateCTAIcon: (icon: CTAIcon) => void;
  updateCTALabel: (label: string) => void;
  updateCTALink: (link: string) => void;
  updateInfoTitle: (title: string) => void;
  updateInfoContent: (content: string) => void;
  updateInfoCloseLabel: (closeLabel: string) => void;
  updateNavItemLabel: (label: string, index: number) => void;
  updateNavItemLink: (link: string, index: number) => void;
  updateNavItemIcon: (icon: CTAIcon, index: number) => void;
  addNavItem: (navItem: MagicPillNavbarItem) => void;
  deleteNavItem: (index: number) => void;
}

const MagicPillContext = createContext<MagicPillContextType>({
  pillData: defaultPillData,
  setPillData: () => {},
  updateMode: () => {},
  updateNotificationIcon: () => {},
  updateNotificationMessage: () => {},
  updateCTAIcon: () => {},
  updateCTALabel: () => {},
  updateCTALink: () => {},
  updateInfoTitle: () => {},
  updateInfoContent: () => {},
  updateInfoCloseLabel: () => {},
  updateNavItemLabel: () => {},
  updateNavItemLink: () => {},
  updateNavItemIcon: () => {},
  addNavItem: () => {},
  deleteNavItem: () => {},
});

export const useMagicPill = () => useContext(MagicPillContext);

export const MagicPillProvider = ({ 
  children 
}: { 
  children: React.ReactNode 
}) => {
  const [pillData, setPillData] = useState<MagicPillType>(defaultPillData);

  // Create wrapper functions that use the handlers with the local setPillData
  const contextValue: MagicPillContextType = {
    pillData,
    setPillData,
    updateMode: (mode: Mode) => updateMode(mode, setPillData),
    updateNotificationIcon: (icon: NotificationIcon) => updateNotificationIcon(icon, setPillData),
    updateNotificationMessage: (message: string) => updateNotificationMessage(message, setPillData),
    updateCTAIcon: (icon: CTAIcon) => updateCTAIcon(icon, setPillData),
    updateCTALabel: (label: string) => updateCTALabel(label, setPillData),
    updateCTALink: (link: string) => updateCTALink(link, setPillData),
    updateInfoTitle: (title: string) => updateInfoTitle(title, setPillData),
    updateInfoContent: (content: string) => updateInfoContent(content, setPillData),
    updateInfoCloseLabel: (closeLabel: string) => updateInfoCloseLabel(closeLabel, setPillData),
    updateNavItemLabel: (label: string, index: number) => updateNavItemLabel(label, index, setPillData),
    updateNavItemLink: (link: string, index: number) => updateNavItemLink(link, index, setPillData),
    updateNavItemIcon: (icon: CTAIcon, index: number) => updateNavItemIcon(icon, index, setPillData),
    addNavItem: (navItem: MagicPillNavbarItem) => addNavItem(navItem, setPillData),
    deleteNavItem: (index: number) => deleteNavItem(index, setPillData),
  };

  return (
    <MagicPillContext.Provider value={contextValue}>
      {children}
    </MagicPillContext.Provider>
  );
};
  1. Wrap your app with the provider (in app/layout.tsx):
import "magic-pill/dist/magicpill.css";
import { MagicPillProvider } from "./contexts/magicPillContext";
import { MagicPillInitializer } from "./contexts/magicPillInitializer";

export default function RootLayout({ children }) {

  return (
    <html lang="en">
      <body>
        <MagicPillProvider>
          {children}
          <MagicPillInitializer />
        </MagicPillProvider>
      </body>
    </html>
  );
}
  1. Create an initializer file for Magic Pill (e.g., in app/contexts/magicPillInitializer.tsx):
"use client"
import { MagicPill } from "magic-pill";
import { useMagicPill } from "./magicPillContext";

export const MagicPillInitializer = () => {
  const { pillData } = useMagicPill();

  return (
   <MagicPill pillData={pillData}/>
  )
};

| At this point, if you launch you app, Magic Pill should appear in your view

  1. Use Magic Pill anywhere in your app (e.g., in app/demo/page.tsx):
"use client"
import { useEffect } from "react";
import { useMagicPill } from "../contexts/magicPillContext";

export default function MPTest() {
  const { setPillData } = useMagicPill();

  useEffect(() => {
    setPillData({ mode: "notification", notification: { icon: "info", message: "Hello, world!" } });
  }, []);

  return (
   <h1>Magic Pill Demo Page</h1>
  );
}

It really is as simple as that, to use Magic Pill, once the setup is done

A notification appears as a small pill, expands after 2.5 s, and hides itself 5 s later (it stays open while hovered or focused). Setting a notification with different content shows the pill again.

Update Magic Pill's content granularly

Magic Pill, right from the start, has been thought out to be as highly customizable as possible. To help you use it in the best way possible, a collection of handlers is part of the package.

  • updateMode - Change Magic Pill's mode between "notification" and "navbar"
  • updateNotificationIcon - Change the main notification icon
  • updateNotificationMessage - Change the main notification message
  • updateCTAIcon - Change the notification's CTA (Call To Action) icon
  • updateCTALabel - Change the notification's CTA (Call To Action) label
  • updateCTALink - Change the notification's CTA (Call To Action) redirection link
  • updateInfoTitle - Change the notification's expanded info title
  • updateInfoContent - Change the notification's expanded info main content
  • updateInfoCloseLabel - Change the notification's expanded info close button's label
  • updateNavItemLabel - Change a navbar item's label
  • updateNavItemLink - Change a navbar item's link
  • updateNavItemIcon - Change a navbar item's icon
  • handleActiveNavItem - Automatically working handler directly used by the navbar to update the active link
  • addNavItem - Add an item to the navbar
  • deleteNavItem - Delete an item from the navbar
Security: info.content is raw HTML

The notification's expanded info content (notification.info.content, or updateInfoContent) is rendered as raw HTML, without any sanitising, so that you can format it.

Never put user input or any other untrusted text in it (form values, URL parameters, data from an API or a database that users can write to…). Doing so lets anyone inject scripts into your page (XSS).

  • Only pass HTML that you wrote yourself.
  • If you really need to display external text there, sanitise it first with a dedicated library such as DOMPurify.

The message, the info title and the labels are rendered as plain text, so they're safe. Links (cta.link, navbar link) go into an href: if they can come from users, only allow http(s) or relative URLs, because React 18 doesn't block javascript: URLs (React 19 does).

A future major version will replace this HTML string with regular React content.

Available Icons
Notification Icons
  • "info" - Information icon
  • "checkmark" - Success/confirmation icon
  • "questionmark" - Help/question icon
  • "coupon" - Coupon/offer icon
  • "" - No icon
CTA (Call to Action) Icons
  • "arrow" - Arrow icon
  • "box" - Box icon
  • "checkmark" - Checkmark icon
  • "cross" - Cross/close icon
  • "info" - Information icon
  • "mail" - Mail/email icon
  • "plus" - Plus/add icon
  • "quotation" - Quote/speech icon
  • "tel" - Phone/telephone icon
  • "undo" - Undo/back icon
  • "" - No icon
Accessibility
  • Notifications are announced by screen readers (the pill is a polite live region).
  • The auto-hide pauses while the pill is hovered or holds keyboard focus.
  • With prefers-reduced-motion: reduce, the animations become short fades.
  • The info toggle exposes aria-expanded and aria-controls.
Customization

Magic Pill is easily customizable through CSS variables. Simply replace the theme colors or fonts by changing the values in the variables set in ":root".

/* Font import */
@import url('https://fonts.googleapis.com/css2?family=Lexend:wght@100..900&family=Overlock:ital,wght@0,400;0,700;0,900;1,400;1,700;1,900&display=swap');

/* CSS variables */
:root {
  --mp__themeDark: #141414;
  --mp__themeLight: #F9F9F9;
  --mp__font-text: "Overlock", sans-serif;
  --mp__font-accent: "Lexend", sans-serif;
  --mp__normal: normal;
  --mp__italic: italic;
  --mp__medium: 400;
  --mp__bold: 700;
  --mp__black: 900;
  --mp__success: #3F7253;
  --mp__danger: #FC5D6A;
  --mp__textSize: 19.4px;
  --mp__titleSize: 31.42px;
}

Build your own

Maybe what I brought to the table wasn't enough but you like the idea behind it, that's why Magic Pill is under MIT License, which means you can pretty much do whatever you want and build upon my own version of Magic Pill to bring it to new heights or just make it your own.

Here's how to proceed:

  1. Clone the project:
git clone https://github.com/CedricTheveneau/Magic-Pill.git
  1. Use the Node.js version from .nvmrc (Node 26) and install all dependencies:
nvm use
npm install
  1. Check that everything works:
npm run typecheck   # TypeScript
npm test            # Vitest test suite
npm run build       # Builds dist/ with tsdown
  1. You're good to go! For easier development, we recommend creating a Next.js app and creating a symbolic link between the app and the package. Now, when you're making changes to the code in src/, the changes should be reflected in your Next.js app.
# Create a new Next.js app
npx create-next-app@latest my-app --typescript

# Link the package (from the Magic-Pill directory)
npm link

# Link to your app (from your app directory)
npm link magic-pill

Troubleshooting / Contact

Magic Pill is still under development, you'll certainly encounter issues with it. You can send me emails anytime at theveneaucedricpro@gmail.com, I'll try my best to help you out.

License

Magic Pill is distributed under the MIT License.

What's next?

TODO DOING
Support of custom svg icons Animation fixes
Transition between two modes Responsive version + Proportions rework
Implementation of function triggers on CTAs Full documentation
Proper testing

Keywords