Giter Club home page Giter Club logo

capsize's People

Contributors

19h47 avatar apkoponen avatar belkin avatar benjervis avatar chrisru avatar danielroe avatar dependabot[bot] avatar dremora avatar jahredhope avatar markdalgleish avatar mattcompiles avatar michaeltaranto avatar mrm007 avatar seek-oss-ci avatar stefanhamburger 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

capsize's Issues

Some combination of values don't wrap the full text height

Description

I noticed some specific combination of values cause the box height to not fully wrap the text, for example:

image

And this other combination gets closer:

image

At first I thought this only happened when using font height, but happens when using either font height or cap height.

I'm guessing this could be an issue with rendering pixels in browsers (due to non integer values), or a rounding error. Any ideas about this one? is it expected? (if not I'm happy to take a look and try contribute!)

Document that it's the hhea ascender/descender/lineGap that matter.

https://codepen.io/dabrahams/pen/BadXbRe shows a port of the capsize computations to scss; I've verified they give the same numerical results as the typescript code for 3 different fonts.

As you can see, the tops of the paragraphs are all offset downward, whereas I expected to see the top of the first paragraph at 0. At the top of the SCSS you can switch the font size arbitrarily, and set the font to either 'arial' or 'georgia' (or any other font you like, as long as you add the metrics around line 119 of the SCSS).

Am I doing something wrong here? Missing something?

Many thanks in advance.

Getting an error when using createTextStyle

I'm working on a monorepo, based on nx, and using vite, vitest, vanilla-extract, react and typescript.
I use createTextStyle within my Typography component like this:
export const textCapsize = createTextStyle({ fontSize: 14, leading: 20, fontMetrics: ourFontMetrics, });

(ourFontMetrics is imported from '@capsizecss/metrics')
I use textCapsize within our recipe (vanilla-extract).

I'm getting a test failure with the following error:
Error: Styles were unable to be assigned to a file. This is generally caused by one of the following:

   - You may have created styles outside of a '.css.ts' context
   - You may have incorrect configuration. See https://vanilla-extract.style/documentation/getting-started`

It looks like something is missing from our configuration but wasn't able to find it.

TailwindCSS Plugin

It’d be cool to see an official TailwindCSS plugin. There’s three unofficial plugins already:

TailwindCSS integrations have been discussed in #8

I also made my own plugin version over the past several days, written in TypeScript and supporting arbitrary values with cap height, line gap, and other features. Though, I also made design decisions that split from the current library. If you’re still interested, I could polish it a bit and make a draft PR.

If there’s no plans to support TailwindCSS, feel free to just close this issue.

Website updated without Font Metrics

Hi,

In our project, our users are relying on getting the font metrics using your CapSize docs.
Upload the file and then retrieve the Font Metrics from there.

I saw that you now have a new implementation, but this is kind of an issue for us. We would like to still be able to add metrics in a config file retrieving them manually from the site.
We might think about using the new function but as for now, not seeing all the 5 metrics in the doc site is breaking our flow.

Could be possible to add back the functionality to see the FontMetrics when uploading the file?

Thank you.

Cuts off descenders when using common CSS approaches for line truncation

The two most common approaches I've seen for line truncation are summarized in this CSS Tricks article. Using either approach causes the descenders to be hidden.

CleanShot 2020-07-23 at 17 49 07

The screenshot above was captured after adding the following styles to the div that wraps the text on https://seek-oss.github.io/capsize/. The font in the screenshot is Roboto from Google Fonts.

    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;

Would the best way forward for me to support truncation be to look at using a JS approach like Clamp.js?

Not finding capsize properly for this font

WARNING I do recognize that this isnt released yet, and Im by no means using in production. Just a mere fellow dev giving it a whirl, because im excited.

Our custom bought font we use in our design system doesn't seem to work. Just wanting to let you guys know in case there is a bug.

Font: https://cdn.autoguru.com.au/assets/fonts/avertastd-regular-webfont.woff2 (there is a woff too)

