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

devsbc-components

v1.3.9

Published

Esta libreria permite reutilizar muchos componentes de gran utilidad y genericos para ser utilizados en tus proyectos.

Readme

DevsBC Components

Esta libreria permite reutilizar muchos componentes de gran utilidad y genericos para ser utilizados en tus proyectos.

Incluye

  • Formulario
  • ModeService
  • AuthService

IMPORTANTE
Agrega Angular Material a tu proyecto

ng add @angular/material

Agrega Bootstrap
https://getbootstrap.com/docs/5.0/getting-started/download/

Instalacion

Instala la libreria en tu modulo principal

npm i devsbc-form

Uso

import { DevsbcModule } from './../../projects/devsbc-components/src/lib/devsbc.module';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    DevsbcModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

En tu tsconfig.json

{
  "compilerOptions": {
    ....
    "paths": {
      "devsbc-components": [
        "node_modules/devsbc-components/devsbc-components",
        "node_modules/devsbc-components/"
      ],
    }
  }
}

Componentes

Resumen

Ira deja te explico, este componente te permite crear formularios con:
Angular Material, usando el Grid de Bootstrap.
El componente recibe un objeto que representa la vista del HTML y un formulario Angular que valida los campos.

En tu componente:

<dbc-form [data]="TUFORMULARIO"></dbc-form>

Modelo de Formulario

import { FormGroup } from '@angular/forms';

export interface FormModel {
  formData: FormDataModel[];
  view: ViewFormModel[];
  buttonLabel: string;
  onSubmit: any;
  disableButton: boolean;
}

interface FormDataModel {
  name: string;
  validator: any;
  value: any;
}

interface ViewFormModel {
  row: number;
  cols: FormFieldModel[];
}

interface FormFieldModel {
  callback?: FormCallbackModel | any;
  element: string;
  name: string;
  placeholder: string;
  type: string;
  required: boolean;
  disabled?: boolean;
  /* For select */
  options?: any[];
  multiple?: boolean;
}

interface FormCallbackModel {
  event: string;
  function: (e: any, form?: FormGroup) => any;
}

Ejemplo(s)

Cada view tiene un arreglo de cols, usa la misma funcionalidad de Bootstrap en el Grid.
Si requieres en la vista Desktop ver columnas en una sola fila, agregalas en el mismo arreglo de cols.

  • Cabe destacar que la propiedad name debe ser igual en view y formData

IMPORTANTE
El campo FormDataModel utiliza:
import { Validators } from '@angular/forms';
Esto te permite agregar Validaciones a cada campo utilizando Angular Forms.
Si no deseas agregar validacion para un campo simplemente agrega [] (array vacio)

const form: FormModel = {
    view: [
      { row: 1,
        cols: [
          { placeholder: 'Título', name: 'title', type: 'text', element: 'input', required: true },
        ]
      },
      {
        row: 2,
        cols: [
          { placeholder: 'Descripción', name: 'description', type: 'text', element: 'textarea', required: false },
        ]
      },
      {
        row: 3,
        cols: [
          { placeholder: 'Texto del botón', name: 'button', type: 'text', element: 'input', required: false },
        ]
      },
      {
        row: 4,
        cols: [
          { placeholder: 'Enlace del botón', name: 'href', type: 'text', element: 'input', required: false },
        ]
      }
    ],
    formData: [
      { name: 'title', value: null, validator: Validators.required },
      { name: 'description', value: null, validator: [] },
      { name: 'button', value: null, validator: [] },
      { name: 'href', value: null, validator: [] },
    ],
    disableButton: false,
    buttonLabel: 'Crear Slider',
    onSubmit: (data: any) => this.onSubmit(data) // call your submit function
  };

  public onSubmit(data: any) {
    // Your logic Here
    // The data is ready to usage
  }

Tambien es posible pasar funciones para que respondan a eventos en el formulario.
Para ello usa la propiedad callback en la definicion de la vista en cada columna.

Es necesario definir el nombre del evento, el cual es igual a los eventos HTML/Angular disponibles.

La funcion definida tambien puede cambiar el estado del formulario.

En el Siguiente ejemplo:

  • En el FormFieldModel 'email' el callback verifica que ambos campos sean igual. (con esto es posible deshabilitar el formulario, vaciar campos o mostrar mensajes personalizados)
  • En el FormFieldModel 'pin' el callback cambia el texto ingresado a mayusculas.

