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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@digitalbooting/react-super-css

v0.0.5

Published

Light Weight Super CSS generator compatible with JSX

Downloads

36

Readme

Super CSS React

React Super CSS es una pequeña librería que te permite dar soporte a tus componentes para manejar propiedades dinámicas y responsivas de una manera muy facil.

Dynamic Props:

Con propiedades dinámicas me refiero a que solo se renderizan las propiedades utilizadas en tiempo de ejecución y no todas las definidas en tu componente, por ejemplo:

Imagina que tienes un componente <Flex /> en tu código como el siguiente:

<Flex width="90%" lgWidth="1500px" justify="between">
	...tu contneido
</Flex>

La propiedad width siempre estará visible en tu inspector de estilos mientras que la propiedad lgWidth solo sera renderizada en el momento en que la condición de un breakpoint especifico se cumpla.

Responsive props

Estas propiedades son aplicables a tu componente en el que integres Super CSS React, con propiedades responsivas me refiero a aquellas propiedades que se aplican a diferentes resoluciones de pantalla de una manera muy sencilla, antes de ver un ejemplo completo hay que comenzar por lo más importante: definir los breakpoint para que la librería funcione:

Breakpoints y prefijos

en la configuración inicial necesitas definir 2 propiedades de la siguiente manera:

const customConfig = {
	breakpoints: [390, 768, 1200] /* Breakpoints numericos */,
	breakpointsPrefix: ["xs", "sm", "md"] /* Prefijos para las propiedades responsivas */
};

const SuperCSSProps =  new  SuperCSSProps(customConfig);

En el ejemplo anterior se define en la configuración la propiedad breakpoints que corresponde a la medida numérica del breakpoint responsivo, la segunda propiedad es breakpointsPrefix que corresponde al prefijo que antecede a cada propiedad que se va a poder definir en los componentes.

Nota que ambos arreglos tienen la misma longitud y el orden de breakpoints corresponde en cuanto a índice al orden de su prefijo en breakpointsPrefix

Ahora veamos un ejemplo de como usar los 3 breakpoints definidos en el componente <Flex /> del ejemplo inicial:

<Flex width="90%" xsWidth="80%" smWidth="1200px" mdWidth={900} justify="between">
	... tu contenido
</Flex>

En el ejemplo anterior puedes observar varias cosas:

  1. Las propiedades responsivas se definen en formato CamelCase
  2. el prefijo antecede al nombre de cada propiedad esto es importante.
  3. las propiedades aceptan valores de tipo string y numérico.

En los ejemplos anteriores hemos utilizado la propiedad width para explicar cómo funciona, pero la librería tiene soporte para cualquier propiedad CSS definida en la especificación siempre que las anteceda un prefijo para aplicarlo de manera responsiva o sin el para aplicarlo de forma general y siempre que dicha propiedad CSS este escrita en CamelCase, veamos un ejemplo más completo:

<Flex
	xsWidth="90%"
	lgWidth="80%"
	backgroundColor="white"
	xsBackgroundColor="red"
	xsDirection="specialcolumn"
	mdDirection="row"
>
	<Text  xsSize={18}  mdFontSize={22}>Hola Mundo</Text>
</Flex>

En el ejemplo anterior hay 2 nuevos conceptos: Shortcuts de propiedades y Shortcuts de valores

En la configuración inicial de la librería hay 2 nuevas propiedades que se pueden configurar:

  1. alias (Objeto en el que puedes definir tus propios shortcuts) por ejemplo:

en lugar de escribir una propiedad CSS demasiado extensa puedes definir tu shortcut de la siguiente manera:

const customConfig = {
	alias: {
		brtop: "border-top-radius"
	},
	values: {}
};

const SuperCSSProps =  new  SuperCSSProps(customConfig);

El shortcut definido como brtop al renderizar tu CSS se reemplazara por border-top-radius

ahora en tu componente puedes usarlo de esta manera:

<Flex  brtop="15px">...tu contenido</Flex>
  1. values

Con los valores pasa excatamente lo mismo, imagina que no quieres definir en el caso de flexbox el valor space-between puedes crear un shortcut en el objeto de values de la configuración de esta manera:

const customConfig = {
    alias: {},
	values: {
		between: "space-between"
	}
};

const SuperCSSProps =  new  SuperCSSProps(customConfig);

y de igual manera usar este shortcut en tus valores de propiedades de esta forma:

<Flex  justifyContent="between">...tu contenido</Flex>

Shortcuts multiples (solo para alias)

puedes definir un shortcut para multiples propiedades CSS como cuando necesitas definir al mismo tiempo un width y un min-width puedes hacer los siguiente:

const customConfig = {
	alias: {
		w: ["width", "min-width"],
		svgSize: ["width", "min-width", "height", "min-height"]
	},
	values: {} /* sin soporte para esta caracteristica */
};

const SuperCSSProps =  new  SuperCSSProps(customConfig);