Screen Shot 2020-06-04 at 5 12 14 pm


Also; the website doesnt work in firefox :/

Once again. Please see this as a friendly fyi, nothing more, nothing less. Close the issue if you feel :)

@capsizecss/metrics missing metrics

29 Google Fonts at the time of writing are missing the required metrics for capsize.

The required metrics are:

{
    capHeight: 700,
    ascent: 1058,
    descent: -291,
    lineGap: 0,
    unitsPerEm: 1000,
}

The incomplete fonts are:

Abhaya Libre
  missing capHeight
Anaheim
  missing capHeight
Averia Gruesa Libre
  missing capHeight
Averia Libre
  missing capHeight
Averia Sans Libre
  missing capHeight
Averia Serif Libre
  missing capHeight
Bentham
  missing capHeight
Buda Light
  missing capHeight
Cantarell
  missing capHeight
Caudex
  missing capHeight
Coda
  missing capHeight
Coda Caption ExtraBold
  missing capHeight
Coiny
  missing capHeight
Della Respira
  missing capHeight
Gidugu
  missing capHeight
Glegoo
  missing capHeight
Kavivanar
  missing capHeight
Kristi
  missing capHeight
M PLUS 1p
  missing capHeight
Mina
  missing capHeight
News Cycle
  missing capHeight
Oxygen
  missing capHeight
Pavanam
  missing capHeight
Pontano Sans
  missing capHeight
Rounded Mplus 1c
  missing capHeight
Seymour One
  missing capHeight
Six Caps
  missing capHeight
Vibur
  missing capHeight
Yellowtail
  missing capHeight

I checked the actual font tables of an example Averia Serif Libre and found that the capHeight value is missing. What are other ways we can calculate capHeight?

expose xHeight to metrics package

Hello, curious if you'd be open to exposing xHeight for the @capsizecss/metrics package? I'm calculating this myself with unpack right now, but figured it'd be nice if it was easily available for Google Font metrics.

Doesn't tsc cleanly to javascript

When I run tsc in the root directory, I get lots of errors, and this is after responding to many of them by using npm to install various modules:

packages/core/stories/createStyleObject.stories.ts:1:10 - error TS2614: Module '"@emotion/css"' has no exported member 'css'. Did you mean to use 'import css from "@emotion/css"' instead?

1 import { css } from '@emotion/css';
           ~~~

packages/metrics/scripts/build.ts:3:20 - error TS2307: Cannot find module 'dedent' or its corresponding type declarations.

3 import dedent from 'dedent';
                     ~~~~~~~~

packages/metrics/scripts/build.ts:4:20 - error TS2307: Cannot find module 'p-queue' or its corresponding type declarations.

4 import PQueue from 'p-queue';
                     ~~~~~~~~~

packages/metrics/scripts/build.ts:5:25 - error TS2307: Cannot find module 'cli-progress' or its corresponding type declarations.

5 import cliProgress from 'cli-progress';
                          ~~~~~~~~~~~~~~

packages/metrics/scripts/build.ts:6:31 - error TS2307: Cannot find module '@capsizecss/unpack' or its corresponding type declarations.

6 import { Font, fromUrl } from '@capsizecss/unpack';
                                ~~~~~~~~~~~~~~~~~~~~
...

Maybe there's some implicit knowledge I'm supposed to have about how to build such projects for use in a website?

createFontStack returns incorrect values for fonts with the same metrics

We use appleSystem and BlinkMacSystemFont metrics to create a font stack.

createFontStack([appleSystem, BlinkMacSystemFont])

Calling this method returns this

@font-face {
  font-family: "-apple-system Fallback";
  src: local('BlinkMacSystemFont');
  ascent-override: 95.2148%;
  descent-override: 20.5078%;
}

Both fonts have the same meters(here and here) and the return value should not have ascent-override and descent-override styles. The calculation of these parameters is performed by this code. I think that there should be a check of metrics and if the values match, then we should not calculate ascent-override and descent-override parameters.

