• Stars
    star
    167
  • Rank 219,730 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

restyle

build status

new 10 minutes intro about restyle.js in vimeo

This project has been somehow inspired by absurd.js but it is not exactly the same.

You can check restyle specifications or go directly to a face 2 face against absurd but the long story short is that no JavaScript library out there fits in about 1KB and feels as natural as restyle does in typing CSS.

Good news is, you can choose more now but let's see what's in the menu here ;-)

In A Nutshell

restyle is a function able to transform the following:

// we are in a browser
// defining some style at runtime
var myStyle = (function(){

  // some function helper
  function getSomeNumber(boundary) {
    return Math.floor(Math.random() * (boundary + 1));
  }

  // something we could reuse all over
  function hex(red, green, blue) {
    return '#'.concat(
      ('0' + red.toString(16)).slice(-2),
      ('0' + green.toString(16)).slice(-2),
      ('0' + blue.toString(16)).slice(-2)
    );
  }

  // the fresh new appended style object wrap
  return restyle({
    body: {
      backgroundColor: hex(100, 60, 25),
      padding: {
        top: 50,
        left: '30%'
      }
    },
    '.component > li': {
      width: window.innerWidth,
      height: getSomeNumber(200)
    },
    '.component > .icon-spinner': {
      animation: {
        name: 'spin',
        duration: '4s'
      }
    },
    '@keyframes spin': {
      from: {
        transform: 'rotate(0deg)'
      },
      to: {
        transform: 'rotate(360deg)'
      }
    }
  });
}());

into this runtime appended and generated cross browser CSS style:

body {
  background-color: #643c19;
  padding-top: 50px;
  padding-left: 30%;
}

.component > li {
  width: 1251px;
  height: 182px;
}

.component > .icon-spinner {
  -webkit-animation-name: spin;
  -moz-animation-name: spin;
  -ms-animation-name: spin;
  -o-animation-name: spin;
  animation-name: spin;
  -webkit-animation-duration: 4s;
  -moz-animation-duration: 4s;
  -ms-animation-duration: 4s;
  -o-animation-duration: 4s;
  animation-duration: 4s;
}