Imagina este ejemplo de componente para un icono:

<Icon icon="user" svgSize={40} />

Tu CSS resultante sería el siguiente:

{
	width: 40px;
	min-width: 40px;
	height: 40px;
	min-height: 40px;
}

Ok todo muy bien pero como lo utilizo en React JS?

Veamos 2 ejemplos completos, uno utilizando Styled Components y uno sin Utilizar Styled Components:

Styled Components

import React from 'react';
import styled from 'styled-components';
import SuperCSSProps from '@digitalbooting/react-super-css';

const customConfig = {
  breakpoints: [576, 768, 992, 1200],
  breakpointsPrefix: ['xs', 'sm', 'md', 'lg'],
  alias: {
      createBorder: "border"
  },
  values: {
      black: "1px solid #000000"
  }
};

const SuperCSS = new SuperCSSProps(customConfig);

const StyledComponent = styled.div`
  ${(props) => SuperCSS.hydrate(props)}
`;

const MyComponent = () => {    
  return (
    <StyledComponent
      width={900}
      mdWidth="90%"
      createBorder="black"
    >
      {/* Contenido del componente */}
    </StyledComponent>
  );
};

export default MyComponent;

Sin Styled Components

import React from 'react';
import styled from 'styled-components';
import SuperCSSProps from '@digitalbooting/react-super-css';

const customConfig = {
  breakpoints: [576, 768, 992, 1200],
  breakpointsPrefix: ['xs', 'sm', 'md', 'lg'],
  alias: {
      createBorder: "border"
      direction: 'flex-direction'
  },
  values: {
      black: "1px solid #000000"
  }
};

const SuperCSS = new SuperCSSProps(customConfig);

const MyComponent = () => {
    const styles = SuperCSS.hydrate({
	    createBorder: 'black',
	    width: '100%',
	    mdWidth: '80%',
	    display: 'flex'
	    xsDirection: 'column',
	    mdDirection: 'row'
    }) 
    
  return (
    <div style={styles}>
      {/* Contenido del componente */}
    </div>
  );
};

export default MyComponent;

La función utilizada para generar el CSS resultante de las propiedades hydrate retorna un String con el CSS generado.

Soporte

Hay 2 propiedades adicionales en la configuración: supportCSSProps y reservedProps

supportCSSProps

esta propiedad es un arreglo de propiedades CSS validas ue pueden ser renderizables en los componentes.

por defecto se incluyen todas las propiedades CSS admitidas por la especificación actual, si alguna propiedad no funciona puedes probar a agregarla en la configuración, si el problema persiste puedes reportarla.

dejo a continuación como referencia el listado de propiedades soportadas. básicamente cualquier propiedad que definas en tus componentes que no esté en este Arreglo de propiedades no será renderizado en el CSS final.