Question: Determining the font metrics without referencing to capsize website

Hi,

First of all amazing work! Now I can sleep in peace knowing that my paragraph is being spaced properly.

I have a question about determining the font metrics used by capsize, is it possible to obtain those without going through the website? I've tried comparing the metrics on capsize website and metrics generated by this tool, but it's vastly different. (am I missing something crucial here?)

Cheers

Expose reference to Vanilla Extract CSS Variables

Is it possible to get a reference to the CSS Variables that @capsizecss/vanilla-extract creates?

For example, in my Vanilla Extract project:

.Text__3ydohf1 {
    --fontSize__1d0g9qk0: 17.094px;
    --lineHeight__1d0g9qk1: 18px;
    --capHeightTrim__1d0g9qk2: -0.0745em;
    --baselineTrim__1d0g9qk3: -0.2765em;
}
.capsize_capsizeStyle__1d0g9qk4 {
    font-size: var(--fontSize__1d0g9qk0);
    line-height: var(--lineHeight__1d0g9qk1);
}

I'd like to have responsive icons inside my capsized text and I want to access the generated CSS Variables to set height, margin-top and margin-bottom so that my icons play nicely alongside that capsized text.

Currently I have:

.Icon_sizes_default__dlhcj82 {
    height: 1.25em;
    width: 1.25em;
    margin-top: -6px;
    margin-bottom: -6px;
}

I would love to have:

.Icon_sizes_responsive__some-hash {
    height: var(--lineHeight__1d0g9qk1);
    width: var(--lineHeight__1d0g9qk1);
    margin-top: var(--capHeightTrim__1d0g9qk2);
    margin-bottom: var(--baselineTrim__1d0g9qk3);
}

capsize_capsizeStyle rules not being built in Remix projects

It looks like @capsizecss/vanilla-extract is not including the capsize_capsizeStyle rules (or related pseudo elements) when in a Remix project. The element in question has the correct className included, but the styles themselves are missing.

Here is a quick screenshot that shows the problem:
image

In the above image you can see that capsize_capsizeStyle_1d0g9qk4 is one of the included class names, but its rules are missing.

Here is a minimal reproduction in stackblitz

Let me know if I can provide any more info or troubleshooting help, or if I am doing something wrong.

Question: System fonts?

Hello

First of all, I'd like to thank you for creating this library. I've been playing around with it and it's been very impressive. Also makes my codebase so much cleaner by not having to support the basekick solution :)