const data: FormModel = {
    view: [
      { row: 1, 
        cols: [
        { placeholder: 'fullName', name: 'fullName', type: 'text', element: 'input' }
        ],
      },
      {
        row: 2, 
        cols: [
          { placeholder: 'email', name: 'email', type: 'email', element: 'input', callback: {
            event: 'keyup',
            function: (e: any, form?: FormGroup) => (form) ? this.onSetEmail(e, form) : e.value
          } },
          { placeholder: 'confirm-email', name: 'confirmEmail', type: 'email', element: 'input', callback: {
            event: 'keyup',
            function: (e: any, form?: FormGroup) => (form) ? this.onSetEmail(e, form) : e.value
          } }
        ]
      },
      {
        row: 3, cols: [
          { placeholder: 'serial-number', name: 'serialNumber', type: 'number', element: 'input', callback: {
            event: 'keyup',
            function: (e: any, form?: FormGroup) => (form) ? this.onSetSN(e, form) : e.value
          }},
          { placeholder: 'confirm-serial-number', name: 'confirmSerialNumber', type: 'number', element: 'input', callback: {
            event: 'keyup',
            function: (e: any, form?: FormGroup) => (form) ? this.onSetSN(e, form) : e.value
          }}
        ]
      },
      {
        row: 4, cols: [
          { placeholder:'PIN', name: 'pin', type: 'text', element: 'input', callback: {
            event: 'keyup',
            function: (e: any, form?: FormGroup) => e.value = e.value.toUpperCase()
          }}
        ]
      }
    ],
    formData: [
      { name: 'fullName', value: '', validator: Validators.required },
      { name: 'email', value: '', validator: [Validators.required, Validators.email] },
      { name: 'confirmEmail', value: '', validator: [Validators.required, Validators.email] },
      { name: 'serialNumber', value: null, validator: Validators.required },
      { name: 'confirmSerialNumber', value: null, validator: Validators.required },
      { name: 'pin', value: null, validator: Validators.required }
    ],
    disableButton: false,
    buttonLabel: 'register',
    onSubmit: (data: any) => this.onSubmit(data)
  }

Eventos disponibles

De momento solo esta disponible un solo evento (wait for more)

  • keyup

Funcionalidad extendida

Si el formulario no cumple con tus requerimientos, puedes agregar HTML personalizado arriba o abajo del formulario y completar la experiencia.
Para ello usa slot="top/bottom" en tu html dentro del componente dbc-form.
La validacion del HTML agregado corre por tu cuenta.

<dbc-form [data]="form">
  <!--USING A FILE MANAGER FOR ADD IMAGE TO FORM -->
  <div slot="top" class="text-center" style="margin-bottom: 10px;">
    <button mat-raised-button color="accent" (click)="getFile()" style="margin-bottom: 10px;">
      <span *ngIf="!url">Seleccionar imagen</span>
      <span *ngIf="url">Cambiar imagen</span>
    </button>
    <img [src]="url" *ngIf="url" >
  </div>
</dbc-form>
<dbc-form [data]="data">
  <!--USING A INFO FOR FORM -->
  <ng-container slot="bottom">
      <div class="row">
          <div class="col">
              <div class="alert alert-danger" role="alert">
                  El número de serie del equipo se encuentra en la parte posterior del equipo
              </div>
              <img src="../../../assets/sn.png">
          </div>
      </div>
  </ng-container>
</dbc-form>

Capturas

El siguiente ejemplo agrega HTML personalizado para integrarse con el formulario
Formulario

La vista movil es responsiva (Grid de Bootstrap)
Formulario

Formulario con Stripe
Formulario

Formulario Autovalidado (Angular Forms Validators)
Formulario

Formulario con File Manager
Formulario

Servicios

Introduccion

Ira deja te explico, cuando requieres probar tu aplicacion regularmente lo haces localmente,
no obstante cuando existen errores o problemas que necesitas verificar resulta muy util habilitar un espacio para pruebas que se encuentre en produccion.
Esto se reduce en un simple switch que de acuerdo a tus configuraciones pueden verlo ciertos usuarios o solo tu.
Para implementar esta funcionalidad este servicio te ayuda a fijar un modo ya sea 'prod' o 'test'
Con esto puedes consumir tu app en produccion en un modo distinto y asegurarte que funciona bien.
Tambien esta implementacion te ayuda a aislar aquellos datos y configuraciones que pertenecen a tu ambiente de pruebas.

