Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate utils to TypeScript #1055

Merged
merged 6 commits into from
Feb 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/light-ears-run.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@primer/components": patch
---

Migrate `utils` to TypeScript
1 change: 1 addition & 0 deletions @types/jest-styled-components/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
declare module 'jest-styled-components/serializer'
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ module.exports = {
cacheDirectory: '.test',
collectCoverage: true,
collectCoverageFrom: ['src/*.js'],
setupFilesAfterEnv: ['<rootDir>/src/utils/test-matchers.js', '<rootDir>/src/utils/test-deprecations.js']
setupFilesAfterEnv: ['<rootDir>/src/utils/test-matchers.tsx', '<rootDir>/src/utils/test-deprecations.tsx']
}
16 changes: 10 additions & 6 deletions src/utils/deprecate.js → src/utils/deprecate.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
/* eslint-disable no-console */
import {useRef, useCallback} from 'react'
declare var __DEV__: boolean
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a better place for this?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure. I think this is fine for now 👍


type DeprecationType = {name: string; message: string; version: string}

const noop = () => {}
// eslint-disable-next-line import/no-mutable-exports
let deprecate = null
let deprecate: ({name, message, version}: DeprecationType) => void | (() => void) = noop

if (__DEV__) {
deprecate = ({name, message, version}) => {
deprecate = ({name, message, version}: DeprecationType) => {
Deprecations.deprecate({name, message, version})
}
} else {
deprecate = noop
}

export {deprecate}
Expand All @@ -19,7 +20,7 @@ export {deprecate}
let useDeprecation = null

if (__DEV__) {
useDeprecation = ({name, message, version}) => {
useDeprecation = ({name, message, version}: DeprecationType) => {
const ref = useRef(false)
const logDeprecation = useCallback(() => {
if (!ref.current) {
Expand All @@ -39,6 +40,9 @@ if (__DEV__) {
export {useDeprecation}

export class Deprecations {
static instance: Deprecations | null = null
deprecations: Array<DeprecationType>

static get() {
if (!Deprecations.instance) {
Deprecations.instance = new Deprecations()
Expand All @@ -51,7 +55,7 @@ export class Deprecations {
this.deprecations = []
}

static deprecate({name, message, version}) {
static deprecate({name, message, version}: DeprecationType) {
const msg = `WARNING! ${name} is deprecated and will be removed in version ${version}. ${message}`
console.warn(msg)

Expand Down
2 changes: 1 addition & 1 deletion src/utils/isNumeric.js → src/utils/isNumeric.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export default function isNumeric(n) {
export default function isNumeric(n: any) {
return !isNaN(parseFloat(n)) && isFinite(n)
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import semver from 'semver'
import {Deprecations} from '../utils/deprecate'
import {Deprecations} from './deprecate'

const ourVersion = require('../../package.json').version

Expand Down
17 changes: 11 additions & 6 deletions src/utils/test-matchers.js → src/utils/test-matchers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import React from 'react'
import 'jest-styled-components'
import {styleSheetSerializer} from 'jest-styled-components/serializer'
import theme from '../theme'
import {ReactTestRendererJSON, ReactTestRendererNode} from 'react-test-renderer'
import {getClasses, mount, getComputedStyles, render} from './testing'
import {Nullish} from '@testing-library/react'

expect.addSnapshotSerializer(styleSheetSerializer)

const stringify = d => JSON.stringify(d, null, ' ')
const stringify = (d: object) => JSON.stringify(d, null, ' ')

/**
* These are props that styled-system aliases for backwards compatibility.
Expand Down Expand Up @@ -34,7 +36,9 @@ expect.extend({

toHaveClasses(node, klasses, only = false) {
const classes = getClasses(node)
const pass = only ? this.equals(classes.sort(), klasses.sort()) : klasses.every(klass => classes.includes(klass))
const pass = only
? this.equals(classes.sort(), klasses.sort())
: klasses.every((klass: Array<string>) => classes.includes(klass))
return {
pass,
message: () => `expected ${stringify(classes)} to include: ${stringify(klasses)}`
Expand Down Expand Up @@ -69,13 +73,14 @@ expect.extend({
const elem = React.cloneElement(element, {sx: sxPropValue})
const rendered = render(elem)

function checkStylesDeep(rendered) {
const className = rendered.props ? rendered.props.className : ''
function checkStylesDeep(rendered: ReactTestRendererJSON): boolean {
const className = rendered?.props ? rendered.props.className : ''
const styles = getComputedStyles(className)
if (styles[mediaKey] && styles[mediaKey].color) {
const mediaStyles = styles[mediaKey] as Nullish<Record<string, string>>
if (mediaStyles && mediaStyles.color) {
return true
} else if (rendered.children) {
return rendered.children.some(child => checkStylesDeep(child))
return rendered.children.some((child: ReactTestRendererNode) => checkStylesDeep(child as ReactTestRendererJSON))
} else {
return false
}
Expand Down
17 changes: 8 additions & 9 deletions src/utils/testing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export function renderClasses(component: React.ReactElement): string {
/**
* Returns true if a node renders with a single class.
*/
export function rendersClass(node: React.ReactElement, klass: string): boolean {
export function rendersClass(node: React.ReactElement, klass: string): boolean {
return renderClasses(node).includes(klass)
}

Expand All @@ -96,7 +96,7 @@ export function renderStyles(node: React.ReactElement): any {
return getComputedStyles(className)
}

export function getComputedStyles(className: string): Record<string, string> {
export function getComputedStyles(className: string): Record<string, string | Record<string, string>> {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This feels weird, but was required to make L80 of src/utils/test-matchers.tsx play nice. My understanding of Record<string, string> is that is types and object that maps strings to strings - but it seems that sometimes this will map strings to object groupings that are themselves Record<string, string>, as in the case of the media query key invoked on L80.

Though, I might be misunderstanding this 😅

const div = document.createElement('div')
div.className = className

Expand All @@ -107,14 +107,14 @@ export function getComputedStyles(className: string): Record<string, string> {
if (rule instanceof CSSMediaRule) {
readMedia(rule)
} else if (rule instanceof CSSStyleRule) {
readRule(rule, computed)
} else {
readRule(rule, computed)
} else {
// console.warn('rule.type =', rule.type)
}
}
}

return computed
return computed

function matchesSafe(node: HTMLDivElement, selector: string) {
if (!selector) {
Expand Down Expand Up @@ -194,16 +194,15 @@ export function unloadCSS(path: string) {
// to render without errors, you can pass a `toRender` function that
// returns an element ready to be rendered.


interface Options {
skipAs?: boolean
skipSx?: boolean
}

interface BehavesAsComponent {
Component: React.FunctionComponent<any>,
systemPropArray: any[],
toRender?: () => React.ReactElement,
Component: React.ComponentType<any>
systemPropArray: any[]
toRender?: () => React.ReactElement
options?: Options
}

Expand Down