I have a question about using capsize with system fonts (e.g.font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";) and the like. Any examples I can find are using a specific font to create the font metrics. What would the recommended approach be in dealing with system fonts?

Feature idea: Tailwind config output

Hey there, Congrats on the launch!

I was thinking that a Tailwind plugin output would make a good feature.
image
I've modified an example from their docs to illustrate how the output could be displayed:

// tailwind.config.js
const plugin = require('tailwindcss/plugin')

module.exports = {
  plugins: [
    plugin(function ({ addComponents }) {
      const capsizedText = {
        '.capsizedText': {
          fontSize: '71.73626373626374px',
          lineHeight: '76px',
          padding: '0.05px 0',
          ':before': {
            content: "''",
            marginTop: '-0.16127450980392152em',
            display: 'block',
            height: 0,
          },
          ':after': {
            content: "''",
            marginBottom: '-0.18861825980392152em',
            display: 'block',
            height: 0,
          },
        },
      }
      addComponents(capsizedText)
    }),
  ],
}

What do you think?

Docs: Small Correction for Responsive Typography Section

In https://github.com/seek-oss/capsize/blob/master/packages/vanilla-extract/README.md#responsive-typography

const vars = createTheme({
  bodyText: {
    mobile: precomputeValues({ fontSize: 18, leading: 24, fontMetrics }),
    tablet: precomputeValues({ fontSize: 16, leading: 22, fontMetrics }),
    desktop: precomputeValues({ fontSize: 14, leading: 18, fontMetrics }),
  },
});

Should be:

const [className, vars] = createTheme({
  bodyText: {
    mobile: precomputeValues({ fontSize: 18, leading: 24, fontMetrics }),
    tablet: precomputeValues({ fontSize: 16, leading: 22, fontMetrics }),
    desktop: precomputeValues({ fontSize: 14, leading: 18, fontMetrics }),
  },
});

Support calculating based on fontSize

Capsize currently accepts inputs which act as constraints for the algorithm generating the styles. Primarily, those constraints are capHeight & leading*:

const styles = capsize({ fontMetrics, leading: 12, capHeight: 10 });

However, my project has a design which specifies a set of fontSize & lineHeight combos:

fontSize lineHeight
12px 20px
14px 22px
20px 28px

I'd like to be able to use capsize to generate the correct style object given those inputs as constraints:

const styles = capsize({ fontMetrics, fontSize: 12, lineHeight: 20 });

I did a rough draft in #3, but it's out of date and misses a few cases like snapping to grid.


* (leading can also be specified as gap, but I'll treat that as a variation of leading here)

ESM incompatibility due to round-to (direct dependency)

First of all thank you for providing and esm export but unfortunately it's not working as expected because round-to (a direct dependency) isn't an esm module itself.

Error:

SyntaxError: Importing binding name 'default' cannot be resolved by star export entries.

See reproduction here (capsize):
https://esm.codes/#aW1wb3J0IGNhcHNpemUgZnJvbSAnaHR0cHM6Ly91bnBrZy5jb20vY2Fwc2l6ZSc7Cgpjb25zdCBzdHlsZXMgPSBjYXBzaXplKHsKICBjYXBIZWlnaHQ6IDE2LAogIGxpbmVHYXA6IDgsCiAgZm9udE1ldHJpY3M6IHsKICAgIGNhcEhlaWdodDogNzAwLAogICAgYXNjZW50OiAxMDU4LAogICAgZGVzY2VudDogLTI5MSwKICAgIGxpbmVHYXA6IDAsCiAgICB1bml0c1BlckVtOiAxMDAwLAogIH0sCn0pOwoKY29uc29sZS5sb2coInN0eWxlczogIiwgc3R5bGVzKTs=

or

import capsize from 'https://unpkg.com/capsize';

const styles = capsize({
  capHeight: 16,
  lineGap: 8,
  fontMetrics: {
    capHeight: 700,
    ascent: 1058,
    descent: -291,
    lineGap: 0,
    unitsPerEm: 1000,
  },
});

console.log("styles: ", styles);

See reproduction here (round-to):
https://esm.codes/#aW1wb3J0IHJvdW5kVG8gZnJvbSAnaHR0cHM6Ly91bnBrZy5jb20vcm91bmQtdG8nOwoKY29uc29sZS5sb2coInJvdW5kOiAiLCByb3VuZFRvKDEuMjM0LCAyKSk7

or

import roundTo from 'https://unpkg.com/round-to';

console.log("round: ", roundTo(1.234, 2));

Be careful not to use a cdn like cdn.skypack.dev it will look like it's working because they magically translate non esm module into esm module on the fly, see here:

https://esm.codes/#aW1wb3J0IHJvdW5kVG8gZnJvbSAnaHR0cHM6Ly9jZG4uc2t5cGFjay5kZXYvcm91bmQtdG8nOwoKY29uc29sZS5sb2coInJvdW5kOiAiLCByb3VuZFRvKDEuMjM0LCAyKSk7

or

import roundTo from 'https://cdn.skypack.dev/round-to';

console.log("round: ", roundTo(1.234, 2));

Latest version of `@capsizecss/metrics` doesn't generate font files

I installed the latest version of @capsizecss/[email protected] and tried to run the example code from the README:

import { createStyleObject } from '@capsizecss/core';
import arialMetrics from '@capsizecss/metrics/arial';

const capsizeStyles = createStyleObject({
  fontSize: 16,
  leading: 24,
  fontMetrics: arialMetrics,
});

I got an error saying that @capsizecss/metrics/arial module was not found. This works perfectly in v1.0.1

Supporting rem as fontSize and lineheight

I'm looking into supporting 'rem' as a unit for our design system, and migrating away from pixel values.

Currently, if I want to do that, I have to override the outputs provided from capsize like so:

export const textCrop = ({
  lineHeight,
  fontSize,
  fontMetrics,
}: TextCropProps) => {
  const fontSizeAsNumber = parseFloat(fontSize);
  const leading = lineHeight * fontSizeAsNumber;

  const capsizeStyles = createStyleObject({
    fontSize: fontSizeAsNumber,
    leading,
    fontMetrics,
  });

  capsizeStyles.fontSize = fontSize;
  capsizeStyles.lineHeight = lineHeight.toString();
  return capsizeStyles;
};

with arguments as an example:fontSize: '2rem' lineHeight: 1.5

Looking into the source code - it seems like pixels are only needed for rounding – I assume if I wanted to use capHeight as a pixel value, and lineGap?

Is there any potential issue with me:

a) passing values in as rem - my assumption is not due to the relative nature of all the calculations
b) overriding the output back to a rem unit?