const CSS_PROPS = [
  "align-content",
  "align-items",
  "align-self",
  "animation",
  "animation-delay",
  "animation-direction",
  "animation-duration",
  "animation-fill-mode",
  "animation-iteration-count",
  "animation-name",
  "animation-play-state",
  "animation-timing-function",
  "backface-visibility",
  "background",
  "background-attachment",
  "background-blend-mode",
  "background-clip",
  "background-color",
  "background-image",
  "background-origin",
  "background-position",
  "background-repeat",
  "background-size",
  "border",
  "border-bottom",
  "border-bottom-color",
  "border-bottom-left-radius",
  "border-bottom-right-radius",
  "border-bottom-style",
  "border-bottom-width",
  "border-collapse",
  "border-color",
  "border-image",
  "border-image-outset",
  "border-image-repeat",
  "border-image-slice",
  "border-image-source",
  "border-image-width",
  "border-left",
  "border-left-color",
  "border-left-style",
  "border-left-width",
  "border-radius",
  "border-right",
  "border-right-color",
  "border-right-style",
  "border-right-width",
  "border-spacing",
  "border-style",
  "border-top",
  "border-top-color",
  "border-top-left-radius",
  "border-top-right-radius",
  "border-top-style",
  "border-top-width",
  "border-width",
  "bottom",
  "box-decoration-break",
  "box-shadow",
  "box-sizing",
  "break-after",
  "break-before",
  "break-inside",
  "caption-side",
  "caret-color",
  "clear",
  "clip",
  "color",
  "column-count",
  "column-fill",
  "column-gap",
  "column-rule",
  "column-rule-color",
  "column-rule-style",
  "column-rule-width",
  "column-span",
  "column-width",
  "columns",
  "content",
  "counter-increment",
  "counter-reset",
  "cursor",
  "direction",
  "display",
  "empty-cells",
  "filter",
  "flex",
  "flex-basis",
  "flex-direction",
  "flex-flow",
  "flex-grow",
  "flex-shrink",
  "flex-wrap",
  "float",
  "font",
  "font-family",
  "font-feature-settings",
  "font-kerning",
  "font-language-override",
  "font-size",
  "font-size-adjust",
  "font-stretch",
  "font-style",
  "font-synthesis",
  "font-variant",
  "font-variant-alternates",
  "font-variant-caps",
  "font-variant-east-asian",
  "font-variant-ligatures",
  "font-variant-numeric",
  "font-variant-position",
  "font-weight",
  "gap",
  "grid",
  "grid-area",
  "grid-auto-columns",
  "grid-auto-flow",
  "grid-auto-rows",
  "grid-column",
  "grid-column-end",
  "grid-column-gap",
  "grid-column-start",
  "grid-gap",
  "grid-row",
  "grid-row-end",
  "grid-row-gap",
  "grid-row-start",
  "grid-template",
  "grid-template-areas",
  "grid-template-columns",
  "grid-template-rows",
  "hanging-punctuation",
  "height",
  "hyphens",
  "image-orientation",
  "image-rendering",
  "image-resolution",
  "inline-size",
  "justify-content",
  "justify-items",
  "justify-self",
  "left",
  "letter-spacing",
  "line-break",
  "line-height",
  "list-style",
  "list-style-image",
  "list-style-position",
  "list-style-type",
  "margin",
  "margin-bottom",
  "margin-left",
  "margin-right",
  "margin-top",
  "max-height",
  "max-width",
  "min-height",
  "min-width",
  "mix-blend-mode",
  "object-fit",
  "object-position",
  "opacity",
  "order",
  "outline",
  "outline-color",
  "outline-offset",
  "outline-style",
  "outline-width",
  "overflow",
  "overflow-wrap",
  "overflow-x",
  "overflow-y",
  "padding",
  "padding-bottom",
  "padding-left",
  "padding-right",
  "padding-top",
  "page-break-after",
  "page-break-before",
  "page-break-inside",
  "perspective",
  "perspective-origin",
  "place-content",
  "place-items",
  "place-self",
  "pointer-events",
  "position",
  "quotes",
  "resize",
  "right",
  "row-gap",
  "scroll-behavior",
  "scroll-margin",
  "scroll-margin-block",
  "scroll-margin-block-end",
  "scroll-margin-block-start",
  "scroll-margin-bottom",
  "scroll-margin-inline",
  "scroll-margin-inline-end",
  "scroll-margin-inline-start",
  "scroll-margin-left",
  "scroll-margin-right",
  "scroll-margin-top",
  "scroll-padding",
  "scroll-padding-block",
  "scroll-padding-block-end",
  "scroll-padding-block-start",
  "scroll-padding-bottom",
  "scroll-padding-inline",
  "scroll-padding-inline-end",
  "scroll-padding-inline-start",
  "scroll-padding-left",
  "scroll-padding-right",
  "scroll-padding-top",
  "scroll-snap-align",
  "scroll-snap-stop",
  "scroll-snap-type",
  "shape-image-threshold",
  "shape-margin",
  "shape-outside",
  "tab-size",
  "table-layout",
  "text-align",
  "text-align-last",
  "text-combine-upright",
  "text-decoration",
  "text-decoration-color",
  "text-decoration-line",
  "text-decoration-style",
  "text-emphasis",
  "text-emphasis-color",
  "text-emphasis-position",
  "text-emphasis-style",
  "text-indent",
  "text-justify",
  "text-orientation",
  "text-overflow",
  "text-rendering",
  "text-shadow",
  "text-transform",
  "text-underline-position",
  "top",
  "touch-action",
  "transform",
  "transform-box",
  "transform-origin",
  "transform-style",
  "transition",
  "transition-delay",
  "transition-duration",
  "transition-property",
  "transition-timing-function",
  "unicode-bidi",
  "user-select",
  "vertical-align",
  "visibility",
  "white-space",
  "width",
  "will-change",
  "word-break",
  "word-spacing",
  "word-wrap",
  "writing-mode",
  "z-index",
];

ReservedProps

En React JS existen propiedades propias del marco o framework que pueden ocsionar un renderizado innecesario en el CSS tales como las siguientes:

const REACT_RESERVED_PROPS = [
  "key",
  "ref",
  "dangerouslySetInnerHTML",
  "style",
  "children",
  "className",
  "htmlFor",
  "id",
];

Si hay alguna propiedad extra puedes definirla en la configuración. Te dejo un ejemplo de cómo configurar estas propiedades en la configuración inicial

const customConfig = {
    alias: {},
	values: {},
	supportCSSProps: [
    	"scroll-behavior",
    	...more css props
	],
	reservedProps: [
    	"children",
    	"className",
    	...more reserved props
	]
};

const SuperCSSProps = new SuperCSSProps(customConfig);

Contribuir

Eres libre de contribuir a este proyecto, para hacerlo envíanos un correo a [email protected]

Somos una agencia creativa de Marketing y Desarrollo. Digital Booting | Agencia Creativa de Marketing Digital