@-webkit-keyframes spin {
  from {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  to {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

@-moz-keyframes spin {
  from {
    -moz-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  to {
    -moz-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

@-ms-keyframes spin {
  from {
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  to {
    -ms-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

@-o-keyframes spin {
  from {
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  to {
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

@keyframes spin {
  from {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  to {
    -webkit-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    -ms-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

with the ability to drop all those styles at once:

myStyle.remove();

New In Version 0.4

It is now possible to simplify transitions through the transition public static method method.

var transition = restyle.transition(
  genericElement,
  from: {
    opacity: '0',
    height: 34
  },
  to: {
    opacity: '1' // will keep height 34
  },
  function onTransitionEnd(e) {
    console.log('transition completed');
    e.detail.clean(); // remove related styles
  }
);

It is also possible to create multiple transitions from a starting point.

var transition = restyle.transition(
  genericElement,
  from: {
    opacity: '0',
    height: 0
  },
  to: [{
    height: 200 // will keep opacity '0'
  }, {
    opacity: '1' // will keep height 200
  }],
  function onTransitionEnd(e) {
    console.log('transition completed');
    e.detail.clean(); // remove related styles
  }
);

In latter case the final callback happens when last transition is completed.

At any time it is possible to ignore the callback via transition.drop() or to clean all styles and transitions via transition.clean().

Please note that unless explicitly done, related styles will not be dropped.

If you need to keep the transition end CSS please add a class and after that clean everything else.

New In Version 0.3

It is now possible to simplify animations through the animate method.

// a generic animation style
var glowAnimation = restyle({
  '@keyframes glow-animation': {
    '0%':   { boxShadow: '0px 0px 0px 0px rgba(255,255,255,1)' },
    '100%': { boxShadow: '0px 0px 32px 16px rgba(255,255,255,1)' }
  },
  '.glow': {
    animation: {
      name: 'glow-animation',
      duration: '1s',
      direction: 'normal'
    }
  }
});

// glowing function
function glow(el, callback) {
  el.classList.add('glow');
  return glowAnimation.animate(el, 'glow-animation', callback);
}

// whenever is needed
document.querySelector('#link')
  .addEventListener('click', function (e) {
    // glow
    glow(e.currentTarget, function (event) {
      console.log(event);
    });
  });

The fallback is based on setTimeout and the returned object has a .drop() method able to cancel the animation end event. The duration is retrieved automatically when the fallback is used. Please note the fallback is compatible with s or ms as seconds or milliseconds and nothing else.

It is possible to retrieve an animation duration through the .getAnimationDuration(domElement, animationName) method which returns -1 in case of failure.

New In Version 0.2

The signature has been improved to accept a first argument representing a generic container/component prefix.

var compStyle = restyle('my-component-name', {
  'div.large': {
    width: '100%'
  },
  span: {
    display: 'none'
  }
});

Above code will produce a CSS similar to the following one:

my-component-name div.large {
  width: 100%;
}
my-component-name span {
  display: none;
}

This can be very handy when you have to style Custom Elements or generic reusable web components.

Signature

restyle(
  [component, ] // an optional string used to auto prefix all styles under a node/component
  Object        // a JSONish object as spec'd
  [, prefixes]  // optional prefixes
                // as node.js module this is by default an empty array
                //  generating prefixes-less CSS for other pre/post processors
                // in browsers this is by default all vendors prefixes
                //  without bothering much that -webkit-background does not even exist
                //  browsers will simply ignore CSS that is meaningless

  [, document]  // browsers only, eventually a different document from another realm
):Object;

Specifications

The first Object parameter in restyle signature is spec'd as such:


selector        any CSS selector
                {
                  body: {
                    // ... 
                  },
                  'ul.dat > li:first-child': {
                    // ...
                  }
                }

property        a property name or a group name
                {
                  div: {
                    // properties
                    width: 256, // will result in "256px"
                    transform: 'rotate(360deg)',
                    background: 'transparent url(image.png) 0 0'
                  }
                }
                camelCase will be translated into camel-case
                (backgroundImage => background-image)

value           the property value or a group of properties
                if int, will be set as 'px' value

group           key/value properties names/values object
                or
                an Array of possible values for the property
                {
                  div: {
                    // group
                    background: {
                      color: 'transparent',
                      image: 'url(image.png)',
                      position: '0 0'
                    }
                  }
                }
                or
                {
                  '.flexbox': {
                    // mutiple values
                    display: [
                      '-webkit-box',
                      '-moz-box',
                      '-ms-flexbox',
                      '-webkit-flex',
                      'flex'
                    ]
                  }
                }

special         keyframes, media queries,
                anything that starts with @
                {
                  div: {
                    // as before
                  },
                  // special selectors
                  '@keyframes spin': {
                    // cpecialContent
                  }
                }

specialContent  everything supported by restyle as CSS
                {
                  // special selectors
                  '@keyframes spin': {
                    // properties => values or groups
                    '0%':   {transform: 'rotate(0deg)'},
                    '100%': {transform: 'rotate(360deg)'}
                  },
                  '@media all and (color)': {
                    'body': {
                      background: randomRainbow()
                    }
                  }
                }

Reason & Benefits

Here a list of bullets to support restyle idea, grouped by usage.

As DOM Runtime

  • all values, groups, and even keys, can be generated at runtime after features detection or states
  • all vendor prefixes are placed automatically, no redundant CSS to write or download
  • all changes are confined in a single style element that can be dropped at any time
  • it can be used to style custom components preserving the overall application size
  • it fits in less than 1KB minzipped

As node.js module or Preprocessor

  • compared to Sass, Stylus, Less, and others, there's nothing new to learn: it's basically JSON that transpile to CSS
  • can be used upfront other preprocessors such beautifiers, cross platform transformers, etc.
  • CSS can be exported as generic JS modules, with the ability to include, require, and use any sort of utility able to simplify CSS creation, aggregate objects upfront for unified style, anything else you might think would be useful
  • it's simple, fast and straightforward

Compatibility

  • restyle is compatible with new browsers but also old as IE6 . If in doubt, check the live test
  • every node.js is able to use restyle too as the Travis passing build on top says ;-)

Examples

It is possible to test them directly in this page but here few examples.

// this example code
restyle({
  'html, body': {
    margin: 0,
    padding: 0,
    width: '100%',
    height: '100%',
    overflow: 'hidden',
    textAlign: 'center',
    fontFamily: 'sans-serif'
  },
  section: {
    margin: 'auto',
    marginTop: 20
  }
}, []);

It will generate a style with the following content.

html, body {
    margin: 0px;
    padding: 0px;
    width: 100%;
    height: 100%;
    overflow: hidden;
    text-align: center;
    font-family: sans-serif;
}

section {
    margin: auto;
    margin-top: 20px;
}

Things become more interesting with more complex CSS and prefixed support:

restyle({
  'div > button:first-child': {
    transform: 'rotate(30deg)'
  }
}, ['moz', 'webkit']);

will result in

div > button:first-child {
  -webkit-transform: rotate(30deg);
  -moz-transform: rotate(30deg);
  transform: rotate(30deg);
}

while this little piece of code:

restyle({
  'body > div': {
    animation: {
      name: 'spin',
      duration: '4s'
    }
  },
  '@keyframes spin': {
    from: {
      transform: 'rotate(0deg)'
    },
    to: {
      transform: 'rotate(360deg)'
    }
  }
});

will produce the following

body > div{
  -webkit-animation-name:spin;
  -moz-animation-name:spin;
  -ms-animation-name:spin;
  -o-animation-name:spin;
  animation-name:spin;
  -webkit-animation-duration:4s;
  -moz-animation-duration:4s;
  -ms-animation-duration:4s;
  -o-animation-duration:4s;
  animation-duration:4s;
}
@-webkit-keyframes spin{
  from{
    -webkit-transform:rotate(0deg);
    transform:rotate(0deg);
  }
  to{
    -webkit-transform:rotate(360deg);
    transform:rotate(360deg);
  }
}
@-moz-keyframes spin{
  from{
    -moz-transform:rotate(0deg);
    transform:rotate(0deg);
  }
  to{
    -moz-transform:rotate(360deg);
    transform:rotate(360deg);
  }
}
@-ms-keyframes spin{
  from{
    -ms-transform:rotate(0deg);
    transform:rotate(0deg);
  }
  to{
    -ms-transform:rotate(360deg);
    transform:rotate(360deg);
  }
}
@-o-keyframes spin{
  from{
    -o-transform:rotate(0deg);
    transform:rotate(0deg);
  }
  to{
    -o-transform:rotate(360deg);
    transform:rotate(360deg);
  }
}
@keyframes spin{
  from{
    -webkit-transform:rotate(0deg);
    -moz-transform:rotate(0deg);
    -ms-transform:rotate(0deg);
    -o-transform:rotate(0deg);
    transform:rotate(0deg);
  }
  to{
    -webkit-transform:rotate(360deg);
    -moz-transform:rotate(360deg);
    -ms-transform:rotate(360deg);
    -o-transform:rotate(360deg);
    transform:rotate(360deg);
  }
}

Special Features

There are few tricks hidden in the simple restyle logic where Array values are able to combine multiple declarations at once.

multiple values, same property

The most classic example here would be flex-box mess, simplified through a variable

var flexBox = [
  '-webkit-box',
  '-moz-box',
  '-ms-flexbox',
  '-webkit-flex',
  'flex'
];

reusable whenever it's needed:

restyle({
  'div.container': {
    display: flexBox
  }
});

resulting into the following CSS

div.container {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
}

multiple styles, same selector

Another example would be mixins or reusable functions in order to define some grouped style and reuse this whenever is needed.

function flexbox() {
  return {
    display: [
      '-webkit-box',
      '-moz-box',
      '-ms-flexbox',
      '-webkit-flex',
      'flex'
    ]
  };
}
function flex(values) {
  return {
    boxFlex: values,
    flex: values
  };
}
function order(value) {
  return {
    boxOrdinalGroup: value,
    flexOrder: value,
    order: value
  };
}
restyle({
  '.wrapper': flexbox(),
  '.item': [
    flex('1 200px'),
    order(2)
  ]
});

Above is a restyle example of ths Sass one showed in CSS tricks.

What Is NOT

Just to be clear what restyle is not a CSS validator, beautifier, or uglifier, plus it is not responsible or capable of making everything magically works.

As example, flex-box is not fixed, neither early or non standard implementation of any feature. However, you can simply combine a common class fix for flex-box and use restyle to add more or simply specify other properties, there are no implicit limits in what you can write through restyle.

You are free to fix things indeed by your own, deciding very specific CSS accordingly with the browser if done at runtime or simply trusting other pre-processors if done on the server side with the benefit that the object will be reused in both worlds, as example:

var flexValue = '1 200px',
    orderValue = 2,
    flexBox = [
      '-webkit-box',
      '-moz-box',
      '-ms-flexbox',
      '-webkit-flex',
      'flex'
    ];

var flex = restyle({
  '.wrapper': {
    display: flexBox
  },
  '.item': {
    boxFlex: flexValue,
    flex: flexValue,
    boxOrdinalGroup: orderValue,
    flexOrder: orderValue,
    order: orderValue
  }
});

F.A.Q.

  • why so many prefixes in the DOM version ? Not influent at runtime, invisible via node, but I've hopefully replied to this here already ;-)
  • should I serve all CSS only via restyle at runtime? you can do whatever you want. You can combine normal CSS with restyle in order to add special FX only or new features where prefixes are a mess. You can use restyle only to fix things that need to be fixed for browsers that support JS. You can use only restyle if your app depends on JavaScript so there's no way it's going to be used or useful at all without JS enabled. You chose, don't blame the tool, it's here to help when needed ;-)
  • what's the difference with absurd.js? by the time I am writing this, restyle works better for WebApp development at runtime and wins in size and performance but it cannot compete against absurd on the server side since it does nothing that absurd does, only the object syntax is similar. Bear in mind I've said similar but not identical, absurd.js is by design not able to solve a property name from a tagName while restyle simply represents CSS without magic involved.
  • can I use restyle for serving both server and client at runtime? Yes, again, you can use restyle as you wish. On the server, you can use same logic you would apply on the client and maybe chose to serve that pre-processed file inside a noscript as external link, using restyle for all other JS centric cases or for graceful enhancement without compromising the layout. CSS modules can be shared, reused, the same, both pre-processed as CSS behind other pre-processors, or just with all prefixes generated at runtime for more complex scenarios. Go wild, still respect your site/app users ;-)
  • didn't Netscape with JSSS ... bla bla? probably you didn't read what restyle is, neither what JSSS proposal was. Please take a minute to understand again what is this about, and feel free to use JSSS if you think that's even an option.

If you have any hint about some syntax that could improve restyle ease please let me know, thanks.

More Repositories

1

hyperHTML

A Fast & Light Virtual DOM Alternative
HTML
3,028
star
2

linkedom

A triple-linked lists based DOM implementation.
HTML
1,156
star
3

document-register-element

A stand-alone working lightweight version of the W3C Custom Elements specification
JavaScript
1,131
star
4

dom4

Modern DOM functionalities for every browser
JavaScript
929
star
5

flatted

A fast and minimal circular JSON parser.
JavaScript
893
star
6

url-search-params

Simple polyfill for URLSearchParams standard
JavaScript
765
star
7

uhtml

A micro HTML/SVG render
JavaScript
707
star
8

lighterhtml

The hyperHTML strength & experience without its complexity 🎉
JavaScript
702
star
9

JSONH

Homogeneous Collection Compressor
JavaScript
618
star
10

circular-json

JSON does not handle circular references. Now it does
JavaScript
599
star
11

viperHTML

Isomorphic hyperHTML
JavaScript
318
star
12

heresy

React-like Custom Elements via V1 API builtin extends.
JavaScript
271
star
13

es6-collections

Map, WeakMap, and Set fast/simple shim for Harmony collections
JavaScript
253
star
14

neverland

React like Hooks for lighterhtml
JavaScript
241
star
15

wicked-elements

Components for the DOM as you've never seen before
JavaScript
235
star
16

eddy

Event Driven JS
JavaScript
211
star
17

dblite

sqlite for node.js without gyp problems
JavaScript
209
star
18

domdiff

Diffing the DOM without virtual DOM
JavaScript
197
star
19

hyperHTML-Element

An extensible class to define hyperHTML based Custom Elements.
JavaScript
195
star
20

benja

Bootable Electron Node JS Application
194
star
21

uce

µhtml based Custom Elements
JavaScript
183
star
22

usignal

A blend of @preact/signals-core and solid-js basic reactivity API
JavaScript
176
star
23

highlighted-code

A textarea builtin extend to automatically provide code highlights based on one of the languages available via highlight.js
HTML
172
star
24

testardo

a browser and OS agnostic web driver for mobile and desktop
JavaScript
166
star
25

sqlite-worker

A simple, and persistent, SQLite database for Web and Workers.
JavaScript
159
star
26

augmentor

Extensible, general purpose, React like hooks for the masses.
JavaScript
135
star
27

uhooks

micro hooks: a minimalistic client/server hooks' implementation
JavaScript
127
star
28

polpetta

Polpetta, any folder is served spiced
JavaScript
125
star
29

basicHTML

A NodeJS based, standard oriented, HTML implementation.
JavaScript
123
star
30

udomdiff

An essential diffing algorithm for µhtml.
JavaScript
117
star
31

pocket.io

A minimalistic version of socket.io that weights about 1K instead of 60K.
JavaScript
112
star
32

caller-of

The tiniest yet most powerful JS utility ever :D
HTML
102
star
33

uland

A µhtml take at neverland
JavaScript
101
star
34

uce-template

A Vue 3 inspired Custom Elements toolless alternative.
JavaScript
100
star
35

json.hpack

JSON Homogeneous Collections Packer
C#
95
star
36

html-escaper

A module to escape/unescape common problematic entities done the right way.
JavaScript
95
star
37

wru

essential unit test framework
JavaScript
95
star
38

udomsay

A stricter, signals driven, ESX based library
JavaScript
95
star
39

db

JavaScript
94
star
40

import.js

A dynamic import() polyfill
JavaScript
93
star
41

regular-elements

Custom Elements made available for any node, and through CSS selectors
JavaScript
91
star
42

proxy-pants

Secured and reliable Proxy based utilities for more or less common tasks.
JavaScript
90
star
43

ucompress

A micro, all-in-one, compressor for common Web files.
JavaScript
90
star
44

archibold.io

archibold.io
Shell
85
star
45

jsgtk

A simplified approach to GJS for Node.JS and JavaScript developers.
JavaScript
85
star
46

heresy-ssr

🔥 heresy 🔥 Server Side Rendering
JavaScript
84
star
47

hypersimple

The easiest way to use hyperHTML
JavaScript
83
star
48

asbundle

A minimalistic JS bundler
JavaScript
77
star
49

introspected

Introspection for serializable arrays and JSON friendly objects.
HTML
77
star
50

node-gtk

GNOME Gtk+ bindings for NodeJS
C++
74
star
51

i18n-utils

The i18n tag function utilitities
JavaScript
73
star
52

viper-news

viperHTML version of the Hacker News app.
JavaScript
72
star
53

ucdn

A µcompress based CDN utility, compatible with both Express and native http module
JavaScript
67
star
54

electroff

A cross browser, electron-less helper, for IoT projects and standalone applications.
JavaScript
64
star
55

builtin-elements

A zero friction custom elements like primitive.
JavaScript
62
star
56

nonchalance

The easiest way to augment DOM builtin elements.
JavaScript
61
star
57

universal-mixin

A mixin usable for both generic objects and decorators.
JavaScript
59
star
58

attachshadow

An iframe based Shadow DOM poorlyfill
JavaScript
59
star
59

ucontent

An SSR HTML content generator.
JavaScript
58
star
60

dom-augmentor

Same as augmentor but with DOM oriented useEffect handling via dropEffect.
JavaScript
56
star
61

ascjs

ES2015 to CommonJS import/export transformer
JavaScript
55
star
62

geo2city

Basic offline reverse geocode
JavaScript
53
star
63

vanilla-elements

A Minimalistic Custom Elements Helper.
JavaScript
51
star
64

wrist

Minimalistic utility for generic one/two ways data bindings.
HTML
51
star
65

screenfit

A cross platform, cross WebView, solution to fit 100% any Web page.
HTML
50
star
66

html-parsed-element

A base custom element class with a reliable `parsedCallback` method.
HTML
50
star
67

sqlite-tag

Template literal tag based sqlite3 queries.
JavaScript
49
star
68

jsdon

A DOM serializer based on LinkeDOM idea
HTML
48
star
69

echomd

A terminal oriented MD like syntax
JavaScript
48
star
70

dom-class

A lightweight, cross browser, simplification of WebComponents.
JavaScript
46
star
71

cloner

Cloning ES5+ objects in a shallow or deep way
JavaScript
46
star
72

css-proxied-vars

The easiest way to set, read, or update, CSS variables per each element.
JavaScript
46
star
73

event-target

The EventTarget Class Polyfill.
HTML
46
star
74

hn

Isomorphic Hacker News
JavaScript
45
star
75

proxied-worker

A tiny utility to asynchronously drive a namespace exposed through a Worker.
JavaScript
45
star
76

Database

Web SQL Storage Made Easy
JavaScript
44
star
77

promise

Abortable and Resolvable Promises.
JavaScript
43
star
78

poorlyfills

Simplified, partial, and poor ES6 collections polyfills, targeting IE9+ and older mobile browsers.
HTML
43
star
79

babel-plugin-transform-builtin-classes

A fix for the infamous Babel #4480 bug.
JavaScript
43
star
80

redefine

lightweight utility for smart object properties definition
JavaScript
42
star
81

bidi-sse

Bidirectional Server-sent Events
JavaScript
42
star
82

nativeHTML

coming soon
JavaScript
42
star
83

domtagger

The hyperHTML's template literal parser
JavaScript
41
star
84

hooked-elements

wickedElements 🧙 with render hooks
JavaScript
41
star
85

classtrophobic

Breaking JS Class Constrains
HTML
41
star
86

a-route

Express like routing as Custom Element or standalone
JavaScript
40
star
87

header-snippets

A collection of snippets to put in your header.
HTML
40
star
88

life-diary

your albums, your journey, your data
JavaScript
40
star
89

static.email

The easiest way to send emails on the Web
JavaScript
39
star
90

lazytag

Lazy loading Custom Elements and their styles without even thinking about it.
JavaScript
38
star
91

es-class

ECMAScript 3 to 6 compatible Class definition
JavaScript
38
star
92

tiny-cdn

A tiny static files serving handler
JavaScript
37
star
93

broadcast

Notification channel for the past, the present, and the future.
JavaScript
37
star
94

p-cool

Pretty Cool Elements
JavaScript
36
star
95

monthly

A simplified way to show a calendar month in any console.
HTML
36
star
96

jsx2tag

Enable JSX for Template Literal Tags based projects.
JavaScript
36
star
97

consolemd

Bringing echomd to console.
JavaScript
36
star
98

common-js

CommonJS + module.import() for any Browser
JavaScript
35
star
99

qsa-observer

handle elements lifecycle through CSS selectors
JavaScript
35
star
100

create-viperhtml-app

A basic viperHTML + hyperHTML setup
JavaScript
35
star