Expose SCSS mixin?

Capsize is great! I am working on adding it to a project. Given the stack I am using the only way of dynamically generating the CSS is via a SASS mixin. I therefore had to mimick the JS calculations, so I was curious if it would be something you would considering exposing from within capsize itself? If so, I can put a PR in for it 👍

List Tag Rendering Incorrectly With Bullet

Hi there!

Working through adding capsize to the text component in our design system and am running into an issue where capsized text in an li tag renders on the next line of the bullet instead of inline. Is this use case not meant to be supported or is this a general issue?

Reproduction

You can easily reproduce it on https://seek-oss.github.io/capsize/ by changing the tag of the capsized text to an li tag. See the screenshot below:

Screen Shot 2021-10-05 at 10 34 55 AM

createStyles utility

First, thanks for such a great little utility library!

I was curious if you'd be willing to add a createStyles utility that would allow exporting just the calculated styles so this library can be used more easily in React Native? I've tested it out and it seems to work great! Just a little awkward having to pull the styles off and rework them. Happy to help put a PR together if this sounds good, just let me know :)

Start error

steps to reproduce

  1. git clone https://github.com/seek-oss/capsize.git
  2. pnpm i
  3. pnpm start

MacOS 13.3.1
node version: 16.20.0
npm version: 8.19.4
pnpm version: 7.29.1

error log:

> [email protected] start
> pnpm site:start


> [email protected] site:start /Users/bytedance/github/capsize
> manypkg run site start

yarn run v1.22.11
$ gatsby develop -H 0.0.0.0
success open and validate gatsby-configs - 0.124s
success load plugins - 0.611s
success onPreInit - 0.027s
success initialize cache - 0.006s
success copy gatsby files - 0.107s
success onPreBootstrap - 0.019s
success createSchemaCustomization - 0.005s
success Checking for changed pages - 0.002s
success source and transform nodes - 0.061s
success building schema - 0.202s
info Total nodes: 37, SitePage nodes: 1 (use --verbose for breakdown)
success createPages - 0.007s
success Checking for changed pages - 0.000s
success createPagesStatefully - 0.056s
success update schema - 0.017s
success write out redirect data - 0.001s
success Build manifest and related icons - 0.444s
success onPostBootstrap - 0.447s
info bootstrap finished - 4.414s
success onPreExtractQueries - 0.001s
success extract queries from components - 0.300s
success write out requires - 0.004s
success run page queries - 0.015s - 1/1 65.70/s
warn Browserslist: caniuse-lite is outdated. Please run:
  npx update-browserslist-db@latest
  Why you should do it regularly: https://github.com/browserslist/update-db#readme

 ERROR #98124  WEBPACK

Generating development JavaScript bundle failed

Can't resolve '@capsizecss/metrics/abrilFatface' in '/Users/bytedance/github/capsize/site/src/components'

