GithubHelp home page GithubHelp logo

kyleamathews / typography.js Goto Github PK

View Code? Open in Web Editor NEW
3.8K 28.0 181.0 8.59 MB

A powerful toolkit for building websites with beautiful design

Home Page: http://kyleamathews.github.io/typography.js/

License: MIT License

JavaScript 91.56% CoffeeScript 8.44%
typography javascript typography-themes theme typography-engine css-in-js css

typography.js's Introduction

Typography.js Build Status Coverage Status

A powerful toolkit for building websites with beautiful design.

Install

npm install typography

Demo/playground

https://kyleamathews.github.io/typography.js

Why

The goal of Typography.js is to provide a high-level elegant API for expressing typographic design intent.

Typography is a complex system of interrelated styles. 100s of style declarations on dozens of elements must be in harmonious order. Trying one design change can mean making dozens of tedious recalculations and CSS value changes. Creating new Typography themes with CSS feels hard.

Typography.js provides a vastly simpler way to define and explore typography designs.

You provide configuration to the Typography.js JS api and it uses its Typography engine to generate CSS for block and inline elements.

Typography.js makes it easy to create designs that are unique, personal, and custom to your project.

Themes & Plugins

  • themes: Typography.js themes are simple Javascript objects. As such they're easy to share across projects or even open source and share via NPM.
  • plugins: Plugins are functions that extend or modify the core Typography engine. They can change how headers are styled or add specialized styles e.g. for code or tables.

Sites that use Typography.js

Javascript usage

import Typography from 'typography'

const typography = new Typography({
  baseFontSize: '18px',
  baseLineHeight: 1.45,
  headerFontFamily: ['Avenir Next', 'Helvetica Neue', 'Segoe UI', 'Helvetica', 'Arial', 'sans-serif'],
  bodyFontFamily: ['Georgia', 'serif'],
  // See below for the full list of options.
})

// Output CSS as string.
typography.toString()

// Or insert styles directly into the <head> (works well for client-only
// JS web apps.)
typography.injectStyles()

Themes

We maintain 30 (and counting) themes that are ready to use on your next project. These are each published as separate NPM packages. Explore themes at http://kyleamathews.github.io/typography.js.

Using themes

Here's an example of how to use the Funston theme.

  1. First save the package to your project npm install --save typography-theme-funston
  2. Then import and pass into Typography when initializing.
import Typography from 'typography'
import funstonTheme from 'typography-theme-funston'

const typography = new Typography(funstonTheme)

Customizing themes

Themes are just javascript objects so it's easy to modify them as needed. For example, if you're using the Funston theme but want to increase the base font size slightly:

import Typography from 'typography'
import funstonTheme from 'typography-theme-funston'
funstonTheme.baseFontSize = '22px' // was 20px.

const typography = new Typography(funstonTheme)

Or you can use the imperative API overrideThemeStyles to directly set/override styles on a theme:

import Typography from 'typography'
import funstonTheme from 'typography-theme-funston'
funstonTheme.overrideThemeStyles = ({ rhythm }, options) => ({
  'h2,h3': {
    marginBottom: rhythm(1/2),
    marginTop: rhythm(2),
  }
})

const typography = new Typography(funstonTheme)

Published Typography.js Themes

Plugins

Plugins are functions that extend or modify the core typography engine. they can change how headers are styled or add specialized styles e.g. for code or tables. Currently there's one plugin available, typography-plugin-code.

To use the Code plugin, first install using NPM.

npm install --save typography-plugin-code

Then add to your theme before creating a new typography object.

import Typography from 'typography'
import CodePlugin from 'typography-plugin-code'
import sternGroveTheme from 'typography-theme-stern-grove'

sternGroveTheme.plugins = [
  new CodePlugin(),
]

const typography = new Typography(sternGroveTheme)

React.js helper components.

Typography.js includes two helper components for your React.js projects, TypographyStyle and GoogleFont. These are ideal for server-rendering.

  • TypographyStyle creates a style element and inserts the generated CSS for your theme.
  • GoogleFont creates the link element to include the Google Fonts & weights specified in your theme.

To use, first install the package npm install --save react-typography then import them into your html.js file.

import { TypographyStyle, GoogleFont } from 'react-typography'
// Best practice is to have a typography module
// where you define your theme.
import typography from 'utils/typography'

// Inside your React.js HTML component.
<html>
  <head>
    <TypographyStyle typography={typography} />
    <GoogleFont typography={typography} />
  </head>
  <body>
    // stuff
  </body>