Ejemplo

Considera esta APP de Ionic que implementa un modo de prueba para hacer testing y separar los datos reales de los ficticios.
mode mode
Considera hacer evidente que tu APP esta en modo prueba(como cambiar el color)
mode

Uso

Utilizar este servicio es tan sencillo, solo pasa tu variable environment.production e inicializar el servicio.
El modo se guarda en sessionStorage.
Utilizar environment.production garantiza que tu app es congruente con tu entorno.
El switch funciona para cambiar de contexto toda la app.

constructor(private modeService: ModeService) {
    this.mode = this.modeService.getMode(environment.production);
}

public toggleMode(event: any) {
    const checked = event.checked;
    const mode = (checked) ? 'test' : 'prod';
    this.modeService.saveMode(mode, true);
 }

Introduccion

Este servicio se encarga de hacer llamadas http POST al servidor para autenticar o registrar un usuario.
Para usar este servicio es necesario contar con un ENDPOINT a tu servidor.

IMPORTANTE
Las llamadas a SignIn y SignUp devuelven un token, basado en JSON Web Token
Para mas informacion acerca de esta implementacion ver JWT.

Si tu servidor no devuelve TOKEN este servicio NO funcionara.
Aqui un ejemplo BASICO de implementacion (BACKEND)

 private generateToken(user: any, duration?: string) {
    const signature = CREDENTIALS.signature;
    const expiration = duration || '1h';
    return jwt.sign({ user }, signature, { expiresIn: expiration });
}

Modelos

Utiliza este modelo con la funcion setSessionName para inicializar el servicio de acuerdo a tus configuraciones.
Considera inicializar el servicio en el componente principal AppComponent

export interface AccessAuthModel {
    sessionName: string;
    multiSession?: boolean; // if multiSession -> User saves in sessionStorage *default localStorage
}

Ejemplo

export class AppComponent {
  constructor(private authService: AuthService) {
    this.authService.setSessionName({
      sessionName: 'my-session',
      multiSession: false
    });
  }
}

Uso

He aqui un ejemplo de como puedes usar este servicio

 /* EXAMPLE FOR AUTH SERVICE */
  baseUrl!: string;

  constructor(private authService: AuthService, private modeService: ModeService) {}

  ngOnInit(): void {
    // Init URL for Access
    this.baseUrl = this.initServerConnection('ip', 'access');

    // Enable this to test
    // this.signIn();
  }

  /* MY OWN IMPLEMENTATION FOR GET BASE URL FOR MY SERVER */
  public initServerConnection(app: string, endpoint: string): string {
    const mode = this.modeService.getMode(environment.production);
    const server = new ServerModel(mode, app);
    const baseUrl = server.getBaseUrl(endpoint);
    return baseUrl;
  }

  public async signIn(): Promise<void> {
    const user = { email: '', password: '' };
    const endpoint = this.baseUrl + '/signin';

    await this.authService.signIn(endpoint, user);
    // show message
    // redirect
    // some stuff
  }

  public async signUp(): Promise<void> {
    const user = { email: '', password: '', username: '', role: '' };
    const endpoint: this.baseUrl + '/signin',

    // the function saves the session
    await this.authService.signUp(endpoint, user);
    // show message
    // redirect
    // some stuff
  }

Funciones Disponibles

| Funcion | Argumentos | Valor de retorno | | :---: | :-: | :-: | | setSessionName | AccessAuthModel | void | | signUp | endpoint: string, user: any | void | | signIn | endpoint: string, user: any | void | | recoverPassword | url: string, email: string | any | | verifyToken | url: string, token: string | any | | updatePassword | url: string, email: string, password: string | any | | isAdmin | url: string, data: any | any | | isAuthenticated | void | any | | getSession | void | any | | getToken | void | string | | logout | urlToRedirect?: string | void |

Flujo de trabajo

El siguiente diagrama representa el flujo basico para usar el servicio.
Diagrama

Como contribuir

Contribuciones aceptadas GitHub
Si fue de ayuda, comprame un cafe.

Contacto

[email protected]