If you're trying to use a package make sure that '@capsizecss/metrics/abrilFatface' is installed. If you're trying to use a
local file make sure that the path is correct.

File: src/components/SiteProvider.tsx


 ERROR #98124  WEBPACK

Generating development JavaScript bundle failed

Can't resolve '@capsizecss/metrics/roboto' in '/Users/bytedance/github/capsize/site/src/components'

If you're trying to use a package make sure that '@capsizecss/metrics/roboto' is installed. If you're trying to use a local
file make sure that the path is correct.

File: src/components/SiteProvider.tsx


 ERROR #98124  WEBPACK

Generating development JavaScript bundle failed

Can't resolve '@capsizecss/metrics/roboto' in '/Users/bytedance/github/capsize/site/src/components'

If you're trying to use a package make sure that '@capsizecss/metrics/roboto' is installed. If you're trying to use a local
file make sure that the path is correct.

File: src/components/AppStateContext.tsx

failed Building development bundle - 7.842s

Different rendering on windows

Some fonts define a different ascent and descent value for windows.

Here is, for example, how capsize shows Tajawal's metrics on Windows vs. Mac:

Mac Windows
CleanShot 2021-08-22 at 21 20 55@2x CleanShot 2021-08-22 at 21 21 54@2x

I've run a script against all google fonts, and around 30% have different ascent or descent values for windows than for other operating systems.

To align fonts with their cap size reliably across operating systems, we have to take the Win Ascent and Descent numbers into account and use them instead of the "normal" HHead metrics on Windows systems.

This is not really an issue with capsize itself because capsize doesn't care where the user gets their font metrics from. If they provide the Windows metrics in browsers on Windows and the other metrics in all other operating systems, it works fine. It's just that probably a lot of people aren't aware of this.

Maybe we can add this to the FAQ section on the website? Additionally, we could extend the automatic font metrics detection logic on the site to use the windows metrics when being viewed on Windows. (The fontkit library only seems to provide the HHead numbers. I've had success with opentype.js to extract also the Win numbers.)

I'm happy to help on this if wanted/needed 🙋‍♂️.

@capsizecss/unpack fontkit module import error

I'm getting an error when trying to import unpack. Tested using a fresh vite deployment

main.ts
`import './style.css'
import { fromFile } from '@capsizecss/unpack';
import font from './font.woff2';

const metrics = await fromFile(font);
console.log('font metrics', metrics)`

package.json
{ "name": "capsize", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "tsc && vite build", "preview": "vite preview" }, "devDependencies": { "typescript": "^5.2.2", "vite": "^5.1.0" }, "dependencies": { "@capsizecss/unpack": "^1.0.0" } }

Error
` VITE v5.1.1 ready in 194 ms

➜ Local: http://localhost:5173/
➜ Network: use --host to expose
➜ press h + enter to show help
X [ERROR] No matching export in "node_modules/fontkit/dist/browser-module.mjs" for import "default"

node_modules/@capsizecss/unpack/dist/capsizecss-unpack.browser.esm.js:3:7:
  3 │ import fontkit from 'fontkit';`

PS - Awesome project! I ended up using the GH site to upload fonts & then lift the metrics from there & they worked absolutely perfectly.

Return numeric values in precomputeValues

Hello again 😊 I've been using Capsize recently with REM units and ThreeJS which relies on World units and was wondering if you'd be interested in simplifying precomputeValues to numeric values to better serve these use cases? This would be a breaking change so totally understand if you'd rather not change the API this much, but I think something along the lines of this would help:

const values = precomputeValues({ fontMetrics, capHeight: 2, lineGap: 1 })
const textStyles = {
  fontSize: `${values.fontSize}rem`,
  lineHeight: `${values.lineHeight}rem`,
  marginTop: `${values.capHeightTrim}rem`,
  marginBottom: `${values.baselineTrim}rem`
}