</html>

Using with create-react-app

If you use the default create-react-app template, the above React.js solution will not work, and the typography.injectStyles() solution will not enable Google Fonts.. A workaround is to install typography-inject-fonts and do

import Typography from 'typography'
import funstonTheme from 'typography-theme-funston'
import injectFonts from 'typography-inject-fonts'

const typography = new Typography(funstonTheme)
typography.injectStyles()
injectFonts(typography)

API

Configuration

When creating a new instance of Typography, you can pass in a configuration object. All configuration keys are optional.

  • title: The theme title.
  • baseFontSize: The base font size in pixels, defaults to 16px.
  • baseLineHeight: The base line height using the css unitless number, defaults to 1.45.
  • scaleRatio: The "scale ratio" for the theme. This value is the ratio between the h1 font size and the baseFontSize. So if the scale ratio is 2 and the baseFontSize is 16px then the h1 font size is 32px.
{
  scaleRatio: 2,
}
  • googleFonts: An array specifying Google Fonts for this project.
googleFonts: [
  {
    name: 'Montserrat',
    styles: [
      '700',
    ],
  },
  {
    name: 'Merriweather',
    styles: [
      '400',
      '400i',
      '700',
      '700i',
    ],
  },
],
  • headerFontFamily: An array of strings specifying the font family stack for headers e.g. ['Helvetica', 'sans-serif']. Defaults to a system UI font stack.
  • bodyFontFamily: An array of strings specifying the font family stack for the body, defaults to ['georgia', 'serif'].
  • headerColor: A css color string to be set on headers. Defaults to inherit.
  • bodyColor: A css color string to be set for body text. Defaults to hsl(0,0%,0%,0.8).
  • headerWeight: Specify the font weight for headers. Defaults to bold.
  • bodyWeight: Specify the font weight for body text. Defaults to normal.
  • boldWeight: Specify the font weight for "bold" (b, strong, dt, th) elements. Defaults to bold.
  • blockMarginBottom: Specify the default margin-bottom for block elements. Defaults to one "rhythm unit" (i.e. the height of the base line height).
  • includeNormalize: Include normalize.css. Normalize.css is an excellent project which works to normalize the base browser CSS across browsers and serves as an excellent foundation for Typography.js. We include normalize.CSS by default but if you're already including it elsewhere in your project, you can disable including it here by passing false.
  • overrideStyles: Imperative API for directly adding to or overriding auto-generated styles. It's called with a Vertical Rhythm object, the options object, and the algorithmically generated styles.
overrideStyles: ({ adjustFontSizeTo, rhythm }, options, styles) => ({
  h1: {
    fontFamily: ['Montserrat', 'sans-serif'].join(','),
  },
  blockquote: {
    ...adjustFontSizeTo('19px'),
    color: gray(41),
    fontStyle: 'italic',
    paddingLeft: rhythm(13/16),
    marginLeft: rhythm(-1),
    borderLeft: `${rhythm(3/16)} solid ${gray(10)}`,
  },
  'blockquote > :last-child': {
    marginBottom: 0,
  },
})
  • overrideThemeStyles: This has the same function signature as overrideStyles but should be used in place of overrideStyles when using a 3rd-party theme so as to not delete the theme's own overrideStyles function.
overrideThemeStyles: ({ rhythm }, options, styles) => ({
  'h2,h3': {
    marginBottom: rhythm(1/2),
    marginTop: rhythm(2),
  }
})

Related

Developing Typography.js

Typography.js is a monorepo facilitated by Lerna.

TODO: document constants + compass-vertical-rhythm + using typgraphy.js for inline styles.

=======

Backers

Support us with a monthly donation and help us continue our activities. [Become a backer]

Sponsors

Become a sponsor and get your logo on our README on Github with a link to your site. [Become a sponsor]

typography.js's People

Contributors

aalaap avatar artcg avatar barrythepenguin avatar bodaz avatar calcsam avatar chasemccoy avatar cmmartin avatar cpboyd avatar d2s avatar dschau avatar dvzrd avatar gerrgg avatar jamiebuilds avatar josxa avatar kitze avatar kyleamathews avatar lautarolobo12 avatar leimonio avatar lipis avatar markfchavez avatar mbao01 avatar mitogh avatar mokkapps avatar nandorojo avatar plan-do-break-fix avatar shen-yu avatar thevangelist avatar viatsko avatar wowu avatar zcserei avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

typography.js's Issues

Outdated & missing package.json metadata

