• Stars
    star
    1,052
  • Rank 43,828 (Top 0.9 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

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

Repository Details

Blazing Fast React UI Primitive

πŸ“¦ ui-box is a low level CSS-in-JS solution that focuses on being simple, fast and extensible. All CSS properties are set using simple React props, which allows you to easily create reusable components that can be enhanced with additional CSS properties. This is very useful for adding things like margins to components, which would normally require adding non-reusable wrapper elements/classes.

Install

yarn add ui-box
# or
npm install --save ui-box

Usage

import Box from 'ui-box'

function Button(props) {
  return <Box is="button" padding="10px" background="red" {...props} />
}

function Example() {
  return (
    <Button disabled margin="10px">
      Hi
    </Button>
  )
}

The above example component renders a red, disabled <button> with margins.

API

Box (default export)

is

Type: string or React component type
Default: 'div'

Lets you change the underlying element type. You can pass either a string to change the DOM element type, or a React component type to inherit another component. The component just needs to accept a className prop to work. A good example is inheriting the react-router Link component. E.g:

<Box is={Link} to="/login">
  Login
</Box>
clearfix

Type: boolean

Utility property for easily adding clearfix styles to the element.

className

Type: string

The className prop you know and love. Internally it gets enhanced with additional class names for the CSS properties you specify.

selectors

Type: object<selector: string, props: CssProps>

This prop allows you to define selectors and custom styles to apply when the selector condition is met. This can be used to create richer element interactions, such as hover or focus states, without the use of another css-in-js library.

<Box is="a" selectors={{ '&:hover': { cursor: 'pointer', textDecoration: 'underline' } }}>
  Hello world
</Box>
CSS properties

All of these CSS properties are supported. You can pass either a string or a number (which gets converted to a px value). The shorthand properties with repeated values only accept a single value, e.g. margin="10px" works but margin="10px 20px" does not. You can use the x/y props (e.g. marginX/marginY) to achieve the same thing.

  • alignContent
  • alignItems
  • alignSelf
  • animation
  • animationDelay
  • animationDirection
  • animationDuration
  • animationFillMode
  • animationIterationCount
  • animationName
  • animationPlayState
  • animationTimingFunction
  • background
  • backgroundBlendMode
  • backgroundClip
  • backgroundColor
  • backgroundImage
  • backgroundOrigin
  • backgroundPosition
  • backgroundRepeat
  • backgroundSize
  • border
  • borderBottom
  • borderBottomColor
  • borderBottomLeftRadius
  • borderBottomRightRadius
  • borderBottomStyle
  • borderBottomWidth
  • borderColor
  • borderLeft
  • borderLeftColor
  • borderLeftStyle
  • borderLeftWidth
  • borderRadius
  • borderRight
  • borderRightColor
  • borderRightStyle
  • borderRightWidth
  • borderStyle
  • borderTop
  • borderTopColor
  • borderTopLeftRadius
  • borderTopRightRadius
  • borderTopStyle
  • borderTopWidth
  • borderWidth
  • bottom
  • boxShadow
  • boxSizing - Set to border-box by default.
  • clear
  • color
  • columnGap
  • content
  • cursor
  • display
  • fill
  • flex
  • flexBasis
  • flexDirection
  • flexFlow
  • flexGrow
  • flexShrink
  • flexWrap
  • float
  • font
  • fontFamily
  • fontSize
  • fontStyle
  • fontVariant
  • fontWeight
  • gap
  • grid
  • gridArea
  • gridAutoColumns
  • gridAutoFlow
  • gridAutoRows
  • gridColumn
  • gridColumnEnd
  • gridColumnGap
  • gridColumnStart
  • gridGap
  • gridRow
  • gridRowEnd
  • gridRowGap
  • gridRowStart
  • gridTemplate
  • gridTemplateAreas
  • gridTemplateColumns
  • gridTemplateRows
  • height
  • justifyContent
  • justifyItems
  • justifySelf
  • left
  • letterSpacing
  • lineHeight
  • listStyle
  • listStyleImage
  • listStylePosition
  • listStyleType
  • margin
  • marginBottom
  • marginLeft
  • marginRight
  • marginTop
  • marginX - Sets marginLeft and marginRight to the same value.
  • marginY - Sets marginTop and marginBottom to the same value.
  • maxHeight
  • maxWidth
  • minHeight
  • minWidth
  • opacity
  • order
  • outline
  • overflow
  • overflowX
  • overflowY
  • padding
  • paddingBottom
  • paddingLeft
  • paddingRight
  • paddingTop
  • paddingX - Sets paddingLeft and paddingRight to the same value.
  • paddingY - Sets paddingTop and paddingBottom to the same value.
  • placeContent
  • placeItems
  • placeSelf
  • pointerEvents
  • position
  • resize
  • right
  • rowGap
  • stroke
  • strokeDasharray
  • strokeDashoffset
  • strokeLinecap
  • strokeMiterlimit
  • strokeWidth
  • textAlign
  • textDecoration
  • textOverflow
  • textShadow
  • textTransform
  • top
  • transform
  • transformOrigin
  • transition
  • transitionDelay
  • transitionDuration
  • transitionProperty
  • transitionTimingFunction
  • userSelect
  • verticalAlign
  • visibility
  • whiteSpace
  • width
  • wordBreak
  • wordWrap
  • zIndex
Other props

All other props passed through to the underlying DOM element / React component.

extractStyles()

Returns a { cache, styles } object which contains the cache entries and rendered styles for server rendering. The styles can be output in a <style> tag or an external stylesheet (however you want). The cache should be passed to hydrate() on the client-side before mounting the app. Also useful for doing snapshot unit testing (make sure to call clearStyles() after each test though).

hydrate(cache)

Hydrates the cache using the cache value returned from extractStyles(). This is used to prevent needing to recalculate all the class names and re-render all the styles on page load when server rendering.

clearStyles()

Clears the cache and removes the rendered styles. Mainly useful for resetting the global state when using extractStyles() in unit tests.

splitProps(props, keys)

Utility function for filtering out props based on an array of keys. Returns an { matchedProps, remainingProps } object.

props

Type: object

keys

Type: array[string]

splitBoxProps(props)

Utility function for filtering out Box props. Returns an { matchedProps, remainingProps } object.

props

Type: object

keyframes(name, timeline)

Function for generating an animation keyframe name and injecting the provided styles into the stylesheet. The timeline object is in the shape of { 'from' | 'to' | [0-100]: CssProps } which define the styles to apply at each position of the animation. Returns the generated name for use with the animation or animationName props.

import Box, { keyframes } from 'ui-box'

const openAnimation = keyframes('openAnimation', {
  from: {
    opacity: 0,
    transform: 'translateY(-120%)'
  },
  to: {
    transform: 'translateY(0)'
  }
})

const AnimatedBox = () => <Box animation={`${openAnimation} 240ms cubic-bezier(0.175, 0.885, 0.320, 1.175)`} />

// Equivalent using individual props:
const AnimatedBox = () => (
  <Box
    animationName={openAnimation}
    animationDuration={240}
    animationTimingFunction="cubic-bezier(0.175, 0.885, 0.320, 1.175)"
  />
)

propTypes

Object of all the Box CSS property propTypes.

propNames

Array of all the Box CSS property names.

propAliases

Array of the Box CSS property aliases (the shorthand properties).

propEnhancers

Object of all the CSS property enhancers (the methods that generate the class name and styles for each property).

Enhancer groups

These enhancer groups are also exported. They're all objects with { propTypes, propAliases, propEnhancers } properties. They're mainly useful for if you want to inherit a subset of the Box CSS propTypes in your own components.

  • animation
  • background
  • borderRadius
  • borders
  • boxShadow
  • dimensions
  • flex
  • interaction
  • layout
  • list
  • opacity
  • overflow
  • position
  • spacing
  • svg
  • text
  • transform
  • transition

Classname prefix

By default ui-box uses ub- as the classname prefix before all ui-box generated classnames. You can alter this by using setClassNamePrefix('whatever-you-want-'). Note that the delimiter is included in the prefix... this is to support backwards compatibility with the old classnames (< v3), which you can achieve using something like this:

import { setClassNamePrefix } from 'ui-box'
setClassNamePrefix('πŸ“¦')

Safe hrefs

By default ui-box ensures that urls use safe protocols when passed to an element. We built this functionality into ui-box to protect the end users of the products you are building. You can opt-out of this by using configureSafeHref({enabled?: boolean, origin?: string}). This allows you to configure which protocols are acceptable (http:, https:, mailto:, tel:, and data:) and that the correct rel values are added (noopener, noreferrer(for external links)).

import { configureSafeHref } from 'ui-box'
configureSafeHref({
  enabled: true // the default behavior
})
import { configureSafeHref } from 'ui-box'
configureSafeHref({
  enabled: true
  origin: 'https://app.segmentio.com',
})

Additionally you can override the behavior on an individual component basis using the prop allowUnsafeHref

<Box is="a" href="javascript:alert('hi')" allowUnsafeHref>
  This is unsafe
</Box>

Server side rendering

To render the styles on the server side just use ReactDOMServer.renderToString() as usual and then call the extractStyles() method retrieve the rendered styles and cache. The styles can then be output to a <style> tag or an external stylesheet. The cache data should be passed to the hydrate() method on the client side before you call ReactDOM.hydrate().

For example:

'use strict'
const React = require('react')
const ReactDOMServer = require('react-dom/server')
const { default: Box, extractStyles } = require('.')

const element = React.createElement(Box, { margin: '10px', color: 'red' }, 'hi')

const html = ReactDOMServer.renderToString(element)
const { styles, cache } = extractStyles()

const page = `
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Page</title>
    <style>
      ${styles}
    </style>
  </head>
  <body>
    <main id="root">
      ${html}
    </main>
    <script type="application/json" id="ui-box-cache">
      ${JSON.stringify(cache)}
    </script>
  </body>
</html>
`
console.log(page)

Development

  • yarn dev starts the development Storybook at http://localhost:9009/.
  • yarn test runs the linter, unit tests and code coverage.
  • yarn ava -w runs the unit tests in watch mode.
  • yarn ava -u updates the snapshot tests.
  • yarn build transpiles the JavaScript files.
  • yarn release releases a new version (requires np to be installed globally).

License

ui-box is released under the MIT license.

Copyright Β© 2017 Segment.io, Inc.

More Repositories

1

evergreen

🌲 Evergreen React UI Framework by Segment
JavaScript
12,161
star
2

kafka-go

Kafka library in Go
Go
7,518
star
3

analytics.js

The hassle-free way to integrate analytics into any web application.
JavaScript
4,775
star
4

myth

A CSS preprocessor that acts like a polyfill for future versions of the spec.
JavaScript
4,345
star
5

ksuid

K-Sortable Globally Unique IDs
Go
4,121
star
6

daydream

A chrome extension to record your actions into a nightmare or puppeteer script
JavaScript
2,768
star
7

chamber

CLI for managing secrets
Go
2,283
star
8

stack

A set of Terraform modules for configuring production infrastructure with AWS
HCL
2,098
star
9

encoding

Go package containing implementations of efficient encoding, decoding, and validation APIs.
Go
911
star
10

golines

A golang formatter that fixes long lines
Go
803
star
11

asm

Go library providing algorithms optimized to leverage the characteristics of modern CPUs
Go
795
star
12

analytics-node

The hassle-free way to integrate analytics into any node application.
JavaScript
593
star
13

topicctl

Tool for declarative management of Kafka topics
Go
558
star
14

aws-okta

aws-vault like tool for Okta authentication
Go
541
star
15

niffy

Perceptual diffing suite built on Nightmare
JavaScript
535
star
16

analytics-ios

The hassle-free way to integrate analytics into any iOS application.
Objective-C
388
star
17

analytics-ruby

The hassle-free way to integrate analytics into any Ruby application.
Ruby
374
star
18

analytics-android

The hassle-free way to add analytics to your Android app.
Java
373
star
19

analytics-react-native

The hassle-free way to add analytics to your React-Native app.
TypeScript
337
star
20

consent-manager

Drop-in consent management plugin for analytics.js
TypeScript
326
star
21

parquet-go

Go library to read/write Parquet files
Go
314
star
22

ts-mysql-plugin

A typescript language service plugin that gives superpowers to SQL tagged template literals.
TypeScript
312
star
23

analytics-next

Segment Analytics.js 2.0
TypeScript
294
star
24

specs

Peer into your ECS clusters
JavaScript
273
star
25

fasthash

Go package porting the standard hashing algorithms to a more efficient implementation.
Go
261
star
26

ctlstore

Control Data Store
Go
261
star
27

ware

Easily create your own middleware layer.
JavaScript
254
star
28

analytics-php

The hassle-free way to integrate analytics into any php application.
PHP
252
star
29

analytics-python

The hassle-free way to integrate analytics into any python application.
Python
231
star
30

chrome-sidebar

Easiest way to embed an iframe as a chrome extension
JavaScript
208
star
31

typewriter

Type safety + intellisense for your Segment analytics
TypeScript
206
star
32

nsq.js

NSQ client for nodejs
JavaScript
203
star
33

stats

Go package for abstracting stats collection
Go
202
star
34

threat-modeling-training

Segment's Threat Modeling training for our engineers
197
star
35

in-eu

πŸ‡ͺπŸ‡Ί privacy first EU detection library for browsers
JavaScript
180
star
36

kubectl-curl

Kubectl plugin to run curl commands against kubernetes pods
Go
167
star
37

go-prompt

Go terminal prompts.
Go
167
star
38

analytics-react

[DEPRECATED AND UNSUPPORTED] The hassle-free way to integrate analytics into your React application.
JavaScript
160
star
39

is-url

Loosely validate a URL.
JavaScript
160
star
40

cwlogs

CLI tool for reading logs from Cloudwatch Logs
Go
142
star
41

kubeapply

A lightweight tool for git-based management of Kubernetes configs
Go
141
star
42

analytics-go

Segment analytics client for Go
Go
136
star
43

analytics.js-core

The hassle-free way to integrate analytics into any web application.
TypeScript
132
star
44

dependency-report

Generate usage reports of your JS dependencies
JavaScript
129
star
45

ecs-logs

Log forwarder for services ran by ecs-agent.
Go
115
star
46

analytics-java

The hassle-free way to integrate analytics into any java application.
Java
113
star
47

analytics.js-integrations

Monorepo housing Segment's analytics.js integrations
JavaScript
112
star
48

go-athena

Golang database/sql driver for AWS Athena
Go
107
star
49

Analytics.NET

The hassle-free way to integrate analytics into any C# / .NET application.
C#
107
star
50

go-queue

NSQ consumer convenience layer.
Go
104
star
51

analytics-swift

The hassle-free way to add Segment analytics to your Swift app (iOS/tvOS/watchOS/macOS/Linux).
Swift
102
star
52

xml-parser

simple non-compliant xml parser for nodejs
JavaScript
101
star
53

backo

exponential backoff without the weird cruft
JavaScript
99
star
54

analytics-vue

The hassle-free way to integrate analytics into your Vue application.
Vue
98
star
55

nsq-go

Go package providing tools for building NSQ clients, servers and middleware.
Go
94
star
56

consul-go

Go package providing building blocks for interacting with Consul.
Go
90
star
57

frictionless-signup

Reduce friction and increase customer data in your online forms using Segment & Clearbit
JavaScript
86
star
58

superagent-retry

Retry superagent requests for common hangups
JavaScript
85
star
59

pg-escape

sprintf-style postgres query escaping and helper functions
JavaScript
84
star
60

conf

Go package for loading program configuration from multiple sources.
Go
81
star
61

orbital

πŸš€πŸŒ A simple end-to-end testing framework for Go
Go
80
star
62

functions-library

A library of example functions to use with the Segment Developer Center
JavaScript
75
star
63

inbound

A url and referrer parsing library for node.
JavaScript
72
star
64

decibel

A small iOS app for recording office noise dB levels to Datadog.
Swift
69
star
65

analytics-angular

The hassle-free way to integrate analytics into your Angular application.
TypeScript
68
star
66

events

Go package for routing, formatting and publishing events produced by a program.
Go
62
star
67

glue

Generate typed Golang RPC clients from server code
Go
60
star
68

pingdummy

Example application for segmentio/stack
JavaScript
60
star
69

go-loggly

Loggly client for Go
Go
59
star
70

analytics-rust

Segment analytics client for Rust
Rust
55
star
71

retrofit-jsonrpc

Json-RPC with Retrofit.
Java
54
star
72

snippet

Render the analytics.js snippet.
JavaScript
53
star
73

nsq_to_redis

NSQ ✈ Redis {pubsub, capped lists}
Go
52
star
74

segment-proxy

Proxies requests to the Segment CDN and Tracking API.
Go
51
star
75

statsy

Simple statsd client for nodejs
JavaScript
49
star
76

sherlock

A pluggable service-detection tool
JavaScript
49
star
77

is-email

Component: loosely validate an email address.
JavaScript
49
star
78

objconv

A Go package exposing encoder and decoders that support data streaming to and from multiple formats.
Go
49
star
79

cli

Go package providing high-level constructs for command-line tools.
Go
48
star
80

facade

Providing common fields for analytics integrations, since 2013.
JavaScript
47
star
81

agecache

An LRU cache with support for max age
Go
47
star
82

validate-form

Easily validate a form element against a set of rules.
JavaScript
44
star
83

go-stats

Go stats ticker utility
Go
44
star
84

go-snakecase

Faster snakecase implementation
Go
43
star
85

utm-params

parse and get all utm parameters
JavaScript
42
star
86

aws-billing

An API to learn how much your AWS hosting costs every month
JavaScript
39
star
87

action-destinations

Action Destinations are the new way to build streaming destinations on Segment.
TypeScript
38
star
88

testdemo

Examples for https://segment.com/blog/5-advanced-testing-techniques-in-go/
Go
38
star
89

data-digger

Dig through structured messages in Kafka, S3, or local files
Go
37
star
90

segment-docs

Segment Documentation. Powered by Jekyll.
HTML
36
star
91

feature

Feature gate database designed for simplicity and efficiency.
Go
36
star
92

redis-go

Go package providing tools for building redis clients, servers and middleware.
Go
36
star
93

http_to_nsq

Publishes HTTP requests to NSQD (for CI webhooks etc)
Go
36
star
94

analytics.js-integration

The base integration factory used to create custom analytics integrations for analytics.js.
JavaScript
35
star
95

ebs-backup

Backup EBS Volumes
Go
34
star
96

Analytics.Xamarin

Analytics for Xamarin, a portable class library supporting iOS, Android, Mac OS, and others.
C#
34
star
97

go-hll

Go implementation of HLL that plays nicely with other languages
Go
34
star
98

terraform-segment-data-lakes

Terraform modules which create AWS resources for a Segment Data Lake.
HCL
34
star
99

analytics-kotlin

The hassle-free way to add Segment analytics to your Kotlin app (Android/JVM).
Kotlin
32
star
100

errors-go

Go package providing various error handling primitives.
Go
32
star