So you'd get numeric values back that are more flexible to work with and instead of using em units for the trim values, I propose multiplying the value by the font size so it can be used with libraries like ThreeJS where relative values don't exist.

Right now I simply parse and round the incoming values myself which is working well:

export const roundValue = (value) => {
  return Math.round(parseFloat(value) * 10000) / 10000
}

export function createTextStyles({
  capHeight,
  lineGap,
}: {
  capHeight: number
  lineGap: number
}) {
  const values = precomputeValues({ fontMetrics, capHeight, lineGap })
  return {
    fontSize: roundValue(values.fontSize),
    lineHeight: roundValue(values.lineHeight),
    leadingTrim: roundValue(lineGap / 2),
  }
}

Happy to work on a PR for this if it sounds like something you'd want to add 🙂

`text-indent` not applied to Capsize elements

This probably falls into the same bucket as the "overflow/truncation" gotchas detailed in the FAQs. I was aware of the some of these layout-related constraints, but this caught me off guard today. Feels like something text-related that should've been fair game.

Screenshot 2022-02-22 at 11 56 41

Like with truncation, this can be worked around by ensuring that the Capsize is applied to parent element and text-indent applied to its own separate child element.

Could be helpful to document?

x height for accessibility

This looks promising.

I'd like to mention that x-height is the single most critical font metric for readability, especially for blocks of body text.

Associated with contrast, we are working on standards/guidelines using x-height as the defining or reference size metric.

I thought it might be useful to mention this early on.

Thank you!

Andy

What License is the repository using?

Hi,

I was just about to fork this repository but noticed that there is no license defined and did not want to violate anyone's rights. Under what license is the code distributed?

Influence of font-weight seems not addressed

While it looks like results of capsize computations are legit for normal font-wight, it looks like font weight affects character proportions in special way, which means that we have to compute values for each font-weight.
Screenshot 2021-06-08 at 12 38 08

From this perspective, option of optical computation on canvas may again become attractive.

Feature Request: Output responsive arrays

First of all, thanks for the library. 😀

I'm using Capsize in a Theme UI (https://theme-ui.com/home) project with responsive styles.

Rather than using Capsize generated CSS-in-JS for each breakpoint in separate media queries, I'd prefer to use the "responsive array" format supported by Theme UI and Styled System (https://styled-system.com/css#responsive-arrays) eg.

const styles = {
  // capHeight: 8, 10
  fontSize: ['12.698412698412698px', '15.873015873015873px'],
  lineHeight: ['16px', '20px'],
  padding: '0.05px 0',
  '::before': {
    content: "''",
    marginTop: ['-0.3029375em', '-0.3021499999999999em'],
    display: 'block',
    height: 0,
  },
  '::after': {
    content: "''",
    marginBottom: ['-0.33493750000000017em', '-0.33415000000000006em'],
    display: 'block',
    height: 0,
  },
}

Currently, I'm using a responsiveCapsize utility function to generate these:

type CapHeightWithLeading = {
  capHeight: number
  leading: number
}

function responsiveCapsize(
  fontMetrics: FontMetrics,
  capHeightsWithLeading: CapHeightWithLeading[]
) {
  const styles = capHeightsWithLeading.map((c) =>
    capsize({
      capHeight: c.capHeight,
      leading: c.leading,
      fontMetrics,
    })
  )

  return {
    fontSize: styles.map((s) => s.fontSize),
    lineHeight: styles.map((s) => s.lineHeight),
    padding: '0.05px 0',
    '::before': {
      content: "''",
      marginTop: styles.map((s) => s['::before'].marginTop),
      display: 'block',
      height: 0,
    },
    '::after': {
      content: "''",
      marginBottom: styles.map((s) => s['::after'].marginBottom),
      display: 'block',
      height: 0,
    },
  }
}

const styles = responsiveCapsize(fontMetrics, [
  { capHeight: 8, leading: 16 },
  { capHeight: 10, leading: 20 },
])

Would you consider adding similar functionality to the Capsize to generate CSS-in-JS output using responsive arrays?

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.