Individual packages should have an URL to the Git repository.

package.json files in /packages/ directory current lack details. Missing "repository": field creates discovery problems for people who look individual packages at the npm package directory (as they need to search separately from search engines to find where original source code is located).


Also, even while individual typography package already has the right "homepage": metadata, it has old URL in the"repository": field. Currently points to a broken repository address (as you had renamed repository from typography to typography.js).

Currently:

  "repository": {
    "type": "git",
    "url": "https://github.com/KyleAMathews/typography.git"
  },

Should be:

  "repository": {
    "type": "git",
    "url": "https://github.com/KyleAMathews/typography.js.git"
  },

Example files from another project:


Should individual packages's "repository": point to the Git repository?
(That is how Jest has solved the metadata issue.)

Do you need any help with this?

Rename Repo

the repo's name is typography.js ...

... typography.js not .coffee

Got some serious badfeelsman.jpg upon realizing this was .coffee

Apparently im not the only one longing for pure js (es6 hopefully) #11

Add <SubTheme> component

In your typography configuration, you can define additional named "themes". These additional configurations are merged into the base configuration i.e. default config <-- config <-- theme

In your code, you'd import the Theme component and use it to surround the section of your site that you want themed differently.

Feature Suggestions

Here are some free ideas:

  • attach (ArrowUp/ArrowDown) key binding for inputs under focus. Would be much easier to flip though fonts if I could just press a key to get the next font.
    click ... scroll ... click is too much for me man 😭
  • add letter-spacing, and other CSS3 typography properties
  • make a snapshot feature. Allow user to make a "snapshot" of the current config (ideally with just a button/keypress)
    • Later allow the user to rapidly flip through those snapshots (which also would have a key binding)
      • delete the ones they don't want
      • want to make it a full app?
        • rename snapshots
        • toggleable per-snapshot lock to prevent accidental deletion
        • showcase / share
        • persist snapshots via accounts (OpenID/OAuth?)
        • one-click export to codepen.io and the like
  • make this extensible so you can use it anywhere
    • Chrome DevTools extension?
    • React Component that hijacks a <style>...</style> in <head>...</head>
    • lots of implications to consider—what about inline styles?

Typography configurations

Put together a really nice configuration? Add it here so others can learn. The best of these will get added to the README.md and the app.

Support colors

Themes should be able to set colors in the option which would get picked up by the design tools. Plugins should also be able to accept colors as an option.

When using react-typography, replace Google Fonts CSS w/ css font-face declaration

This saves the extra request to Google Fonts to grab the CSS file which can significantly delay starting the download of the fonts.

Google Fonts doesn't recommend this as they want you to always be grabbing the latest versions of fonts but if you regularly rebuild your site then you'll generally be up-to-date.

This might be better actually as a Gatsby plugin. It'd be an HTML post-processor — it'd scan HTML for google font css strings and replace them with the font-face declarations.

Easy responsive typography

Like what we do for headers but for everything else. Anytime you call fontSizeToMS (or perhaps a different function) it should generate media queries rules for each modular-scale defined in the config.

Change header/body gray to header/body color & don't specify a header color by default

Only supporting gray colors is confusing plus it's not at all obvious that Typography.js is depending on
gray-percentage. So instead use headerColor and bodyColor and let people pass in a string which corresponds to a valid css color value.

Also @bvaughn pointed out that specifying the header color made it difficult to control the background/foreground colors as headers didn't inherit.

Currently the default is that headers are slightly darker than the body. Which is a solid design choice but confusing as a default as it's hard to override. So by default let's set headerColor to inherit.

Unexpected CSS img styling

This is in a similar vein to https://github.com/gatsbyjs/gatsby-starter-blog/issues/16 & as frustratingly tweeted https://twitter.com/kaihendry/status/778166191860936704 I don't expect style to be set here.

What is the good reason RE https://twitter.com/kylemathews/status/778262611058053126 ?

I wasted a serious amount of time over this margin-bottom:1.66667rem. In hindsight the issue was staring at me from Chrome dev tools, but I really didn't expect typography.js to setup so much CSS. I also resent it's uglyfying my HTML's header and not a separate file too.

I really don't quite understand how a modern day dev is supposed to track cascading CSS rules and override & normalise things, since it seems like I can't assume sane defaults anymore.

Validate options

That option keys are allowed + some options e.g. that modular scales media query is a string and a valid css measure. Also that any string modular scales (no media query) are listed before any array media queries as otherwise, they'd just override the responsive modular scale.

Add breakpoints option

