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

cj-notice

v1.1.0

Published

Plugin vanilla JavaScript para tasks e alerts de confirmação.

Readme

CJNotice.js

Plugin vanilla JavaScript para notificações empilháveis e alerts de confirmação. A biblioteca oferece uma API pequena para comunicar estados da interface, controlar avisos temporários e proteger ações irreversíveis sem depender de frameworks.

Versão atual: 0.1.0-alpha.1

GitHub NPM

Recursos

  • Tasks empilháveis em seis posições da tela.
  • Duração automática ou controle manual com dismiss().
  • Alerts de confirmação com ações de cancelar e confirmar.
  • Foco inicial, suporte à tecla Escape e foco restaurado no fechamento.
  • Tasks fecháveis com Escape, foco no botão de fechamento e navegação por teclado.
  • Role ARIA configurável (status por padrão ou alert para mensagens urgentes).
  • Animações configuráveis (slide, fade ou none) com suporte a prefers-reduced-motion.
  • Atualização de tasks, pausa opcional no hover, barra de progresso e fila por posição.
  • Conteúdo customizado com elementos DOM ou funções geradoras.
  • Callbacks para fechamento, expiração, cancelamento e confirmação.
  • Personalização de cores, borda, raio, ícones e conteúdo.
  • Tipos success, error, warning e info com presets de cores e ícones.
  • Métodos convenientes para tasks e confirmações tipadas.
  • Compatível com JavaScript vanilla e módulos ES.
  • Playground interativo e página de documentação com demos funcionais.

Instalação

npm install cj-notice

Durante a fase alpha, instale explicitamente a versão publicada:

npm install cj-notice@alpha

Uso básico

import CJNotice from "cj-notice";
import "cj-notice/style.css";

const notice = new CJNotice({ duration: 4000 });

notice.task({
    position: "top-right",
    icon: '<strong aria-hidden="true">✓</strong>',
    title: "Tudo certo",
    text: "A operação foi realizada.",
});

Também é possível usar tipos com presets visuais:

notice.success({
    title: "Tudo certo",
    text: "A operação foi realizada.",
});

notice.error({ title: "Falha", text: "Não foi possível concluir." });
notice.warning({ title: "Atenção" });
notice.info({ title: "Informação" });

Os métodos tipados também podem ser usados com show() ou task() por meio da opção type. As opções background, color, borderColor e icon personalizadas substituem os presets automáticos.

show(options) também pode ser usado no lugar de task(options).

Confirmação

notice.confirm({
    title: "Excluir registro?",
    text: "Esta ação não pode ser desfeita.",
    cancelLabel: "Cancelar",
    onCancel: () => console.log("cancelado"),
    confirmations: [
        {
            label: "Excluir",
            onClick: () => console.log("confirmado"),
        },
    ],
});

API

new CJNotice(options)

Cria uma instância do plugin. Os valores informados tornam-se defaults para as próximas tasks e confirmações.

const notice = new CJNotice({
    duration: 5000,
    position: "bottom-right",
    borderColor: "#2563eb",
    role: "status",
    animation: "slide",
});

configure(options)

Atualiza os defaults da instância e retorna o próprio objeto.

notice.configure({ duration: 3000 });

show(options) / task(options)

Exibe uma task e retorna um ID que pode ser usado para removê-la.

const taskId = notice.task({
    position: "bottom-center",
    duration: 0,
    title: "Processando",
    text: "Aguarde a conclusão.",
    onClose: ({ reason }) => console.log(reason),
    onExpire: (id) => console.log("Expirou", id),
});

notice.dismiss(taskId, "completed");

As tasks aceitam:

| Opção | Descrição | | -------------- | ---------------------------------------------------------------------------------------- | | position | top-left, top-center, top-right, bottom-left, bottom-center ou bottom-right. | | title | Título. | | text | Conteúdo textual. | | type | success, error, warning ou info; aplica um preset de cores e ícone. | | icon | HTML ou SVG confiável para o ícone. | | duration | Tempo em milissegundos. Use 0 para controle manual. | | background | Cores do fundo. | | color | Cores do texto. | | borderColor | Cor da borda lateral. | | borderWidth | Espessura da borda lateral. | | radius | Raio dos cantos. | | role | Role ARIA: status (padrão) ou alert. | | animation | Animação: slide (padrão), fade ou none. | | pauseOnHover | Pausa o timer e o progresso enquanto o mouse estiver sobre a task. | | progress | Exibe a barra de progresso em tasks temporizadas; use false para ocultá-la. | | maxVisible | Limite de tasks visíveis na posição; excedentes entram na fila FIFO. | | stackOrder | below (padrão) adiciona ao final ou above adiciona ao topo da pilha. | | content | Elemento DOM ou função que retorna um elemento; substitui title e text. | | onClose | Callback chamado ao fechar a task. Recebe { id, reason }. | | onExpire | Callback chamado quando a duração termina. Recebe o ID. |

dismiss(id, reason)

Remove somente a task indicada. Retorna true quando a task existe e false quando ela não foi encontrada.

O botão de fechamento recebe foco quando a task é criada. Com o foco dentro da task, Escape a dispensa e informa reason: "escape" ao callback onClose. Quando o sistema operacional solicita movimento reduzido, as animações são desativadas automaticamente.

update(id, options)

Atualiza uma task existente sem trocar seu ID ou elemento. Retorna true quando a task existe e false caso contrário. Alterar duration reinicia a contagem.

const taskId = notice.task({ title: "Enviando", duration: 0 });
notice.update(taskId, {
    title: "Enviado",
    text: "Arquivo concluído.",
});

Tasks que excedem maxVisible aguardam na fila da própria posição. Ao fechar uma task visível, a próxima é exibida automaticamente. pauseOnHover: true pausa tanto o timer quanto a barra de progresso.

Conteúdo seguro pode ser fornecido sem innerHTML:

notice.task({
    duration: 0,
    content: () => {
        const element = document.createElement("strong");
        element.textContent = "Conteúdo customizado";
        return element;
    },
});

Além de show() e task(), os métodos success(), error(), warning() e info() criam tasks com o tipo correspondente e retornam o ID da task.

confirm(options)

Abre um alert centralizado com foco gerenciado.

notice.confirm({
    title: "Publicar alterações?",
    text: "A nova versão ficará disponível para sua equipe.",
    cancelLabel: "Ainda não",
    confirmations: [{ label: "Publicar", onClick: publicarAlteracoes }],
});

Confirmações tipadas podem usar type ou os métodos convenientes:

notice.confirmSuccess({
    title: "Publicar alterações?",
    confirmations: [{ label: "Publicar", onClick: publicarAlteracoes }],
});

notice.confirmError({ title: "Excluir registro?" });
notice.confirmWarning({ title: "Atenção" });
notice.confirmInfo({ title: "Detalhes" });

Os tipos disponíveis são success, error, warning e info.

As opções específicas de confirmação são cancelLabel, onCancel, confirmations e onConfirmClose. Cada item de confirmations aceita label e onClick.

Ícones SVG

O campo icon aceita HTML ou SVG fornecido pela aplicação:

notice.task({
    icon: '<svg aria-hidden="true" viewBox="0 0 24 24">...</svg>',
    title: "Sincronizado",
    text: "Os dados estão atualizados.",
});

Como o ícone é inserido com innerHTML, use somente SVGs e HTML de fontes confiáveis. title e text são inseridos como texto simples.

Exemplos e documentação

Desenvolvimento

npm install
npm run dev

Scripts disponíveis:

npm run lint       # valida o código
npm test -- --run  # executa os testes
npm run build      # gera os arquivos em dist/

Licença

MIT