Should be an object with structure something like:

{
  breakpoints: {
    "@media only screen and (max-width:768px)": { // any valid media query.
      scale: 1.618 // Override the default scale
      fontSize: '95%', // Change body font size.
    },
    "@media only screen and (max-width:480px)": { // any valid media query.
      fontSize: '85%',
    },
  }
}

Perhaps also support calling overrideStyles in each breakpoint as well to both neatly consolidate responsive theming + this would be a natural way to design a breakpoints UI for the design tools.

Universal typography

So I finally find a time to rethink universal typography (React + React Native) approach. I am afraid current design is not sufficient. What we need:

  1. Simple theme definition with implicit dependencies likes rhythm with inline styles in mind.
  2. Define only styles, not all HTML elements since they don't exist in React Native and are often superfluous. React soon will use Text and View for span and div. facebook/react#7382
  3. We need to define the common universal set of element styles: Text, Paragraph, Heading, Subheading, List, OrderedList... It can mimics HTML of course, but we have a chance to simplify it and make it more explicit.

In the other words, what we need is a computable expression with typography idiomatic DSL (domain specific language). It must be obvious what it does and it must follow React Native styling, which is basically a subset of CSS.

Then we can integrate universal typography into https://github.com/este/este

What do you think?

Example or how to use Typography React Components in Head

Having trouble understanding how the react components in your example are being added to the head?

<html>
  <head>
    <TypographyStyle typography={typography} />
    <GoogleFont typography={typography} />
  </head>
  <body>
    // stuff
  </body>
</html>
<body>
<div id="app" />
...

In my app the head is inside an index.html page - not a react component. My React application code is being added to the body a la

  ReactDOM.render(
    <App store={ AppStore } />,
    document.getElementById('app')
  );

Can one add the typography React components in the head via ReactDOM.render?

Any help appreciated.

Mark themes which don't require external Webfonts

Sorry, I raised the issue before by email or twitter. However my wish remains the same. A method to see which themes do not use external fonts. Currently there is no easy way to tell upon:
http://kyleamathews.github.io/typography.js/

My end goal is to evaluate themes (or font styles) that do not bring in external fonts. External fonts are a no go in terms of Web performance for me and I'm trying to get the best "look" between major platforms like Android & IOS.

Allow setting weight for body

Would be nice to be able to set body font-weight independently of headings. For example, Roboto 400 is quite heavy for a body font

Terminology fixes

As we're not using the "modular scale" terminology any more (just scale).

Don't create styles string by default

There's a number of use cases for creating new instances of Typography where you don't want/need to generate the string. So instead of doing this by default (it's fairly expensive, 20-30ms), move style creation code to a createStyles function where it can be called on demand e.g. in the react.js component.

Add font-face support

Add an array of objects each specifying the font-face rule e.g.

{
  fontFamily: "DinNextRounded",
  src: [
    "url(../fonts/dinnnextrounded_bold.eot)",
    "url(..'fonts/dinnextrounded_bold.woff)"
  ],
  fontWeight: 700
}

"scale is not a function" with typography-theme-lincoln

typography-theme-lincoln uses the scale function at least in release 0.15.0 and 0.14.0 but doesn't appear to import it. I tried it in gatsby just now, and 0.15.0 gives the error during build time, and 0.14.0 initially seemed to work but then had the same error during runtime. 0.13.0 does work.

Javascript version

Is there a way to get a dist (transpiled) version as plain Javascript? I don't use npm, or coffeescript in my project but would love to try this component?

React Native

I think Este needs this for React Native ASAP. Should not be hard. Universal typography FTW.

overrideThemeStyles = Broken

Returning any value breaks everything. I have tried everything i can think of - looking at your code it woudl appear your demo is broken as you need top return a copied object - this still breaks everything.

ERROR in .//css-loader?{"modules":true,"sourceMap":true,"localIdentName":"[name][local][hash:base64:5]","importLoaders":1}!.//postcss-loader!./src/shared/app/index.css
Module build failed: TypeError: Expected a string
at module.exports (/home/ubuntu/workspace/node_modules/decamelize/index.js:4:9)
at /home/ubuntu/workspace/node_modules/typography/dist/utils/compileStyles.js:36:51
at /home/ubuntu/workspace/node_modules/typography/dist/utils/compileStyles.js:45:11
at /home/ubuntu/workspace/node_modules/lodash/_createBaseEach.js:24:11
at forEach (/home/ubuntu/workspace/node_modules/lodash/forEach.js:38:10)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.