From 1d6cde5877a8971f4f4c576513680c27111d201b Mon Sep 17 00:00:00 2001 From: Josh Goldberg Date: Sun, 23 May 2021 10:52:12 -0400 Subject: [PATCH 01/31] Removed Flow (and its tooling) from the source code (#2385) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Removed Flow * Update packages/jest/src/utils.js Co-authored-by: Mateusz Burzyński * Update packages/react/src/theming.js Co-authored-by: Mateusz Burzyński * Update site/src/utils/markdown-styles.js Co-authored-by: Mateusz Burzyński * Fix markdown-styles.js * Title.js * One more formatting, and a FlowFixMe removal * Updated a few snapshots, and yarn.lock Co-authored-by: Mateusz Burzyński --- .eslintignore | 3 +- .flowconfig | 24 - .flowconfig-ci | 27 - .github/workflows/main.yml | 31 - .prettierrc.yaml | 3 - __mocks__/react-native.js | 1 - __mocks__/react-primitives.js | 1 - docs/docs.yaml | 1 - docs/flow.mdx | 115 -- flow-typed/npm/gatsby_vx.x.x.js | 20 - flow-typed/npm/jest-glamor-react_vx.x.x.js | 24 - flow-typed/npm/jest_v25.x.x.js | 1206 ----------------- flow-typed/npm/react-test-renderer_vx.x.x.js | 43 - package.json | 11 +- .../__fixtures__/core-with-component.js | 1 - .../__fixtures__/function-declaration.js | 1 - .../__tests__/__fixtures__/object-property.js | 1 - .../__tests__/__snapshots__/index.js.snap | 18 +- .../babel-plugin/__tests__/css-macro/index.js | 1 - .../__tests__/css-requires-options.js | 1 - .../__tests__/global-macro/index.js | 1 - .../__tests__/global-requires-options.js | 1 - .../__tests__/styled-macro/index.js | 1 - .../__tests__/styled-requires-options.js | 1 - .../__tests__/vanilla-emotion-macro/index.js | 1 - packages/babel-plugin/src/core-macro.js | 77 +- packages/babel-plugin/src/emotion-macro.js | 13 +- packages/babel-plugin/src/index.js | 27 +- packages/babel-plugin/src/styled-macro.js | 39 +- packages/babel-plugin/src/utils/add-import.js | 8 +- .../src/utils/get-styled-options.js | 5 +- .../src/utils/get-target-class-name.js | 5 +- packages/babel-plugin/src/utils/index.js | 1 - packages/babel-plugin/src/utils/label.js | 17 +- packages/babel-plugin/src/utils/minify.js | 30 +- .../src/utils/object-to-string.js | 3 +- .../babel-plugin/src/utils/source-maps.js | 11 +- packages/babel-plugin/src/utils/strings.js | 9 +- .../utils/transform-expression-with-styles.js | 20 +- .../src/utils/transformer-macro.js | 7 +- .../src/utils/transpiled-output-utils.js | 6 +- packages/cache/__tests__/hydration.js | 1 - packages/cache/__tests__/index.js | 1 - packages/cache/src/index.js | 69 +- packages/cache/src/types.js | 20 +- packages/css/macro.js.flow | 2 - packages/css/package.json | 1 - packages/css/src/create-instance.js | 29 +- packages/css/src/index.js | 1 - packages/css/test/css.test.js | 1 - packages/css/test/cx.test.js | 1 - packages/css/test/inject-global.test.js | 1 - packages/css/test/instance/css.test.js | 1 - .../css/test/instance/emotion-instance.js | 2 - packages/css/test/instance/instance.test.js | 1 - packages/css/test/instance/stream.test.js | 1 - packages/css/test/keyframes.test.js | 1 - packages/css/test/no-babel/index.test.js | 3 +- packages/css/test/no-babel/warnings.test.js | 6 +- packages/css/test/selectivity.test.js | 1 - packages/css/test/sheet.dom.test.js | 1 - packages/css/test/warnings.test.js | 4 +- packages/eslint-plugin/src/index.js | 2 - packages/hash/src/index.js | 3 +- packages/is-prop-valid/src/index.js | 4 +- packages/is-prop-valid/src/props.js | 1 - packages/jest/src/create-enzyme-serializer.js | 19 +- packages/jest/src/create-serializer.js | 44 +- packages/jest/src/enzyme-serializer.js | 1 - packages/jest/src/enzyme.js | 1 - packages/jest/src/index.js | 1 - packages/jest/src/matchers.js | 9 +- packages/jest/src/replace-class-names.js | 13 +- packages/jest/src/serializer.js | 1 - packages/jest/src/utils.js | 77 +- packages/jest/test/printer.test.js | 1 - packages/memoize/src/index.js | 8 +- packages/native/test/native-css.test.js | 4 - packages/primitives-core/src/css.js | 23 +- packages/primitives-core/src/styled.js | 18 +- packages/primitives-core/src/utils.js | 4 +- packages/primitives/src/index.js | 1 - packages/primitives/src/styled.js | 7 +- packages/primitives/src/test-props.js | 5 +- packages/primitives/test/css.test.js | 5 - .../test/emotion-primitives.test.js | 20 +- .../primitives/test/no-babel/basic.test.js | 2 - packages/primitives/test/warnings.test.js | 2 - packages/react/__tests__/at-import.js | 6 +- .../__snapshots__/source-map-server.js.snap | 2 +- .../__tests__/babel/source-map-server.js | 2 +- packages/react/__tests__/class-names.js | 1 - packages/react/__tests__/clone-element.js | 1 - packages/react/__tests__/compat/browser.js | 1 - packages/react/__tests__/compat/server.js | 1 - packages/react/__tests__/css-cache-hash.js | 1 - packages/react/__tests__/css.js | 28 +- packages/react/__tests__/custom-cache.js | 1 - packages/react/__tests__/global-with-theme.js | 6 +- packages/react/__tests__/global.js | 5 - .../react/__tests__/globals-are-the-worst.js | 1 - packages/react/__tests__/import-prod.js | 1 - packages/react/__tests__/keyframes.js | 1 - packages/react/__tests__/legacy-class-name.js | 1 - packages/react/__tests__/ref.js | 1 - packages/react/__tests__/rehydration.js | 10 +- packages/react/__tests__/server.js | 2 +- .../react/__tests__/theme-provider.dom.js | 3 +- packages/react/__tests__/theme-provider.js | 2 - packages/react/__tests__/use-theme.js | 1 - packages/react/__tests__/warnings.js | 25 +- packages/react/__tests__/with-theme.js | 8 +- packages/react/macro.js.flow | 2 - packages/react/src/class-names.js | 107 +- packages/react/src/context.js | 24 +- packages/react/src/css.js | 6 +- packages/react/src/emotion-element.js | 14 +- packages/react/src/global.js | 234 ++-- packages/react/src/index.js | 3 +- packages/react/src/jsx-dev-runtime.js | 10 +- packages/react/src/jsx-runtime.js | 5 +- packages/react/src/jsx.js | 10 +- packages/react/src/keyframes.js | 6 +- packages/react/src/theming.js | 19 +- packages/react/src/utils.js | 1 - packages/serialize/src/index.js | 48 +- .../construct-style-tags-from-chunks.js | 13 +- .../extract-critical-to-chunks.js | 10 +- .../src/create-instance/extract-critical.js | 9 +- packages/server/src/create-instance/index.js | 5 +- packages/server/src/create-instance/inline.js | 13 +- packages/server/src/create-instance/stream.js | 8 +- packages/server/src/create-instance/utils.js | 10 +- packages/server/src/index.js | 1 - .../test/extract-critical-to-chunks.test.js | 7 +- packages/server/test/index.test.js | 3 +- packages/server/test/inline.test.js | 1 - packages/server/test/stream.test.js | 1 - packages/server/test/util.js | 64 +- packages/sheet/__tests__/index.js | 8 +- packages/sheet/src/index.js | 47 +- packages/styled/__tests__/as-prop.js | 1 - packages/styled/__tests__/edge-cases.js | 1 - packages/styled/__tests__/styled-dom.js | 1 - packages/styled/__tests__/styled.js | 2 - packages/styled/__tests__/warnings.js | 9 +- packages/styled/flow-tests/base.js | 21 - packages/styled/flow-tests/index.js | 20 - packages/styled/flow-tests/styled.js | 25 - packages/styled/macro.js.flow | 3 - packages/styled/package.json | 3 +- packages/styled/src/base.js | 27 +- packages/styled/src/index.js | 2 - packages/styled/src/tags.js | 1 - packages/styled/src/utils.js | 21 +- .../__snapshots__/source-map.test.js.snap | 2 +- packages/styled/test/babel-plugin.test.js | 1 - packages/styled/test/composition.test.js | 1 - packages/styled/test/index.test.js | 4 +- packages/styled/test/prop-filtering.test.js | 1 - packages/styled/test/source-map.test.js | 1 - packages/styled/test/theming.dom.test.js | 1 - packages/styled/test/theming.test.js | 1 - packages/unitless/src/index.js | 4 +- packages/utils/src/index.js | 15 +- packages/utils/src/types.js | 5 +- packages/weak-memoize/src/index.js | 9 +- playgrounds/cra/src/App.js | 1 - playgrounds/cra/src/index.js | 1 - playgrounds/razzle/src/App.js | 1 - playgrounds/razzle/src/Home.js | 3 +- playgrounds/razzle/src/client.js | 3 - playgrounds/razzle/src/index.js | 5 +- playgrounds/razzle/src/server.js | 2 - scripts/babel-preset-emotion-dev/package.json | 1 - scripts/babel-preset-emotion-dev/src/index.js | 1 - scripts/babel-tester/src/index.js | 12 +- scripts/benchmarks/.babelrc | 1 - scripts/benchmarks/run.js | 2 +- scripts/benchmarks/src/app/App.js | 2 +- scripts/benchmarks/src/app/Benchmark/index.js | 61 +- scripts/benchmarks/src/app/Benchmark/math.js | 1 - .../benchmarks/src/app/Benchmark/timing.js | 2 - scripts/benchmarks/src/app/Benchmark/types.js | 40 +- scripts/benchmarks/src/app/Button.js | 2 +- scripts/benchmarks/src/app/ReportCard.js | 4 +- scripts/benchmarks/src/impl.js | 18 +- .../emotion-css-prop/Provider.js | 1 - .../emotion-styled/Provider.js | 1 - scripts/benchmarks/src/index.js | 1 - scripts/ssr-benchmarks/bench.js | 1 - scripts/test-utils/enzyme-env.js | 1 - scripts/test-utils/legacy-env.js | 2 - scripts/test-utils/next-env.js | 2 - scripts/test-utils/src/index.js | 9 +- .../gatsby-browser.js | 1 - .../gatsby-ssr.js | 3 +- site/src/components/Box.js | 6 +- site/src/components/DocMetadata.js | 7 +- site/src/components/DocWrapper.js | 40 +- site/src/components/Link.js | 7 +- site/src/components/Playground.js | 8 +- site/src/components/Search.js | 7 +- site/src/components/SiteHeader.js | 1 - site/src/components/Title.js | 5 +- site/src/components/live/compile.js | 17 +- site/src/components/live/index.js | 27 +- site/src/components/live/types.js | 1 - site/src/layouts/index.js | 19 +- site/src/pages/404.js | 1 - site/src/pages/community.js | 3 +- site/src/templates/doc.js | 12 +- site/src/utils/algolia-styles.js | 1 - site/src/utils/async-load-search.js | 4 +- site/src/utils/markdown-styles.js | 26 +- site/src/utils/misc.js | 16 +- site/src/utils/style.js | 1 - site/src/utils/types.js | 22 +- test/pretty-css.js | 17 +- test/styleTransform.js | 1 - test/testSetup.js | 3 - yarn.lock | 39 +- 222 files changed, 927 insertions(+), 2771 deletions(-) delete mode 100644 .flowconfig delete mode 100644 .flowconfig-ci delete mode 100644 docs/flow.mdx delete mode 100644 flow-typed/npm/gatsby_vx.x.x.js delete mode 100644 flow-typed/npm/jest-glamor-react_vx.x.x.js delete mode 100644 flow-typed/npm/jest_v25.x.x.js delete mode 100644 flow-typed/npm/react-test-renderer_vx.x.x.js delete mode 100644 packages/css/macro.js.flow delete mode 100644 packages/react/macro.js.flow delete mode 100644 packages/styled/flow-tests/base.js delete mode 100644 packages/styled/flow-tests/index.js delete mode 100644 packages/styled/flow-tests/styled.js delete mode 100644 packages/styled/macro.js.flow diff --git a/.eslintignore b/.eslintignore index 2ad384975..3403b5396 100644 --- a/.eslintignore +++ b/.eslintignore @@ -4,5 +4,4 @@ coverage/ node_modules/ stylis.min.js /demo/dist -/packages/site/build -flow-typed/ \ No newline at end of file +/packages/site/build \ No newline at end of file diff --git a/.flowconfig b/.flowconfig deleted file mode 100644 index a4493837b..000000000 --- a/.flowconfig +++ /dev/null @@ -1,24 +0,0 @@ -[version] -0.128.0 - -[ignore] -.*/node_modules/config-chain/.* -.*/node_modules/styled-components/.* -.*/node_modules/graphql/.* -.*/node_modules/metro.* -.*/node_modules/preact/.* -.*/node_modules/@parcel/.* - -[untyped] -.*/node_modules/polished/.* - - -[include] - -[libs] - -[declarations] -.*/node_modules/react-native/.* - -[options] -sharedmemory.hash_table_pow=21 diff --git a/.flowconfig-ci b/.flowconfig-ci deleted file mode 100644 index 97256ad2e..000000000 --- a/.flowconfig-ci +++ /dev/null @@ -1,27 +0,0 @@ -[version] -0.128.0 - -[ignore] -.*/node_modules/config-chain/.* -.*/node_modules/styled-components/.* -.*/node_modules/graphql/.* -.*/node_modules/metro.* -.*/node_modules/preact/.* -.*/node_modules/@parcel/.* - - -[untyped] -.*/node_modules/polished/.* - - -[include] - -[libs] - -[declarations] -.*/node_modules/react-native/.* - - -[options] -server.max_workers=1 -sharedmemory.hash_table_pow=21 diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index b9f70f65b..eaaea7979 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -50,37 +50,6 @@ jobs: uses: codecov/codecov-action@v1 if: ${{ matrix.platform == 'ubuntu-latest' && always() }} - flow: - name: Flow - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@main - - - name: Set Node.js 12.x - uses: actions/setup-node@main - with: - node-version: 12.x - - - name: Get yarn cache directory path - id: yarn-cache-dir-path - run: echo "::set-output name=dir::$(yarn cache dir)" - - - uses: actions/cache@v2 - id: yarn-cache - with: - path: | - ${{ steps.yarn-cache-dir-path.outputs.dir }} - node_modules - key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }} - restore-keys: | - ${{ runner.os }}-yarn- - - - name: Install Dependencies - run: yarn - - - name: Check Types - run: yarn flow:check - test_dist: name: Test Dist runs-on: ubuntu-latest diff --git a/.prettierrc.yaml b/.prettierrc.yaml index afa0c8ad2..c00fa2d41 100644 --- a/.prettierrc.yaml +++ b/.prettierrc.yaml @@ -4,6 +4,3 @@ overrides: - files: "docs/*.md" options: printWidth: 60 -- files: "*.js" - options: - parser: flow diff --git a/__mocks__/react-native.js b/__mocks__/react-native.js index 662671020..6a8703720 100644 --- a/__mocks__/react-native.js +++ b/__mocks__/react-native.js @@ -1,4 +1,3 @@ -// @flow /* eslint-env jest */ let components = [ diff --git a/__mocks__/react-primitives.js b/__mocks__/react-primitives.js index 83501e477..80ff2af8b 100644 --- a/__mocks__/react-primitives.js +++ b/__mocks__/react-primitives.js @@ -1,2 +1 @@ -// @flow export * from 'react-primitives/lib/index.web' diff --git a/docs/docs.yaml b/docs/docs.yaml index b105ffae6..6506eb7c6 100644 --- a/docs/docs.yaml +++ b/docs/docs.yaml @@ -29,7 +29,6 @@ - source-maps - testing - typescript - - flow # This loads the READMEs instead of files in docs/ - title: Packages diff --git a/docs/flow.mdx b/docs/flow.mdx deleted file mode 100644 index 60ccc5579..000000000 --- a/docs/flow.mdx +++ /dev/null @@ -1,115 +0,0 @@ ---- -title: 'Flow' ---- - -Emotion is built with Flow, so it exports type definitions for most of its packages, -including `@emotion/styled`. - -## @emotion/styled - -The styled package can be used to define styled components in two ways, by calling `styled()`, -or by using the `styled.*` shortcuts. - -Unfortunately, Flow doesn't currently support generic types on tagged templates, this means if -you'd like to explictly type a styled component props, you will have to use one of the following -alternatives: - -```jsx -import styled from '@emotion/styled' - -// Option A -const A = styled('div')` - color: red; -` - -// Option B -const B = styled.div({ - color: 'red', -}) -``` - -Styled components are annotated the same way normal React components are: - -```jsx -import styled from '@emotion/styled' - -type Props = { a: string } -const Link = styled('a')` - color: red; -` - -const App = () => Click me -``` - -Just like for normal React components, you don't need to provide type annotations -for your styled components if you don't plan to export them from your module: - -```jsx -import styled from '@emotion/styled' - -const Internal = styled.div` - color: red; -` -``` - -Be aware, Flow infers the return type of your components by referencing their return type, -this means you will need to annotate the properties of the root component in the case below: - -```jsx - -const Container = styled.div` - ^^^^^^^^^^^ Missing type annotation for P. P is a type parameter declared in function type [1] and was implicitly instantiated at -encaps tag [2]. - color: red; -` - -export const App = () => -``` - -You can use `React$ElementConfig` to obtain the props type of a HTML tag, or of -any existing React component: - -```jsx -import type { ElementConfig } from 'react' - -type Props = ElementConfig<'div'> -const Container = styled('div')` - color: red; -` - -export const App = () => -``` - - -```jsx -import type { ElementConfig } from 'react' -import styled from '@emotion/styled' - -const Container = styled>('div')` - background-color: yellow; -` - -const App = () => ( - {() => 10} - ^^^^^^^^^^ Cannot create Container element because in property children: - • Either inexact function [1] is incompatible with exact React.Element [2]. - • Or function [1] is incompatible with React.Portal [3]. - • Or property @@iterator is missing in function [1] but exists in $Iterable [4]. -) -``` - -Alternatively, you can define the return type of your component, so that -Flow doesn't need to infer it reading the props type of the internal component: - -```jsx -import type { Node } from 'react' - -const Container = styled.div` - color: red; -` - -export const App = (): Node => -``` - - - diff --git a/flow-typed/npm/gatsby_vx.x.x.js b/flow-typed/npm/gatsby_vx.x.x.js deleted file mode 100644 index 776c5a980..000000000 --- a/flow-typed/npm/gatsby_vx.x.x.js +++ /dev/null @@ -1,20 +0,0 @@ -// flow-typed signature: 47a1ce76579bcf60e33bc03fcf5c8762 -// flow-typed version: <>/gatsby_v^1.9.100/flow_v0.59.0 - -/** - * This is an autogenerated libdef stub for: - * - * 'gatsby' - * - * Fill this stub out by replacing all the `any` types. - * - * Once filled out, we encourage you to share your work with the - * community by sending a pull request to: - * https://github.com/flowtype/flow-typed - */ - -declare module 'gatsby' { - declare module.exports: any -} -// eslint-disable-next-line no-unused-vars -declare var graphql: Function diff --git a/flow-typed/npm/jest-glamor-react_vx.x.x.js b/flow-typed/npm/jest-glamor-react_vx.x.x.js deleted file mode 100644 index e792873ef..000000000 --- a/flow-typed/npm/jest-glamor-react_vx.x.x.js +++ /dev/null @@ -1,24 +0,0 @@ -// flow-typed signature: 22afe792d07ce86b99954c5d2a83c46e -// flow-typed version: <>/jest-glamor-react_v^3.1.1/flow_v0.59.0 - -/** - * This is an autogenerated libdef stub for: - * - * 'jest-glamor-react' - * - * Fill this stub out by replacing all the `any` types. - * - * Once filled out, we encourage you to share your work with the - * community by sending a pull request to: - * https://github.com/flowtype/flow-typed - */ - -import type {JestSnapshotSerializer} from 'jest' - - -interface GlamorStyleSheet { - tags: Array; -} -declare module 'jest-glamor-react' { - declare module.exports: JestSnapshotSerializer & (sheet: GlamorStyleSheet) => JestSnapshotSerializer -} diff --git a/flow-typed/npm/jest_v25.x.x.js b/flow-typed/npm/jest_v25.x.x.js deleted file mode 100644 index 84fb20228..000000000 --- a/flow-typed/npm/jest_v25.x.x.js +++ /dev/null @@ -1,1206 +0,0 @@ -// flow-typed signature: a0fbdb22ab391eceafc1d5643528e257 -// flow-typed version: dd2428a21d/jest_v25.x.x/flow_>=v0.104.x - -type JestMockFn, TReturn> = { - (...args: TArguments): TReturn, - /** - * An object for introspecting mock calls - */ - mock: { - /** - * An array that represents all calls that have been made into this mock - * function. Each call is represented by an array of arguments that were - * passed during the call. - */ - calls: Array, - /** - * An array that contains all the object instances that have been - * instantiated from this mock function. - */ - instances: Array, - /** - * An array that contains all the object results that have been - * returned by this mock function call - */ - results: Array<{ - isThrow: boolean, - value: TReturn, - ... - }>, - ... - }, - /** - * Resets all information stored in the mockFn.mock.calls and - * mockFn.mock.instances arrays. Often this is useful when you want to clean - * up a mock's usage data between two assertions. - */ - mockClear(): void, - /** - * Resets all information stored in the mock. This is useful when you want to - * completely restore a mock back to its initial state. - */ - mockReset(): void, - /** - * Removes the mock and restores the initial implementation. This is useful - * when you want to mock functions in certain test cases and restore the - * original implementation in others. Beware that mockFn.mockRestore only - * works when mock was created with jest.spyOn. Thus you have to take care of - * restoration yourself when manually assigning jest.fn(). - */ - mockRestore(): void, - /** - * Accepts a function that should be used as the implementation of the mock. - * The mock itself will still record all calls that go into and instances - * that come from itself -- the only difference is that the implementation - * will also be executed when the mock is called. - */ - mockImplementation( - fn: (...args: TArguments) => TReturn - ): JestMockFn, - /** - * Accepts a function that will be used as an implementation of the mock for - * one call to the mocked function. Can be chained so that multiple function - * calls produce different results. - */ - mockImplementationOnce( - fn: (...args: TArguments) => TReturn - ): JestMockFn, - /** - * Accepts a string to use in test result output in place of "jest.fn()" to - * indicate which mock function is being referenced. - */ - mockName(name: string): JestMockFn, - /** - * Just a simple sugar function for returning `this` - */ - mockReturnThis(): void, - /** - * Accepts a value that will be returned whenever the mock function is called. - */ - mockReturnValue(value: TReturn): JestMockFn, - /** - * Sugar for only returning a value once inside your mock - */ - mockReturnValueOnce(value: TReturn): JestMockFn, - /** - * Sugar for jest.fn().mockImplementation(() => Promise.resolve(value)) - */ - mockResolvedValue(value: TReturn): JestMockFn>, - /** - * Sugar for jest.fn().mockImplementationOnce(() => Promise.resolve(value)) - */ - mockResolvedValueOnce( - value: TReturn - ): JestMockFn>, - /** - * Sugar for jest.fn().mockImplementation(() => Promise.reject(value)) - */ - mockRejectedValue(value: TReturn): JestMockFn>, - /** - * Sugar for jest.fn().mockImplementationOnce(() => Promise.reject(value)) - */ - mockRejectedValueOnce(value: TReturn): JestMockFn>, - ... -}; - -type JestAsymmetricEqualityType = { /** - * A custom Jasmine equality tester - */ -asymmetricMatch(value: mixed): boolean, ... }; - -type JestCallsType = { - allArgs(): mixed, - all(): mixed, - any(): boolean, - count(): number, - first(): mixed, - mostRecent(): mixed, - reset(): void, - ... -}; - -type JestClockType = { - install(): void, - mockDate(date: Date): void, - tick(milliseconds?: number): void, - uninstall(): void, - ... -}; - -type JestMatcherResult = { - message?: string | (() => string), - pass: boolean, - ... -}; - -type JestMatcher = ( - received: any, - ...actual: Array -) => JestMatcherResult | Promise; - -type JestPromiseType = { - /** - * Use rejects to unwrap the reason of a rejected promise so any other - * matcher can be chained. If the promise is fulfilled the assertion fails. - */ - rejects: JestExpectType, - /** - * Use resolves to unwrap the value of a fulfilled promise so any other - * matcher can be chained. If the promise is rejected the assertion fails. - */ - resolves: JestExpectType, - ... -}; - -/** - * Jest allows functions and classes to be used as test names in test() and - * describe() - */ -type JestTestName = string | Function; - -/** - * Plugin: jest-styled-components - */ - -type JestStyledComponentsMatcherValue = - | string - | JestAsymmetricEqualityType - | RegExp - | typeof undefined; - -type JestStyledComponentsMatcherOptions = { - media?: string, - modifier?: string, - supports?: string, - ... -}; - -type JestStyledComponentsMatchersType = { toHaveStyleRule( - property: string, - value: JestStyledComponentsMatcherValue, - options?: JestStyledComponentsMatcherOptions -): void, ... }; - -/** - * Plugin: jest-enzyme - */ -type EnzymeMatchersType = { - // 5.x - toBeEmpty(): void, - toBePresent(): void, - // 6.x - toBeChecked(): void, - toBeDisabled(): void, - toBeEmptyRender(): void, - toContainMatchingElement(selector: string): void, - toContainMatchingElements(n: number, selector: string): void, - toContainExactlyOneMatchingElement(selector: string): void, - toContainReact(element: React$Element): void, - toExist(): void, - toHaveClassName(className: string): void, - toHaveHTML(html: string): void, - toHaveProp: ((propKey: string, propValue?: any) => void) & - ((props: {...}) => void), - toHaveRef(refName: string): void, - toHaveState: ((stateKey: string, stateValue?: any) => void) & - ((state: {...}) => void), - toHaveStyle: ((styleKey: string, styleValue?: any) => void) & - ((style: {...}) => void), - toHaveTagName(tagName: string): void, - toHaveText(text: string): void, - toHaveValue(value: any): void, - toIncludeText(text: string): void, - toMatchElement( - element: React$Element, - options?: {| ignoreProps?: boolean, verbose?: boolean |} - ): void, - toMatchSelector(selector: string): void, - // 7.x - toHaveDisplayName(name: string): void, - ... -}; - -// DOM testing library extensions (jest-dom) -// https://github.com/testing-library/jest-dom -type DomTestingLibraryType = { - /** - * @deprecated - */ - toBeInTheDOM(container?: HTMLElement): void, - toBeInTheDocument(): void, - toBeVisible(): void, - toBeEmpty(): void, - toBeDisabled(): void, - toBeEnabled(): void, - toBeInvalid(): void, - toBeRequired(): void, - toBeValid(): void, - toContainElement(element: HTMLElement | null): void, - toContainHTML(htmlText: string): void, - toHaveAttribute(attr: string, value?: any): void, - toHaveClass(...classNames: string[]): void, - toHaveFocus(): void, - toHaveFormValues(expectedValues: { [name: string]: any, ... }): void, - toHaveStyle(css: string): void, - toHaveTextContent( - text: string | RegExp, - options?: { normalizeWhitespace: boolean, ... } - ): void, - toHaveValue(value?: string | string[] | number): void, - ... -}; - -// Jest JQuery Matchers: https://github.com/unindented/custom-jquery-matchers -type JestJQueryMatchersType = { - toExist(): void, - toHaveLength(len: number): void, - toHaveId(id: string): void, - toHaveClass(className: string): void, - toHaveTag(tag: string): void, - toHaveAttr(key: string, val?: any): void, - toHaveProp(key: string, val?: any): void, - toHaveText(text: string | RegExp): void, - toHaveData(key: string, val?: any): void, - toHaveValue(val: any): void, - toHaveCss(css: { [key: string]: any, ... }): void, - toBeChecked(): void, - toBeDisabled(): void, - toBeEmpty(): void, - toBeHidden(): void, - toBeSelected(): void, - toBeVisible(): void, - toBeFocused(): void, - toBeInDom(): void, - toBeMatchedBy(sel: string): void, - toHaveDescendant(sel: string): void, - toHaveDescendantWithText(sel: string, text: string | RegExp): void, - ... -}; - -// Jest Extended Matchers: https://github.com/jest-community/jest-extended -type JestExtendedMatchersType = { - /** - * Note: Currently unimplemented - * Passing assertion - * - * @param {String} message - */ - // pass(message: string): void; - - /** - * Note: Currently unimplemented - * Failing assertion - * - * @param {String} message - */ - // fail(message: string): void; - - /** - * Use .toBeEmpty when checking if a String '', Array [] or Object {} is empty. - */ - toBeEmpty(): void, - /** - * Use .toBeOneOf when checking if a value is a member of a given Array. - * @param {Array.<*>} members - */ - toBeOneOf(members: any[]): void, - /** - * Use `.toBeNil` when checking a value is `null` or `undefined`. - */ - toBeNil(): void, - /** - * Use `.toSatisfy` when you want to use a custom matcher by supplying a predicate function that returns a `Boolean`. - * @param {Function} predicate - */ - toSatisfy(predicate: (n: any) => boolean): void, - /** - * Use `.toBeArray` when checking if a value is an `Array`. - */ - toBeArray(): void, - /** - * Use `.toBeArrayOfSize` when checking if a value is an `Array` of size x. - * @param {Number} x - */ - toBeArrayOfSize(x: number): void, - /** - * Use `.toIncludeAllMembers` when checking if an `Array` contains all of the same members of a given set. - * @param {Array.<*>} members - */ - toIncludeAllMembers(members: any[]): void, - /** - * Use `.toIncludeAnyMembers` when checking if an `Array` contains any of the members of a given set. - * @param {Array.<*>} members - */ - toIncludeAnyMembers(members: any[]): void, - /** - * Use `.toSatisfyAll` when you want to use a custom matcher by supplying a predicate function that returns a `Boolean` for all values in an array. - * @param {Function} predicate - */ - toSatisfyAll(predicate: (n: any) => boolean): void, - /** - * Use `.toBeBoolean` when checking if a value is a `Boolean`. - */ - toBeBoolean(): void, - /** - * Use `.toBeTrue` when checking a value is equal (===) to `true`. - */ - toBeTrue(): void, - /** - * Use `.toBeFalse` when checking a value is equal (===) to `false`. - */ - toBeFalse(): void, - /** - * Use .toBeDate when checking if a value is a Date. - */ - toBeDate(): void, - /** - * Use `.toBeFunction` when checking if a value is a `Function`. - */ - toBeFunction(): void, - /** - * Use `.toHaveBeenCalledBefore` when checking if a `Mock` was called before another `Mock`. - * - * Note: Required Jest version >22 - * Note: Your mock functions will have to be asynchronous to cause the timestamps inside of Jest to occur in a differentJS event loop, otherwise the mock timestamps will all be the same - * - * @param {Mock} mock - */ - toHaveBeenCalledBefore(mock: JestMockFn): void, - /** - * Use `.toBeNumber` when checking if a value is a `Number`. - */ - toBeNumber(): void, - /** - * Use `.toBeNaN` when checking a value is `NaN`. - */ - toBeNaN(): void, - /** - * Use `.toBeFinite` when checking if a value is a `Number`, not `NaN` or `Infinity`. - */ - toBeFinite(): void, - /** - * Use `.toBePositive` when checking if a value is a positive `Number`. - */ - toBePositive(): void, - /** - * Use `.toBeNegative` when checking if a value is a negative `Number`. - */ - toBeNegative(): void, - /** - * Use `.toBeEven` when checking if a value is an even `Number`. - */ - toBeEven(): void, - /** - * Use `.toBeOdd` when checking if a value is an odd `Number`. - */ - toBeOdd(): void, - /** - * Use `.toBeWithin` when checking if a number is in between the given bounds of: start (inclusive) and end (exclusive). - * - * @param {Number} start - * @param {Number} end - */ - toBeWithin(start: number, end: number): void, - /** - * Use `.toBeObject` when checking if a value is an `Object`. - */ - toBeObject(): void, - /** - * Use `.toContainKey` when checking if an object contains the provided key. - * - * @param {String} key - */ - toContainKey(key: string): void, - /** - * Use `.toContainKeys` when checking if an object has all of the provided keys. - * - * @param {Array.} keys - */ - toContainKeys(keys: string[]): void, - /** - * Use `.toContainAllKeys` when checking if an object only contains all of the provided keys. - * - * @param {Array.} keys - */ - toContainAllKeys(keys: string[]): void, - /** - * Use `.toContainAnyKeys` when checking if an object contains at least one of the provided keys. - * - * @param {Array.} keys - */ - toContainAnyKeys(keys: string[]): void, - /** - * Use `.toContainValue` when checking if an object contains the provided value. - * - * @param {*} value - */ - toContainValue(value: any): void, - /** - * Use `.toContainValues` when checking if an object contains all of the provided values. - * - * @param {Array.<*>} values - */ - toContainValues(values: any[]): void, - /** - * Use `.toContainAllValues` when checking if an object only contains all of the provided values. - * - * @param {Array.<*>} values - */ - toContainAllValues(values: any[]): void, - /** - * Use `.toContainAnyValues` when checking if an object contains at least one of the provided values. - * - * @param {Array.<*>} values - */ - toContainAnyValues(values: any[]): void, - /** - * Use `.toContainEntry` when checking if an object contains the provided entry. - * - * @param {Array.} entry - */ - toContainEntry(entry: [string, string]): void, - /** - * Use `.toContainEntries` when checking if an object contains all of the provided entries. - * - * @param {Array.>} entries - */ - toContainEntries(entries: [string, string][]): void, - /** - * Use `.toContainAllEntries` when checking if an object only contains all of the provided entries. - * - * @param {Array.>} entries - */ - toContainAllEntries(entries: [string, string][]): void, - /** - * Use `.toContainAnyEntries` when checking if an object contains at least one of the provided entries. - * - * @param {Array.>} entries - */ - toContainAnyEntries(entries: [string, string][]): void, - /** - * Use `.toBeExtensible` when checking if an object is extensible. - */ - toBeExtensible(): void, - /** - * Use `.toBeFrozen` when checking if an object is frozen. - */ - toBeFrozen(): void, - /** - * Use `.toBeSealed` when checking if an object is sealed. - */ - toBeSealed(): void, - /** - * Use `.toBeString` when checking if a value is a `String`. - */ - toBeString(): void, - /** - * Use `.toEqualCaseInsensitive` when checking if a string is equal (===) to another ignoring the casing of both strings. - * - * @param {String} string - */ - toEqualCaseInsensitive(string: string): void, - /** - * Use `.toStartWith` when checking if a `String` starts with a given `String` prefix. - * - * @param {String} prefix - */ - toStartWith(prefix: string): void, - /** - * Use `.toEndWith` when checking if a `String` ends with a given `String` suffix. - * - * @param {String} suffix - */ - toEndWith(suffix: string): void, - /** - * Use `.toInclude` when checking if a `String` includes the given `String` substring. - * - * @param {String} substring - */ - toInclude(substring: string): void, - /** - * Use `.toIncludeRepeated` when checking if a `String` includes the given `String` substring the correct number of times. - * - * @param {String} substring - * @param {Number} times - */ - toIncludeRepeated(substring: string, times: number): void, - /** - * Use `.toIncludeMultiple` when checking if a `String` includes all of the given substrings. - * - * @param {Array.} substring - */ - toIncludeMultiple(substring: string[]): void, - ... -}; - -// Diffing snapshot utility for Jest (snapshot-diff) -// https://github.com/jest-community/snapshot-diff -type SnapshotDiffType = { - /** - * Compare the difference between the actual in the `expect()` - * vs the object inside `valueB` with some extra options. - */ - toMatchDiffSnapshot( - valueB: any, - options?: {| - expand?: boolean; - colors?: boolean; - contextLines?: number; - stablePatchmarks?: boolean; - aAnnotation?: string; - bAnnotation?: string; - |}, - testName?: string - ): void, - ... -} - -interface JestExpectType { - not: JestExpectType & - EnzymeMatchersType & - DomTestingLibraryType & - JestJQueryMatchersType & - JestStyledComponentsMatchersType & - JestExtendedMatchersType & - SnapshotDiffType; - /** - * If you have a mock function, you can use .lastCalledWith to test what - * arguments it was last called with. - */ - lastCalledWith(...args: Array): void; - /** - * toBe just checks that a value is what you expect. It uses === to check - * strict equality. - */ - toBe(value: any): void; - /** - * Use .toBeCalledWith to ensure that a mock function was called with - * specific arguments. - */ - toBeCalledWith(...args: Array): void; - /** - * Using exact equality with floating point numbers is a bad idea. Rounding - * means that intuitive things fail. - */ - toBeCloseTo(num: number, delta: any): void; - /** - * Use .toBeDefined to check that a variable is not undefined. - */ - toBeDefined(): void; - /** - * Use .toBeFalsy when you don't care what a value is, you just want to - * ensure a value is false in a boolean context. - */ - toBeFalsy(): void; - /** - * To compare floating point numbers, you can use toBeGreaterThan. - */ - toBeGreaterThan(number: number): void; - /** - * To compare floating point numbers, you can use toBeGreaterThanOrEqual. - */ - toBeGreaterThanOrEqual(number: number): void; - /** - * To compare floating point numbers, you can use toBeLessThan. - */ - toBeLessThan(number: number): void; - /** - * To compare floating point numbers, you can use toBeLessThanOrEqual. - */ - toBeLessThanOrEqual(number: number): void; - /** - * Use .toBeInstanceOf(Class) to check that an object is an instance of a - * class. - */ - toBeInstanceOf(cls: Class<*>): void; - /** - * .toBeNull() is the same as .toBe(null) but the error messages are a bit - * nicer. - */ - toBeNull(): void; - /** - * Use .toBeTruthy when you don't care what a value is, you just want to - * ensure a value is true in a boolean context. - */ - toBeTruthy(): void; - /** - * Use .toBeUndefined to check that a variable is undefined. - */ - toBeUndefined(): void; - /** - * Use .toContain when you want to check that an item is in a list. For - * testing the items in the list, this uses ===, a strict equality check. - */ - toContain(item: any): void; - /** - * Use .toContainEqual when you want to check that an item is in a list. For - * testing the items in the list, this matcher recursively checks the - * equality of all fields, rather than checking for object identity. - */ - toContainEqual(item: any): void; - /** - * Use .toEqual when you want to check that two objects have the same value. - * This matcher recursively checks the equality of all fields, rather than - * checking for object identity. - */ - toEqual(value: any): void; - /** - * Use .toHaveBeenCalled to ensure that a mock function got called. - */ - toHaveBeenCalled(): void; - toBeCalled(): void; - /** - * Use .toHaveBeenCalledTimes to ensure that a mock function got called exact - * number of times. - */ - toHaveBeenCalledTimes(number: number): void; - toBeCalledTimes(number: number): void; - /** - * - */ - toHaveBeenNthCalledWith(nthCall: number, ...args: Array): void; - nthCalledWith(nthCall: number, ...args: Array): void; - /** - * - */ - toHaveReturned(): void; - toReturn(): void; - /** - * - */ - toHaveReturnedTimes(number: number): void; - toReturnTimes(number: number): void; - /** - * - */ - toHaveReturnedWith(value: any): void; - toReturnWith(value: any): void; - /** - * - */ - toHaveLastReturnedWith(value: any): void; - lastReturnedWith(value: any): void; - /** - * - */ - toHaveNthReturnedWith(nthCall: number, value: any): void; - nthReturnedWith(nthCall: number, value: any): void; - /** - * Use .toHaveBeenCalledWith to ensure that a mock function was called with - * specific arguments. - */ - toHaveBeenCalledWith(...args: Array): void; - toBeCalledWith(...args: Array): void; - /** - * Use .toHaveBeenLastCalledWith to ensure that a mock function was last called - * with specific arguments. - */ - toHaveBeenLastCalledWith(...args: Array): void; - lastCalledWith(...args: Array): void; - /** - * Check that an object has a .length property and it is set to a certain - * numeric value. - */ - toHaveLength(number: number): void; - /** - * - */ - toHaveProperty(propPath: string | $ReadOnlyArray, value?: any): void; - /** - * Use .toMatch to check that a string matches a regular expression or string. - */ - toMatch(regexpOrString: RegExp | string): void; - /** - * Use .toMatchObject to check that a javascript object matches a subset of the properties of an object. - */ - toMatchObject(object: Object | Array): void; - /** - * Use .toStrictEqual to check that a javascript object matches a subset of the properties of an object. - */ - toStrictEqual(value: any): void; - /** - * This ensures that an Object matches the most recent snapshot. - */ - toMatchSnapshot(propertyMatchers?: any, name?: string): void; - /** - * This ensures that an Object matches the most recent snapshot. - */ - toMatchSnapshot(name: string): void; - - toMatchInlineSnapshot(snapshot?: string): void; - toMatchInlineSnapshot(propertyMatchers?: any, snapshot?: string): void; - /** - * Use .toThrow to test that a function throws when it is called. - * If you want to test that a specific error gets thrown, you can provide an - * argument to toThrow. The argument can be a string for the error message, - * a class for the error, or a regex that should match the error. - * - * Alias: .toThrowError - */ - toThrow(message?: string | Error | Class | RegExp): void; - toThrowError(message?: string | Error | Class | RegExp): void; - /** - * Use .toThrowErrorMatchingSnapshot to test that a function throws a error - * matching the most recent snapshot when it is called. - */ - toThrowErrorMatchingSnapshot(): void; - toThrowErrorMatchingInlineSnapshot(snapshot?: string): void; -} - -type JestObjectType = { - /** - * Disables automatic mocking in the module loader. - * - * After this method is called, all `require()`s will return the real - * versions of each module (rather than a mocked version). - */ - disableAutomock(): JestObjectType, - /** - * An un-hoisted version of disableAutomock - */ - autoMockOff(): JestObjectType, - /** - * Enables automatic mocking in the module loader. - */ - enableAutomock(): JestObjectType, - /** - * An un-hoisted version of enableAutomock - */ - autoMockOn(): JestObjectType, - /** - * Clears the mock.calls and mock.instances properties of all mocks. - * Equivalent to calling .mockClear() on every mocked function. - */ - clearAllMocks(): JestObjectType, - /** - * Resets the state of all mocks. Equivalent to calling .mockReset() on every - * mocked function. - */ - resetAllMocks(): JestObjectType, - /** - * Restores all mocks back to their original value. - */ - restoreAllMocks(): JestObjectType, - /** - * Removes any pending timers from the timer system. - */ - clearAllTimers(): void, - /** - * Returns the number of fake timers still left to run. - */ - getTimerCount(): number, - /** - * The same as `mock` but not moved to the top of the expectation by - * babel-jest. - */ - doMock(moduleName: string, moduleFactory?: any): JestObjectType, - /** - * The same as `unmock` but not moved to the top of the expectation by - * babel-jest. - */ - dontMock(moduleName: string): JestObjectType, - /** - * Returns a new, unused mock function. Optionally takes a mock - * implementation. - */ - fn, TReturn>( - implementation?: (...args: TArguments) => TReturn - ): JestMockFn, - /** - * Determines if the given function is a mocked function. - */ - isMockFunction(fn: Function): boolean, - /** - * Given the name of a module, use the automatic mocking system to generate a - * mocked version of the module for you. - */ - genMockFromModule(moduleName: string): any, - /** - * Mocks a module with an auto-mocked version when it is being required. - * - * The second argument can be used to specify an explicit module factory that - * is being run instead of using Jest's automocking feature. - * - * The third argument can be used to create virtual mocks -- mocks of modules - * that don't exist anywhere in the system. - */ - mock( - moduleName: string, - moduleFactory?: any, - options?: Object - ): JestObjectType, - /** - * Returns the actual module instead of a mock, bypassing all checks on - * whether the module should receive a mock implementation or not. - */ - requireActual(moduleName: string): any, - /** - * Returns a mock module instead of the actual module, bypassing all checks - * on whether the module should be required normally or not. - */ - requireMock(moduleName: string): any, - /** - * Resets the module registry - the cache of all required modules. This is - * useful to isolate modules where local state might conflict between tests. - */ - resetModules(): JestObjectType, - /** - * Creates a sandbox registry for the modules that are loaded inside the - * callback function. This is useful to isolate specific modules for every - * test so that local module state doesn't conflict between tests. - */ - isolateModules(fn: () => void): JestObjectType, - /** - * Exhausts the micro-task queue (usually interfaced in node via - * process.nextTick). - */ - runAllTicks(): void, - /** - * Exhausts the macro-task queue (i.e., all tasks queued by setTimeout(), - * setInterval(), and setImmediate()). - */ - runAllTimers(): void, - /** - * Exhausts all tasks queued by setImmediate(). - */ - runAllImmediates(): void, - /** - * Executes only the macro task queue (i.e. all tasks queued by setTimeout() - * or setInterval() and setImmediate()). - */ - advanceTimersByTime(msToRun: number): void, - /** - * Executes only the macro task queue (i.e. all tasks queued by setTimeout() - * or setInterval() and setImmediate()). - * - * Renamed to `advanceTimersByTime`. - */ - runTimersToTime(msToRun: number): void, - /** - * Executes only the macro-tasks that are currently pending (i.e., only the - * tasks that have been queued by setTimeout() or setInterval() up to this - * point) - */ - runOnlyPendingTimers(): void, - /** - * Explicitly supplies the mock object that the module system should return - * for the specified module. Note: It is recommended to use jest.mock() - * instead. - */ - setMock(moduleName: string, moduleExports: any): JestObjectType, - /** - * Indicates that the module system should never return a mocked version of - * the specified module from require() (e.g. that it should always return the - * real module). - */ - unmock(moduleName: string): JestObjectType, - /** - * Instructs Jest to use fake versions of the standard timer functions - * (setTimeout, setInterval, clearTimeout, clearInterval, nextTick, - * setImmediate and clearImmediate). - */ - useFakeTimers(): JestObjectType, - /** - * Instructs Jest to use the real versions of the standard timer functions. - */ - useRealTimers(): JestObjectType, - /** - * Creates a mock function similar to jest.fn but also tracks calls to - * object[methodName]. - */ - spyOn( - object: Object, - methodName: string, - accessType?: 'get' | 'set' - ): JestMockFn, - /** - * Set the default timeout interval for tests and before/after hooks in milliseconds. - * Note: The default timeout interval is 5 seconds if this method is not called. - */ - setTimeout(timeout: number): JestObjectType, - ... -}; - -type JestSpyType = { calls: JestCallsType, ... }; - -type JestDoneFn = {| - (): void, - fail: (error: Error) => void, -|}; - -/** Runs this function after every test inside this context */ -declare function afterEach( - fn: (done: JestDoneFn) => ?Promise, - timeout?: number -): void; -/** Runs this function before every test inside this context */ -declare function beforeEach( - fn: (done: JestDoneFn) => ?Promise, - timeout?: number -): void; -/** Runs this function after all tests have finished inside this context */ -declare function afterAll( - fn: (done: JestDoneFn) => ?Promise, - timeout?: number -): void; -/** Runs this function before any tests have started inside this context */ -declare function beforeAll( - fn: (done: JestDoneFn) => ?Promise, - timeout?: number -): void; - -/** A context for grouping tests together */ -declare var describe: { - /** - * Creates a block that groups together several related tests in one "test suite" - */ - (name: JestTestName, fn: () => void): void, - /** - * Only run this describe block - */ - only(name: JestTestName, fn: () => void): void, - /** - * Skip running this describe block - */ - skip(name: JestTestName, fn: () => void): void, - /** - * each runs this test against array of argument arrays per each run - * - * @param {table} table of Test - */ - each( - ...table: Array | mixed> | [Array, string] - ): ( - name: JestTestName, - fn?: (...args: Array) => ?Promise, - timeout?: number - ) => void, - ... -}; - -/** An individual test unit */ -declare var it: { - /** - * An individual test unit - * - * @param {JestTestName} Name of Test - * @param {Function} Test - * @param {number} Timeout for the test, in milliseconds. - */ - ( - name: JestTestName, - fn?: (done: JestDoneFn) => ?Promise, - timeout?: number - ): void, - /** - * Only run this test - * - * @param {JestTestName} Name of Test - * @param {Function} Test - * @param {number} Timeout for the test, in milliseconds. - */ - only: {| - ( - name: JestTestName, - fn?: (done: JestDoneFn) => ?Promise, - timeout?: number - ): void, - each( - ...table: Array | mixed> | [Array, string] - ): ( - name: JestTestName, - fn?: (...args: Array) => ?Promise, - timeout?: number - ) => void - |}, - /** - * Skip running this test - * - * @param {JestTestName} Name of Test - * @param {Function} Test - * @param {number} Timeout for the test, in milliseconds. - */ - skip( - name: JestTestName, - fn?: (done: JestDoneFn) => ?Promise, - timeout?: number - ): void, - /** - * Highlight planned tests in the summary output - * - * @param {String} Name of Test to do - */ - todo(name: string): void, - /** - * Run the test concurrently - * - * @param {JestTestName} Name of Test - * @param {Function} Test - * @param {number} Timeout for the test, in milliseconds. - */ - concurrent( - name: JestTestName, - fn?: (done: JestDoneFn) => ?Promise, - timeout?: number - ): void, - /** - * each runs this test against array of argument arrays per each run - * - * @param {table} table of Test - */ - each( - ...table: Array | mixed> | [Array, string] - ): ( - name: JestTestName, - fn?: (...args: Array) => ?Promise, - timeout?: number - ) => void, - ... -}; - -declare function fit( - name: JestTestName, - fn: (done: JestDoneFn) => ?Promise, - timeout?: number -): void; -/** An individual test unit */ -declare var test: typeof it; -/** A disabled group of tests */ -declare var xdescribe: typeof describe; -/** A focused group of tests */ -declare var fdescribe: typeof describe; -/** A disabled individual test */ -declare var xit: typeof it; -/** A disabled individual test */ -declare var xtest: typeof it; - -type JestPrettyFormatColors = { - comment: { - close: string, - open: string, - ... - }, - content: { - close: string, - open: string, - ... - }, - prop: { - close: string, - open: string, - ... - }, - tag: { - close: string, - open: string, - ... - }, - value: { - close: string, - open: string, - ... - }, - ... -}; - -type JestPrettyFormatIndent = string => string; -type JestPrettyFormatRefs = Array; -type JestPrettyFormatPrint = any => string; -type JestPrettyFormatStringOrNull = string | null; - -type JestPrettyFormatOptions = {| - callToJSON: boolean, - edgeSpacing: string, - escapeRegex: boolean, - highlight: boolean, - indent: number, - maxDepth: number, - min: boolean, - plugins: JestPrettyFormatPlugins, - printFunctionName: boolean, - spacing: string, - theme: {| - comment: string, - content: string, - prop: string, - tag: string, - value: string, - |}, -|}; - -type JestPrettyFormatPlugin = { - print: ( - val: any, - serialize: JestPrettyFormatPrint, - indent: JestPrettyFormatIndent, - opts: JestPrettyFormatOptions, - colors: JestPrettyFormatColors - ) => string, - test: any => boolean, - ... -}; - -type JestPrettyFormatPlugins = Array; - -/** The expect function is used every time you want to test a value */ -declare var expect: { - /** The object that you want to make assertions against */ - ( - value: any - ): JestExpectType & - JestPromiseType & - EnzymeMatchersType & - DomTestingLibraryType & - JestJQueryMatchersType & - JestStyledComponentsMatchersType & - JestExtendedMatchersType & - SnapshotDiffType, - /** Add additional Jasmine matchers to Jest's roster */ - extend(matchers: { [name: string]: JestMatcher, ... }): void, - /** Add a module that formats application-specific data structures. */ - addSnapshotSerializer(pluginModule: JestPrettyFormatPlugin): void, - assertions(expectedAssertions: number): void, - hasAssertions(): void, - any(value: mixed): JestAsymmetricEqualityType, - anything(): any, - arrayContaining(value: Array): Array, - objectContaining(value: Object): Object, - /** Matches any received string that contains the exact expected string. */ - stringContaining(value: string): string, - stringMatching(value: string | RegExp): string, - not: { - arrayContaining: (value: $ReadOnlyArray) => Array, - objectContaining: (value: {...}) => Object, - stringContaining: (value: string) => string, - stringMatching: (value: string | RegExp) => string, - ... - }, - ... -}; - -// TODO handle return type -// http://jasmine.github.io/2.4/introduction.html#section-Spies -declare function spyOn(value: mixed, method: string): Object; - -/** Holds all functions related to manipulating test runner */ -declare var jest: JestObjectType; - -/** - * The global Jasmine object, this is generally not exposed as the public API, - * using features inside here could break in later versions of Jest. - */ -declare var jasmine: { - DEFAULT_TIMEOUT_INTERVAL: number, - any(value: mixed): JestAsymmetricEqualityType, - anything(): any, - arrayContaining(value: Array): Array, - clock(): JestClockType, - createSpy(name: string): JestSpyType, - createSpyObj( - baseName: string, - methodNames: Array - ): { [methodName: string]: JestSpyType, ... }, - objectContaining(value: Object): Object, - stringMatching(value: string): string, - ... -}; diff --git a/flow-typed/npm/react-test-renderer_vx.x.x.js b/flow-typed/npm/react-test-renderer_vx.x.x.js deleted file mode 100644 index 2f2d85c1f..000000000 --- a/flow-typed/npm/react-test-renderer_vx.x.x.js +++ /dev/null @@ -1,43 +0,0 @@ -// flow-typed signature: b39646fcd6b54764b610c38b101a4fdd -// flow-typed version: <>/react-test-renderer_v^16.0.0/flow_v0.59.0 - -/** - * This is an autogenerated libdef stub for: - * - * 'react-test-renderer' - * - * Fill this stub out by replacing all the `any` types. - * - * Once filled out, we encourage you to share your work with the - * community by sending a pull request to: - * https://github.com/flowtype/flow-typed - */ - -type TestRendererOptions = { - createNodeMock: (element: React$Element) => any -} - -type ReactTestRendererNode = ReactTestRendererJSON | string - -type ReactTestRendererJSON = {| - type: string, - props: { [propName: string]: any }, - children: null | Array, - $$typeof?: Symbol // Optional because we add it with defineProperty(). -|} - -declare module 'react-test-renderer' { - declare module.exports: { - create: ( - element: React$Element, - options?: TestRendererOptions - ) => { - toJSON: () => ReactTestRendererJSON, - update: (newElement: React$Element) => void, - unmount: () => void, - toTree: () => any, - getInstance: () => any, - root: any - } - } -} diff --git a/package.json b/package.json index 9760f282e..c76238872 100644 --- a/package.json +++ b/package.json @@ -18,8 +18,6 @@ "benchmark": "cd scripts/benchmarks && yarn benchmark", "start:site": "cd site && yarn start:site", "build:site": "cd site && yarn build:site", - "flow": "flow", - "flow:check": "flow check --flowconfig-name=.flowconfig-ci", "preinstall": "node ./scripts/ensure-yarn.js", "postinstall": "opencollective postinstall && preconstruct dev && manypkg check", "changeset": "changeset", @@ -58,7 +56,6 @@ ], "plugins": [ "prettier", - "flowtype", "@emotion" ], "parser": "babel-eslint", @@ -67,12 +64,11 @@ "no-template-curly-in-string": 0, "prefer-const": 0, "no-unused-vars": 0, - "flowtype/define-flow-type": 2, "import/no-duplicates": 0, "prettier/prettier": [ "error", { - "parser": "flow" + "parser": "typescript-eslint" } ], "react/jsx-curly-brace-presence": 0, @@ -181,10 +177,8 @@ "@babel/helper-module-imports": "^7.12.13", "@babel/plugin-proposal-class-properties": "^7.13.0", "@babel/plugin-syntax-jsx": "^7.12.13", - "@babel/plugin-transform-flow-strip-types": "^7.13.0", "@babel/plugin-transform-react-jsx": "^7.12.17", "@babel/preset-env": "^7.13.10", - "@babel/preset-flow": "^7.12.13", "@babel/preset-react": "^7.12.13", "@babel/register": "^7.13.8", "@babel/runtime": "^7.13.10", @@ -200,7 +194,6 @@ "@types/react": "^16.9.11", "babel-check-duplicated-nodes": "^1.0.0", "babel-eslint": "^10.1.0", - "babel-flow-types": "^1.2.3", "babel-jest": "^26.3.0", "babel-plugin-add-basic-constructor-for-react-components": "^0.1.0", "babel-plugin-codegen": "^3.0.0", @@ -222,7 +215,6 @@ "eslint-config-react": "^1.1.7", "eslint-config-standard": "^14.1.1", "eslint-config-standard-react": "^9.2.0", - "eslint-plugin-flowtype": "^5.2.0", "eslint-plugin-import": "^2.22.1", "eslint-plugin-node": "^11.1.0", "eslint-plugin-prettier": "^3.1.4", @@ -230,7 +222,6 @@ "eslint-plugin-react": "^7.21.3", "eslint-plugin-react-hooks": "^4.1.2", "eslint-plugin-standard": "^4.0.1", - "flow-bin": "^0.128.0", "html-tag-names": "^1.1.2", "husky": "^3.0.9", "jest": "^26.4.2", diff --git a/packages/babel-plugin/__tests__/__fixtures__/core-with-component.js b/packages/babel-plugin/__tests__/__fixtures__/core-with-component.js index 9985981ae..2dd040802 100644 --- a/packages/babel-plugin/__tests__/__fixtures__/core-with-component.js +++ b/packages/babel-plugin/__tests__/__fixtures__/core-with-component.js @@ -1,4 +1,3 @@ -// @flow import styled from '@emotion/styled' const MyComponent = styled.div({ color: 'hotpink' }) diff --git a/packages/babel-plugin/__tests__/__fixtures__/function-declaration.js b/packages/babel-plugin/__tests__/__fixtures__/function-declaration.js index b2f0327c2..8663c9c65 100644 --- a/packages/babel-plugin/__tests__/__fixtures__/function-declaration.js +++ b/packages/babel-plugin/__tests__/__fixtures__/function-declaration.js @@ -1,4 +1,3 @@ -// @flow import * as React from 'react' import { jsx } from '@emotion/react' diff --git a/packages/babel-plugin/__tests__/__fixtures__/object-property.js b/packages/babel-plugin/__tests__/__fixtures__/object-property.js index fa222c87f..c06dd8b67 100644 --- a/packages/babel-plugin/__tests__/__fixtures__/object-property.js +++ b/packages/babel-plugin/__tests__/__fixtures__/object-property.js @@ -1,4 +1,3 @@ -// @flow import * as React from 'react' import { jsx } from '@emotion/react' import styled from '@emotion/styled' diff --git a/packages/babel-plugin/__tests__/__snapshots__/index.js.snap b/packages/babel-plugin/__tests__/__snapshots__/index.js.snap index cc09cf62b..11226254f 100644 --- a/packages/babel-plugin/__tests__/__snapshots__/index.js.snap +++ b/packages/babel-plugin/__tests__/__snapshots__/index.js.snap @@ -56,8 +56,7 @@ const OtherComponent = () =>
;" `; exports[`@emotion/babel-plugin core-with-component 1`] = ` -"// @flow -import styled from '@emotion/styled' +"import styled from '@emotion/styled' const MyComponent = styled.div({ color: 'hotpink' }) @@ -70,7 +69,6 @@ import _styled from \\"@emotion/styled/base\\"; function _EMOTION_STRINGIFIED_CSS_ERROR__() { return \\"You have tried to stringify object returned from \`css\` function. It isn't supposed to be used directly (e.g. as value of the \`className\` prop), but rather handed to emotion so it can handle it (e.g. as value of \`css\` prop).\\"; } -// @flow const MyComponent = _styled(\\"div\\", process.env.NODE_ENV === \\"production\\" ? { target: \\"eck06en0\\" } : { @@ -82,7 +80,7 @@ const MyComponent = _styled(\\"div\\", process.env.NODE_ENV === \\"production\\" } : { name: \\"3sn2xs\\", styles: \\"color:hotpink\\", - map: \\"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImNvcmUtd2l0aC1jb21wb25lbnQuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBR29CIiwiZmlsZSI6ImNvcmUtd2l0aC1jb21wb25lbnQuanMiLCJzb3VyY2VzQ29udGVudCI6WyIvLyBAZmxvd1xuaW1wb3J0IHN0eWxlZCBmcm9tICdAZW1vdGlvbi9zdHlsZWQnXG5cbmNvbnN0IE15Q29tcG9uZW50ID0gc3R5bGVkLmRpdih7IGNvbG9yOiAnaG90cGluaycgfSlcblxuY29uc3QgT3RoZXJDb21wb25lbnQgPSBNeUNvbXBvbmVudC53aXRoQ29tcG9uZW50KCdzZWN0aW9uJylcbiJdfQ== */\\", + map: \\"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImNvcmUtd2l0aC1jb21wb25lbnQuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBRW9CIiwiZmlsZSI6ImNvcmUtd2l0aC1jb21wb25lbnQuanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgc3R5bGVkIGZyb20gJ0BlbW90aW9uL3N0eWxlZCdcblxuY29uc3QgTXlDb21wb25lbnQgPSBzdHlsZWQuZGl2KHsgY29sb3I6ICdob3RwaW5rJyB9KVxuXG5jb25zdCBPdGhlckNvbXBvbmVudCA9IE15Q29tcG9uZW50LndpdGhDb21wb25lbnQoJ3NlY3Rpb24nKVxuIl19 */\\", toString: _EMOTION_STRINGIFIED_CSS_ERROR__ }); @@ -220,8 +218,7 @@ const SomeComponent = props =>
;" `; exports[`@emotion/babel-plugin object-property 1`] = ` -"// @flow -import * as React from 'react' +"import * as React from 'react' import { jsx } from '@emotion/react' import styled from '@emotion/styled' @@ -323,7 +318,6 @@ import _styled from \\"@emotion/styled/base\\"; function _EMOTION_STRINGIFIED_CSS_ERROR__() { return \\"You have tried to stringify object returned from \`css\` function. It isn't supposed to be used directly (e.g. as value of the \`className\` prop), but rather handed to emotion so it can handle it (e.g. as value of \`css\` prop).\\"; } -// @flow import * as React from 'react'; import { jsx } from '@emotion/react'; const MyObject = { @@ -338,7 +332,7 @@ const MyObject = { } : { name: \\"3sn2xs\\", styles: \\"color:hotpink\\", - map: \\"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm9iamVjdC1wcm9wZXJ0eS5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFNYyIsImZpbGUiOiJvYmplY3QtcHJvcGVydHkuanMiLCJzb3VyY2VzQ29udGVudCI6WyIvLyBAZmxvd1xuaW1wb3J0ICogYXMgUmVhY3QgZnJvbSAncmVhY3QnXG5pbXBvcnQgeyBqc3ggfSBmcm9tICdAZW1vdGlvbi9yZWFjdCdcbmltcG9ydCBzdHlsZWQgZnJvbSAnQGVtb3Rpb24vc3R5bGVkJ1xuXG5jb25zdCBNeU9iamVjdCA9IHtcbiAgTXlQcm9wZXJ0eTogc3R5bGVkLmRpdih7IGNvbG9yOiAnaG90cGluaycgfSlcbn1cblxuZnVuY3Rpb24gTG9nbyhwcm9wcykge1xuICByZXR1cm4gPE15T2JqZWN0Lk15UHJvcGVydHkgLz5cbn1cbiJdfQ== */\\", + map: \\"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm9iamVjdC1wcm9wZXJ0eS5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFLYyIsImZpbGUiOiJvYmplY3QtcHJvcGVydHkuanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgKiBhcyBSZWFjdCBmcm9tICdyZWFjdCdcbmltcG9ydCB7IGpzeCB9IGZyb20gJ0BlbW90aW9uL3JlYWN0J1xuaW1wb3J0IHN0eWxlZCBmcm9tICdAZW1vdGlvbi9zdHlsZWQnXG5cbmNvbnN0IE15T2JqZWN0ID0ge1xuICBNeVByb3BlcnR5OiBzdHlsZWQuZGl2KHsgY29sb3I6ICdob3RwaW5rJyB9KVxufVxuXG5mdW5jdGlvbiBMb2dvKHByb3BzKSB7XG4gIHJldHVybiA8TXlPYmplY3QuTXlQcm9wZXJ0eSAvPlxufVxuIl19 */\\", toString: _EMOTION_STRINGIFIED_CSS_ERROR__ }) }; diff --git a/packages/babel-plugin/__tests__/css-macro/index.js b/packages/babel-plugin/__tests__/css-macro/index.js index fae1b1815..4d73fb4e8 100644 --- a/packages/babel-plugin/__tests__/css-macro/index.js +++ b/packages/babel-plugin/__tests__/css-macro/index.js @@ -1,4 +1,3 @@ -// @flow import babelTester from 'babel-tester' babelTester('@emotion/react - css macro', __dirname) diff --git a/packages/babel-plugin/__tests__/css-requires-options.js b/packages/babel-plugin/__tests__/css-requires-options.js index fd91b0c07..9173c489d 100644 --- a/packages/babel-plugin/__tests__/css-requires-options.js +++ b/packages/babel-plugin/__tests__/css-requires-options.js @@ -1,4 +1,3 @@ -// @flow import nodePath from 'path' import babelTester from 'babel-tester' import plugin from '@emotion/babel-plugin' diff --git a/packages/babel-plugin/__tests__/global-macro/index.js b/packages/babel-plugin/__tests__/global-macro/index.js index f2d206728..c3eb1874e 100644 --- a/packages/babel-plugin/__tests__/global-macro/index.js +++ b/packages/babel-plugin/__tests__/global-macro/index.js @@ -1,4 +1,3 @@ -// @flow import babelTester from 'babel-tester' babelTester('@emotion/react - Global macro', __dirname) diff --git a/packages/babel-plugin/__tests__/global-requires-options.js b/packages/babel-plugin/__tests__/global-requires-options.js index e8e7cf132..a8cd7cfad 100644 --- a/packages/babel-plugin/__tests__/global-requires-options.js +++ b/packages/babel-plugin/__tests__/global-requires-options.js @@ -1,4 +1,3 @@ -// @flow import babelTester from 'babel-tester' import plugin from '@emotion/babel-plugin' diff --git a/packages/babel-plugin/__tests__/styled-macro/index.js b/packages/babel-plugin/__tests__/styled-macro/index.js index f183501ef..26c27d241 100644 --- a/packages/babel-plugin/__tests__/styled-macro/index.js +++ b/packages/babel-plugin/__tests__/styled-macro/index.js @@ -1,4 +1,3 @@ -// @flow import babelTester from 'babel-tester' babelTester('@emotion/styled.macro', __dirname) diff --git a/packages/babel-plugin/__tests__/styled-requires-options.js b/packages/babel-plugin/__tests__/styled-requires-options.js index a2d1a57e2..05e003fb3 100644 --- a/packages/babel-plugin/__tests__/styled-requires-options.js +++ b/packages/babel-plugin/__tests__/styled-requires-options.js @@ -1,4 +1,3 @@ -// @flow import babelTester from 'babel-tester' import plugin from '@emotion/babel-plugin' diff --git a/packages/babel-plugin/__tests__/vanilla-emotion-macro/index.js b/packages/babel-plugin/__tests__/vanilla-emotion-macro/index.js index 07961ee8f..cdce44dff 100644 --- a/packages/babel-plugin/__tests__/vanilla-emotion-macro/index.js +++ b/packages/babel-plugin/__tests__/vanilla-emotion-macro/index.js @@ -1,4 +1,3 @@ -// @flow import babelTester from 'babel-tester' babelTester('vanilla emotion', __dirname) diff --git a/packages/babel-plugin/src/core-macro.js b/packages/babel-plugin/src/core-macro.js index 77f39f124..df12adec9 100644 --- a/packages/babel-plugin/src/core-macro.js +++ b/packages/babel-plugin/src/core-macro.js @@ -1,4 +1,3 @@ -// @flow import { transformExpressionWithStyles, createTransformerMacro, @@ -6,19 +5,21 @@ import { addImport } from './utils' -export const transformCssCallExpression = ({ - state, - babel, - path, - sourceMap, - annotateAsPure = true -}: { +export const transformCssCallExpression = ( + { + state, + babel, + path, + sourceMap, + annotateAsPure = true + } /*: { state: *, babel: *, path: *, sourceMap?: string, annotateAsPure?: boolean -}) => { +} */ +) => { let node = transformExpressionWithStyles({ babel, state, @@ -34,15 +35,13 @@ export const transformCssCallExpression = ({ } } -export const transformCsslessArrayExpression = ({ - state, - babel, - path -}: { +export const transformCsslessArrayExpression = ( + { state, babel, path } /*: { babel: *, state: *, path: * -}) => { +} */ +) => { let t = babel.types let expressionPath = path.get('value.expression') let sourceMap = @@ -72,17 +71,19 @@ export const transformCsslessArrayExpression = ({ } } -export const transformCsslessObjectExpression = ({ - state, - babel, - path, - cssImport -}: { +export const transformCsslessObjectExpression = ( + { + state, + babel, + path, + cssImport + } /*: { babel: *, state: *, path: *, cssImport: { importSource: string, cssExport: string } -}) => { +} */ +) => { let t = babel.types let expressionPath = path.get('value.expression') let sourceMap = @@ -115,31 +116,35 @@ export const transformCsslessObjectExpression = ({ } } -let cssTransformer = ({ - state, - babel, - reference -}: { +let cssTransformer = ( + { + state, + babel, + reference + } /*: { state: any, babel: any, reference: any -}) => { +} */ +) => { transformCssCallExpression({ babel, state, path: reference.parentPath }) } -let globalTransformer = ({ - state, - babel, - reference, - importSource, - options -}: { +let globalTransformer = ( + { + state, + babel, + reference, + importSource, + options + } /*: { state: any, babel: any, reference: any, importSource: string, options: { cssExport?: string } -}) => { +} */ +) => { const t = babel.types if ( diff --git a/packages/babel-plugin/src/emotion-macro.js b/packages/babel-plugin/src/emotion-macro.js index c35bb9552..17c1dd4df 100644 --- a/packages/babel-plugin/src/emotion-macro.js +++ b/packages/babel-plugin/src/emotion-macro.js @@ -1,4 +1,3 @@ -// @flow import { transformExpressionWithStyles, createTransformerMacro } from './utils' const isAlreadyTranspiled = path => { @@ -29,13 +28,9 @@ const isAlreadyTranspiled = path => { return ['name', 'styles'].every(p => properties.has(p)) } -let createEmotionTransformer = (isPure: boolean) => ({ - state, - babel, - importSource, - reference, - importSpecifierName -}: Object) => { +let createEmotionTransformer = (isPure /*: boolean */) => ( + { state, babel, importSource, reference, importSpecifierName } /*: Object */ +) => { const path = reference.parentPath if (isAlreadyTranspiled(path)) { @@ -63,5 +58,5 @@ export let transformers = { keyframes: createEmotionTransformer(true) } -export let createEmotionMacro = (importSource: string) => +export let createEmotionMacro = (importSource /*: string */) => createTransformerMacro(transformers, { importSource }) diff --git a/packages/babel-plugin/src/index.js b/packages/babel-plugin/src/index.js index 4c4388274..753048b88 100644 --- a/packages/babel-plugin/src/index.js +++ b/packages/babel-plugin/src/index.js @@ -1,4 +1,3 @@ -// @flow import syntaxJsx from '@babel/plugin-syntax-jsx' import { createEmotionMacro, @@ -69,13 +68,15 @@ export const macros = { vanillaEmotion: vanillaEmotionMacro } +/* export type BabelPath = any export type EmotionBabelPluginPass = any +*/ const AUTO_LABEL_VALUES = ['dev-only', 'never', 'always'] -export default function(babel: *, options: *) { +export default function(babel, options) { if ( options.autoLabel !== undefined && !AUTO_LABEL_VALUES.includes(options.autoLabel) @@ -92,7 +93,7 @@ export default function(babel: *, options: *) { name: '@emotion', inherits: syntaxJsx, visitor: { - ImportDeclaration(path: *, state: *) { + ImportDeclaration(path, state) { const macro = state.pluginMacros[path.node.source.value] // most of this is from https://github.com/kentcdodds/babel-plugin-macros/blob/main/src/index.js if (macro === undefined) { @@ -146,13 +147,13 @@ export default function(babel: *, options: *) { isBabelMacrosCall: true }) }, - Program(path: *, state: *) { + Program(path, state) { let macros = {} - let jsxReactImports: Array<{ + let jsxReactImports /*: Array<{ importSource: string, export: string, cssExport: string - }> = [ + }> */ = [ { importSource: '@emotion/react', export: 'jsx', cssExport: 'css' } ] state.jsxReactImport = jsxReactImports[0] @@ -196,11 +197,11 @@ export default function(babel: *, options: *) { } } - let [exportTransformer, defaultOptions] = - // $FlowFixMe - Array.isArray(packageTransformers[exportName]) - ? packageTransformers[exportName] - : [packageTransformers[exportName]] + let [exportTransformer, defaultOptions] = Array.isArray( + packageTransformers[exportName] + ) + ? packageTransformers[exportName] + : [packageTransformers[exportName]] transformers[localExportName] = [ exportTransformer, @@ -253,7 +254,7 @@ export default function(babel: *, options: *) { state.emotionSourceMap = true } }, - JSXAttribute(path: *, state: *) { + JSXAttribute(path, state) { if (path.node.name.name !== 'css' || !state.transformCssProp) { return } @@ -276,7 +277,7 @@ export default function(babel: *, options: *) { } }, CallExpression: { - exit(path: BabelPath, state: EmotionBabelPluginPass) { + exit(path /*: BabelPath */, state /*: EmotionBabelPluginPass */) { try { if ( path.node.callee && diff --git a/packages/babel-plugin/src/styled-macro.js b/packages/babel-plugin/src/styled-macro.js index aef7008dd..be14abf99 100644 --- a/packages/babel-plugin/src/styled-macro.js +++ b/packages/babel-plugin/src/styled-macro.js @@ -1,4 +1,3 @@ -// @flow import { transformExpressionWithStyles, getStyledOptions, @@ -13,15 +12,16 @@ const getReferencedSpecifier = (path, specifierName) => { : specifiers.find(p => p.node.local.name === specifierName) } -export let styledTransformer = ({ - state, - babel, - path, - importSource, - reference, - importSpecifierName, - options: { styledBaseImport, isWeb } -}: { +export let styledTransformer = ( + { + state, + babel, + path, + importSource, + reference, + importSpecifierName, + options: { styledBaseImport, isWeb } + } /*: { state: Object, babel: Object, path: any, @@ -29,7 +29,8 @@ export let styledTransformer = ({ importSpecifierName: string, reference: Object, options: { styledBaseImport?: [string, string], isWeb: boolean } -}) => { +} */ +) => { let t = babel.types let getStyledIdentifier = () => { @@ -121,17 +122,19 @@ export let styledTransformer = ({ } } -export let createStyledMacro = ({ - importSource, - originalImportSource = importSource, - baseImportName = 'default', - isWeb -}: { +export let createStyledMacro = ( + { + importSource, + originalImportSource = importSource, + baseImportName = 'default', + isWeb + } /*: { importSource: string, originalImportSource?: string, baseImportName?: string, isWeb: boolean -}) => +} */ +) => createTransformerMacro( { default: [ diff --git a/packages/babel-plugin/src/utils/add-import.js b/packages/babel-plugin/src/utils/add-import.js index 4d1113ac8..393ef1fb5 100644 --- a/packages/babel-plugin/src/utils/add-import.js +++ b/packages/babel-plugin/src/utils/add-import.js @@ -1,10 +1,10 @@ import { addDefault, addNamed } from '@babel/helper-module-imports' export function addImport( - state: any, - importSource: string, - importedSpecifier: string, - nameHint?: string + state, + importSource /*: string */, + importedSpecifier /*: string */, + nameHint /* ?: string */ ) { let cacheKey = ['import', importSource, importedSpecifier].join(':') if (state[cacheKey] === undefined) { diff --git a/packages/babel-plugin/src/utils/get-styled-options.js b/packages/babel-plugin/src/utils/get-styled-options.js index b37b027f2..351afad60 100644 --- a/packages/babel-plugin/src/utils/get-styled-options.js +++ b/packages/babel-plugin/src/utils/get-styled-options.js @@ -1,9 +1,8 @@ -// @flow import { getLabelFromPath } from './label' import { getTargetClassName } from './get-target-class-name' import createNodeEnvConditional from './create-node-env-conditional' -const getKnownProperties = (t: *, node: *) => +const getKnownProperties = (t, node) => new Set( node.properties .filter(n => t.isObjectProperty(n) && !n.computed) @@ -13,7 +12,7 @@ const getKnownProperties = (t: *, node: *) => const createObjectSpreadLike = (t, file, ...objs) => t.callExpression(file.addHelper('extends'), [t.objectExpression([]), ...objs]) -export let getStyledOptions = (t: *, path: *, state: *) => { +export let getStyledOptions = (t, path, state) => { const autoLabel = state.opts.autoLabel || 'dev-only' let args = path.node.arguments diff --git a/packages/babel-plugin/src/utils/get-target-class-name.js b/packages/babel-plugin/src/utils/get-target-class-name.js index 9b78a9725..5d524b920 100644 --- a/packages/babel-plugin/src/utils/get-target-class-name.js +++ b/packages/babel-plugin/src/utils/get-target-class-name.js @@ -1,11 +1,10 @@ -// @flow import findRoot from 'find-root' import memoize from '@emotion/memoize' import nodePath from 'path' import hashString from '@emotion/hash' import escapeRegexp from 'escape-string-regexp' -let hashArray = (arr: Array) => hashString(arr.join('')) +let hashArray = (arr /*: Array */) => hashString(arr.join('')) const unsafeRequire = require @@ -15,7 +14,7 @@ const separator = new RegExp(escapeRegexp(nodePath.sep), 'g') const normalizePath = path => nodePath.normalize(path).replace(separator, '/') -export function getTargetClassName(state: *, t: *) { +export function getTargetClassName(state, t) { if (state.emotionTargetClassNameCount === undefined) { state.emotionTargetClassNameCount = 0 } diff --git a/packages/babel-plugin/src/utils/index.js b/packages/babel-plugin/src/utils/index.js index 733b947dc..6b9248397 100644 --- a/packages/babel-plugin/src/utils/index.js +++ b/packages/babel-plugin/src/utils/index.js @@ -1,4 +1,3 @@ -// @flow export { getLabelFromPath } from './label' export { getSourceMap } from './source-maps' export { getTargetClassName } from './get-target-class-name' diff --git a/packages/babel-plugin/src/utils/label.js b/packages/babel-plugin/src/utils/label.js index 86602079c..18a1f7ea6 100644 --- a/packages/babel-plugin/src/utils/label.js +++ b/packages/babel-plugin/src/utils/label.js @@ -1,20 +1,21 @@ -// @flow import nodePath from 'path' +/* type LabelFormatOptions = { name: string, path: string } +*/ const invalidClassNameCharacters = /[!"#$%&'()*+,./:;<=>?@[\]^`|}~{]/g -const sanitizeLabelPart = (labelPart: string) => +const sanitizeLabelPart = (labelPart /*: string */) => labelPart.trim().replace(invalidClassNameCharacters, '-') function getLabel( - identifierName?: string, - labelFormat?: string | (LabelFormatOptions => string), - filename: string + identifierName /* ?: string */, + labelFormat /* ?: string | (LabelFormatOptions => string) */, + filename /*: string */ ) { if (!identifierName) return null @@ -45,7 +46,7 @@ function getLabel( .replace(/\[dirname\]/gi, sanitizeLabelPart(localDirname)) } -export function getLabelFromPath(path: *, state: *, t: *) { +export function getLabelFromPath(path, state, t) { return getLabel( getIdentifierName(path, t), state.opts.labelFormat, @@ -72,7 +73,6 @@ const getObjPropertyLikeName = (path, t) => { } function getDeclaratorName(path, t) { - // $FlowFixMe const parent = path.findParent( p => p.isVariableDeclarator() || @@ -143,14 +143,13 @@ function getDeclaratorName(path, t) { return variableDeclarator.node.id.name } -function getIdentifierName(path: *, t: *) { +function getIdentifierName(path, t) { let objPropertyLikeName = getObjPropertyLikeName(path.parentPath, t) if (objPropertyLikeName) { return objPropertyLikeName } - // $FlowFixMe let classOrClassPropertyParent = path.findParent( p => t.isClassProperty(p) || t.isClass(p) ) diff --git a/packages/babel-plugin/src/utils/minify.js b/packages/babel-plugin/src/utils/minify.js index f39d8437b..8a1733ea6 100644 --- a/packages/babel-plugin/src/utils/minify.js +++ b/packages/babel-plugin/src/utils/minify.js @@ -1,4 +1,3 @@ -// @flow import { compile } from 'stylis' const isAutoInsertedRule = element => { @@ -63,18 +62,17 @@ var stringifyTree = elements => { .join('') } -const interleave = (strings: Array<*>, interpolations: Array<*>) => +const interleave = (strings /*: Array<*> */, interpolations /*: Array<*> */) => interpolations.reduce( (array, interp, i) => array.concat([interp], strings[i + 1]), [strings[0]] ) -function getDynamicMatches(str: string) { +function getDynamicMatches(str /*: string */) { const re = /xxx(\d+):xxx/gm let match const matches = [] while ((match = re.exec(str)) !== null) { - // so that flow doesn't complain if (match !== null) { matches.push({ value: match[0], @@ -88,9 +86,9 @@ function getDynamicMatches(str: string) { } function replacePlaceholdersWithExpressions( - str: string, - expressions: Array<*>, - t: * + str /*: string */, + expressions /*: Array<*> */, + t ) { const matches = getDynamicMatches(str) if (matches.length === 0) { @@ -119,16 +117,18 @@ function replacePlaceholdersWithExpressions( } }) - return interleave(strings, finalExpressions).filter( - (node: { value: string }) => { - return node.value !== '' - } - ) + return interleave(strings, finalExpressions).filter(( + node /*: { value: string } */ + ) => { + return node.value !== '' + }) } -function createRawStringFromTemplateLiteral(quasi: { +function createRawStringFromTemplateLiteral( + quasi /*: { quasis: Array<{ value: { cooked: string } }> -}) { +} */ +) { let strs = quasi.quasis.map(x => x.value.cooked) const src = strs @@ -144,7 +144,7 @@ function createRawStringFromTemplateLiteral(quasi: { return src } -export default function minify(path: *, t: *): void { +export default function minify(path, t) { const quasi = path.node.quasi const raw = createRawStringFromTemplateLiteral(quasi) const minified = stringifyTree(toInputTree(compile(raw), [])) diff --git a/packages/babel-plugin/src/utils/object-to-string.js b/packages/babel-plugin/src/utils/object-to-string.js index a3bfa5646..f275c5b07 100644 --- a/packages/babel-plugin/src/utils/object-to-string.js +++ b/packages/babel-plugin/src/utils/object-to-string.js @@ -1,10 +1,9 @@ -// @flow import { serializeStyles } from '@emotion/serialize' // to anyone looking at this, this isn't intended to simplify every single case // it's meant to simplify the most common cases so i don't want to make it especially complex // also, this will be unnecessary when prepack is ready -export function simplifyObject(node: *, t: Object) { +export function simplifyObject(node, t /*: Object */) { let finalString = '' for (let i = 0; i < node.properties.length; i++) { let property = node.properties[i] diff --git a/packages/babel-plugin/src/utils/source-maps.js b/packages/babel-plugin/src/utils/source-maps.js index b499f33cc..e4926711b 100644 --- a/packages/babel-plugin/src/utils/source-maps.js +++ b/packages/babel-plugin/src/utils/source-maps.js @@ -1,4 +1,3 @@ -// @flow import { SourceMapGenerator } from 'source-map' import convert from 'convert-source-map' @@ -6,7 +5,7 @@ function getGeneratorOpts(file) { return file.opts.generatorOpts ? file.opts.generatorOpts : file.opts } -export function makeSourceMapGenerator(file: *) { +export function makeSourceMapGenerator(file) { const generatorOpts = getGeneratorOpts(file) const filename = generatorOpts.sourceFileName const generator = new SourceMapGenerator({ @@ -19,12 +18,12 @@ export function makeSourceMapGenerator(file: *) { } export function getSourceMap( - offset: { + offset /*: { line: number, column: number - }, - state: * -): string { + } */, + state +) /*: string */ { const generator = makeSourceMapGenerator(state.file) const generatorOpts = getGeneratorOpts(state.file) if ( diff --git a/packages/babel-plugin/src/utils/strings.js b/packages/babel-plugin/src/utils/strings.js index 6c91c6216..5e85223e9 100644 --- a/packages/babel-plugin/src/utils/strings.js +++ b/packages/babel-plugin/src/utils/strings.js @@ -1,13 +1,12 @@ -// @flow import { getTypeScriptMakeTemplateObjectPath, isTaggedTemplateTranspiledByBabel } from './transpiled-output-utils' export const appendStringReturningExpressionToArguments = ( - t: *, - path: *, - expression: * + t, + path, + expression ) => { let lastIndex = path.node.arguments.length - 1 let last = path.node.arguments[lastIndex] @@ -44,7 +43,7 @@ export const appendStringReturningExpressionToArguments = ( } } -export const joinStringLiterals = (expressions: Array<*>, t: *) => { +export const joinStringLiterals = (expressions /*: Array<*> */, t) => { return expressions.reduce((finalExpressions, currentExpression, i) => { if (!t.isStringLiteral(currentExpression)) { finalExpressions.push(currentExpression) diff --git a/packages/babel-plugin/src/utils/transform-expression-with-styles.js b/packages/babel-plugin/src/utils/transform-expression-with-styles.js index c47e7366e..f2dee87e1 100644 --- a/packages/babel-plugin/src/utils/transform-expression-with-styles.js +++ b/packages/babel-plugin/src/utils/transform-expression-with-styles.js @@ -1,5 +1,3 @@ -// @flow - import { serializeStyles } from '@emotion/serialize' import minify from './minify' import { getLabelFromPath } from './label' @@ -14,19 +12,21 @@ import createNodeEnvConditional from './create-node-env-conditional' const CSS_OBJECT_STRINGIFIED_ERROR = "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)." -export let transformExpressionWithStyles = ({ +export let transformExpressionWithStyles = ( + { + babel, + state, + path, + shouldLabel, + sourceMap = '' + } /*: { babel, state, path, - shouldLabel, - sourceMap = '' -}: { - babel: *, - state: *, - path: *, shouldLabel: boolean, sourceMap?: string -}): * => { +} */ +) => { const autoLabel = state.opts.autoLabel || 'dev-only' let t = babel.types if (t.isTaggedTemplateExpression(path)) { diff --git a/packages/babel-plugin/src/utils/transformer-macro.js b/packages/babel-plugin/src/utils/transformer-macro.js index ea1048969..679ad1af3 100644 --- a/packages/babel-plugin/src/utils/transformer-macro.js +++ b/packages/babel-plugin/src/utils/transformer-macro.js @@ -1,11 +1,12 @@ -// @flow import { createMacro } from 'babel-plugin-macros' +/* type Transformer = Function +*/ export function createTransformerMacro( - transformers: { [key: string]: Transformer | [Transformer, Object] }, - { importSource }: { importSource: string } + transformers /*: { [key: string]: Transformer | [Transformer, Object] } */, + { importSource } /*: { importSource: string } */ ) { let macro = createMacro( ({ path, source, references, state, babel, isEmotionCall }) => { diff --git a/packages/babel-plugin/src/utils/transpiled-output-utils.js b/packages/babel-plugin/src/utils/transpiled-output-utils.js index e6943e3b6..74187e413 100644 --- a/packages/babel-plugin/src/utils/transpiled-output-utils.js +++ b/packages/babel-plugin/src/utils/transpiled-output-utils.js @@ -1,8 +1,6 @@ -// @flow - // this only works correctly in modules, but we don't run on scripts anyway, so it's fine // the difference is that in modules template objects are being cached per call site -export function getTypeScriptMakeTemplateObjectPath(path: *) { +export function getTypeScriptMakeTemplateObjectPath(path) { if (path.node.arguments.length === 0) { return null } @@ -28,7 +26,7 @@ export function getTypeScriptMakeTemplateObjectPath(path: *) { // we could push them to found array expressions, as we do it for TS-transpile output ¯\_(ツ)_/¯ // it seems overly complicated though - mainly because we'd also have to check against existing stuff of a particular type (source maps & labels) // considering Babel double-transpilation as a valid use case seems rather far-fetched -export function isTaggedTemplateTranspiledByBabel(path: *) { +export function isTaggedTemplateTranspiledByBabel(path) { if (path.node.arguments.length === 0) { return false } diff --git a/packages/cache/__tests__/hydration.js b/packages/cache/__tests__/hydration.js index 132f26237..851e3ffb9 100644 --- a/packages/cache/__tests__/hydration.js +++ b/packages/cache/__tests__/hydration.js @@ -1,4 +1,3 @@ -// @flow import { safeQuerySelector } from 'test-utils' import hashString from '@emotion/hash' import createCache from '@emotion/cache' diff --git a/packages/cache/__tests__/index.js b/packages/cache/__tests__/index.js index 48ff19bef..890c6c66e 100644 --- a/packages/cache/__tests__/index.js +++ b/packages/cache/__tests__/index.js @@ -1,4 +1,3 @@ -// @flow import createCache from '@emotion/cache' test('throws correct error with invalid key', () => { diff --git a/packages/cache/src/index.js b/packages/cache/src/index.js index 741cce9f0..9723713f1 100644 --- a/packages/cache/src/index.js +++ b/packages/cache/src/index.js @@ -1,6 +1,5 @@ -// @flow import { StyleSheet } from '@emotion/sheet' -import { type EmotionCache, type SerializedStyles } from '@emotion/utils' +/* import { type EmotionCache, type SerializedStyles } from '@emotion/utils' */ import { serialize, compile, @@ -18,10 +17,11 @@ import { createUnsafeSelectorsAlarm, incorrectImportAlarm } from './stylis-plugins' -import type { StylisPlugin } from './types' +/* import type { StylisPlugin } from './types' */ let isBrowser = typeof document !== 'undefined' +/* export type Options = { nonce?: string, stylisPlugins?: StylisPlugin[], @@ -30,6 +30,7 @@ export type Options = { speedy?: boolean, prepend?: boolean } +*/ let getServerStylisCache = isBrowser ? undefined @@ -42,7 +43,7 @@ let getServerStylisCache = isBrowser const defaultStylisPlugins = [prefixer] -let createCache = (options: Options): EmotionCache => { +let createCache = (options /*: Options */) /*: EmotionCache */ => { let key = options.key if (process.env.NODE_ENV !== 'production' && !key) { @@ -61,21 +62,19 @@ let createCache = (options: Options): EmotionCache => { // document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be) // note this very very intentionally targets all style elements regardless of the key to ensure // that creating a cache works inside of render of a React component - Array.prototype.forEach.call(ssrStyles, (node: HTMLStyleElement) => { + Array.prototype.forEach.call(ssrStyles, (node /*: HTMLStyleElement */) => { // we want to only move elements which have a space in the data-emotion attribute value // because that indicates that it is an Emotion 11 server-side rendered style elements // while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector // Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes) // so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles // will not result in the Emotion 10 styles being destroyed - const dataEmotionAttribute = ((node.getAttribute( - 'data-emotion' - ): any): string) + const dataEmotionAttribute = node.getAttribute('data-emotion') if (dataEmotionAttribute.indexOf(' ') === -1) { return } - ;((document.head: any): HTMLHeadElement).appendChild(node) + document.head.appendChild(node) node.setAttribute('data-s', '') }) } @@ -83,7 +82,6 @@ let createCache = (options: Options): EmotionCache => { const stylisPlugins = options.stylisPlugins || defaultStylisPlugins if (process.env.NODE_ENV !== 'production') { - // $FlowFixMe if (/[^a-z-]/.test(key)) { throw new Error( `Emotion key must only contain lower case alphabetical characters and - but "${key}" was passed` @@ -91,21 +89,17 @@ let createCache = (options: Options): EmotionCache => { } } let inserted = {} - // $FlowFixMe - let container: HTMLElement + let container /*: HTMLElement */ const nodesToHydrate = [] if (isBrowser) { - container = options.container || ((document.head: any): HTMLHeadElement) + container = options.container || document.head Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which // means that the style elements we're looking at are only Emotion 11 server-rendered style elements document.querySelectorAll(`style[data-emotion^="${key} "]`), - (node: HTMLStyleElement) => { - const attrib = ((node.getAttribute(`data-emotion`): any): string).split( - ' ' - ) - // $FlowFixMe + (node /*: HTMLStyleElement */) => { + const attrib = node.getAttribute(`data-emotion`).split(' ') for (let i = 1; i < attrib.length; i++) { inserted[attrib[i]] = true } @@ -114,13 +108,12 @@ let createCache = (options: Options): EmotionCache => { ) } - let insert: ( + let insert /*: ( selector: string, serialized: SerializedStyles, sheet: StyleSheet, shouldCache: boolean - ) => string | void - + ) => string | void */ const omnipresentPlugins = [compat, removeLabel] if (process.env.NODE_ENV !== 'production') { @@ -162,19 +155,19 @@ let createCache = (options: Options): EmotionCache => { const stylis = styles => serialize(compile(styles), serializer) insert = ( - selector: string, - serialized: SerializedStyles, - sheet: StyleSheet, - shouldCache: boolean - ): void => { + selector /*: string */, + serialized /*: SerializedStyles */, + sheet /*: StyleSheet */, + shouldCache /*: boolean */ + ) /*: void */ => { currentSheet = sheet if ( process.env.NODE_ENV !== 'production' && serialized.map !== undefined ) { currentSheet = { - insert: (rule: string) => { - sheet.insert(rule + ((serialized.map: any): string)) + insert: (rule /*: string */) => { + sheet.insert(rule + serialized.map) } } } @@ -192,9 +185,11 @@ let createCache = (options: Options): EmotionCache => { ) const stylis = styles => serialize(compile(styles), serializer) - // $FlowFixMe let serverStylisCache = getServerStylisCache(stylisPlugins)(key) - let getRules = (selector: string, serialized: SerializedStyles): string => { + let getRules = ( + selector /*: string */, + serialized /*: SerializedStyles */ + ) /*: string */ => { let name = serialized.name if (serverStylisCache[name] === undefined) { serverStylisCache[name] = stylis( @@ -204,11 +199,11 @@ let createCache = (options: Options): EmotionCache => { return serverStylisCache[name] } insert = ( - selector: string, - serialized: SerializedStyles, - sheet: StyleSheet, - shouldCache: boolean - ): string | void => { + selector /*: string */, + serialized /*: SerializedStyles */, + sheet /*: StyleSheet */, + shouldCache /*: boolean */ + ) /*: string | void */ => { let name = serialized.name let rules = getRules(selector, serialized) if (cache.compat === undefined) { @@ -245,11 +240,11 @@ let createCache = (options: Options): EmotionCache => { } } - const cache: EmotionCache = { + const cache /*: EmotionCache */ = { key, sheet: new StyleSheet({ key, - container: ((container: any): HTMLElement), + container: container, nonce: options.nonce, speedy: options.speedy, prepend: options.prepend diff --git a/packages/cache/src/types.js b/packages/cache/src/types.js index 92312fb30..f02fb3341 100644 --- a/packages/cache/src/types.js +++ b/packages/cache/src/types.js @@ -1,14 +1,13 @@ -// @flow - +/* export type StylisElement = { - type: string, - value: string, - props: Array, - root: StylisElement | null, - children: Array, - line: number, - column: number, - length: number, + type: string + value: string + props: Array + root: StylisElement | null + children: Array + line: number + column: number + length: number return: string } export type StylisPluginCallback = ( @@ -24,3 +23,4 @@ export type StylisPlugin = ( children: Array, callback: StylisPluginCallback ) => string | void +*/ diff --git a/packages/css/macro.js.flow b/packages/css/macro.js.flow deleted file mode 100644 index 63ae97e66..000000000 --- a/packages/css/macro.js.flow +++ /dev/null @@ -1,2 +0,0 @@ -// @flow -export * from './src/index.js' diff --git a/packages/css/package.json b/packages/css/package.json index b5ba665d9..9b571f3e1 100644 --- a/packages/css/package.json +++ b/packages/css/package.json @@ -11,7 +11,6 @@ "types", "macro.js", "macro.d.ts", - "macro.js.flow", "create-instance" ], "scripts": { diff --git a/packages/css/src/create-instance.js b/packages/css/src/create-instance.js index 96c24ad7d..08bf7e59b 100644 --- a/packages/css/src/create-instance.js +++ b/packages/css/src/create-instance.js @@ -1,20 +1,23 @@ -// @flow import createCache from '@emotion/cache' import { serializeStyles } from '@emotion/serialize' import { insertStyles, - getRegisteredStyles, - type EmotionCache, - type SerializedStyles + getRegisteredStyles + /* type EmotionCache, */ + /* type SerializedStyles */ } from '@emotion/utils' -function insertWithoutScoping(cache, serialized: SerializedStyles) { +function insertWithoutScoping(cache, serialized /*: SerializedStyles */) { if (cache.inserted[serialized.name] === undefined) { return cache.insert('', serialized, cache.sheet, true) } } -function merge(registered: Object, css: (*) => string, className: string) { +function merge( + registered /*: Object */, + css /*: (*) => string */, + className /*: string */ +) { const registeredStyles = [] const rawClassName = getRegisteredStyles( registered, @@ -28,6 +31,7 @@ function merge(registered: Object, css: (*) => string, className: string) { return rawClassName + css(registeredStyles) } +/* export type Interpolation = any export type Interpolations = Array @@ -59,15 +63,15 @@ export type Emotion = { keyframes: CreateStyles, sheet: StyleSheet, cache: EmotionCache, - merge: *, - getRegisteredStyles: * + merge, + getRegisteredStyles } +*/ -let createEmotion = (options: *): Emotion => { +let createEmotion = (options) /*: Emotion */ => { let cache = createCache(options) - // $FlowFixMe - cache.sheet.speedy = function(value: boolean) { + cache.sheet.speedy = function(value /*: boolean */) { if (process.env.NODE_ENV !== 'production' && this.ctr !== 0) { throw new Error('speedy must be changed before any rules are inserted') } @@ -104,7 +108,7 @@ let createEmotion = (options: *): Emotion => { cx, injectGlobal, keyframes, - hydrate(ids: Array) { + hydrate(ids /*: Array */) { ids.forEach(key => { cache.inserted[key] = true }) @@ -114,7 +118,6 @@ let createEmotion = (options: *): Emotion => { cache.inserted = {} cache.sheet.flush() }, - // $FlowFixMe sheet: cache.sheet, cache, getRegisteredStyles: getRegisteredStyles.bind(null, cache.registered), diff --git a/packages/css/src/index.js b/packages/css/src/index.js index 523fed93e..9e4000e3d 100644 --- a/packages/css/src/index.js +++ b/packages/css/src/index.js @@ -1,4 +1,3 @@ -// @flow import createEmotion from './create-instance' export const { diff --git a/packages/css/test/css.test.js b/packages/css/test/css.test.js index b32630a6d..7b44dab7a 100644 --- a/packages/css/test/css.test.js +++ b/packages/css/test/css.test.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/legacy-env' import React from 'react' import renderer from 'react-test-renderer' diff --git a/packages/css/test/cx.test.js b/packages/css/test/cx.test.js index fc074cbba..30370209e 100644 --- a/packages/css/test/cx.test.js +++ b/packages/css/test/cx.test.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/legacy-env' import React from 'react' import renderer from 'react-test-renderer' diff --git a/packages/css/test/inject-global.test.js b/packages/css/test/inject-global.test.js index 44e9d0d66..44050042e 100644 --- a/packages/css/test/inject-global.test.js +++ b/packages/css/test/inject-global.test.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/legacy-env' import { injectGlobal, sheet, flush, css } from '@emotion/css' diff --git a/packages/css/test/instance/css.test.js b/packages/css/test/instance/css.test.js index 73685174d..67a2a02ea 100644 --- a/packages/css/test/instance/css.test.js +++ b/packages/css/test/instance/css.test.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/next-env' import React from 'react' import renderer from 'react-test-renderer' diff --git a/packages/css/test/instance/emotion-instance.js b/packages/css/test/instance/emotion-instance.js index 943d71287..59a4d1f8b 100644 --- a/packages/css/test/instance/emotion-instance.js +++ b/packages/css/test/instance/emotion-instance.js @@ -1,4 +1,3 @@ -// @flow import createEmotion from '@emotion/css/create-instance' import createEmotionServer from '@emotion/server/create-instance' @@ -12,7 +11,6 @@ export let container if (typeof document !== 'undefined') { container = document.createElement('div') - // $FlowFixMe document.head.appendChild(container) } diff --git a/packages/css/test/instance/instance.test.js b/packages/css/test/instance/instance.test.js index af9f5e668..b3ee02629 100644 --- a/packages/css/test/instance/instance.test.js +++ b/packages/css/test/instance/instance.test.js @@ -1,4 +1,3 @@ -// @flow import createEmotion from '@emotion/css/create-instance' import { container, css, sheet } from './emotion-instance' diff --git a/packages/css/test/instance/stream.test.js b/packages/css/test/instance/stream.test.js index 986abf5b0..1bee8277a 100644 --- a/packages/css/test/instance/stream.test.js +++ b/packages/css/test/instance/stream.test.js @@ -1,6 +1,5 @@ /** * @jest-environment node - * @flow */ import { JSDOM } from 'jsdom' diff --git a/packages/css/test/keyframes.test.js b/packages/css/test/keyframes.test.js index fc2a5b062..961568ca8 100644 --- a/packages/css/test/keyframes.test.js +++ b/packages/css/test/keyframes.test.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/legacy-env' import React from 'react' import renderer from 'react-test-renderer' diff --git a/packages/css/test/no-babel/index.test.js b/packages/css/test/no-babel/index.test.js index f56530e43..fd3412a38 100644 --- a/packages/css/test/no-babel/index.test.js +++ b/packages/css/test/no-babel/index.test.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/legacy-env' import React from 'react' import renderer from 'react-test-renderer' @@ -211,7 +210,7 @@ describe('css', () => { expect(tree).toMatchSnapshot() }) test('name with class component', () => { - class SomeComponent extends React.Component<{ className: string }> { + class SomeComponent extends React.Component /* <{ className: string }> */ { render() { return
} diff --git a/packages/css/test/no-babel/warnings.test.js b/packages/css/test/no-babel/warnings.test.js index 22df9d49a..564eabb3d 100644 --- a/packages/css/test/no-babel/warnings.test.js +++ b/packages/css/test/no-babel/warnings.test.js @@ -1,8 +1,6 @@ -// @flow import 'test-utils/legacy-env' import { css } from '@emotion/css' -// $FlowFixMe console.error = jest.fn() afterEach(() => { @@ -16,7 +14,7 @@ it('warns about illegal escape sequences inside first quasi of template literal' } ` - expect((console.error: any).mock.calls[0]).toMatchInlineSnapshot(` + expect(console.error.mock.calls[0]).toMatchInlineSnapshot(` Array [ "You have illegal escape sequence in your template literal, most likely inside content's property value. Because you write your CSS inside a JavaScript string you actually have to do double escaping, so for example \\"content: '\\\\00d7';\\" should become \\"content: '\\\\\\\\00d7';\\". @@ -36,7 +34,7 @@ it('warns about illegal escape sequences inside non-first quasi of template lite } ` - expect((console.error: any).mock.calls[0]).toMatchInlineSnapshot(` + expect(console.error.mock.calls[0]).toMatchInlineSnapshot(` Array [ "You have illegal escape sequence in your template literal, most likely inside content's property value. Because you write your CSS inside a JavaScript string you actually have to do double escaping, so for example \\"content: '\\\\00d7';\\" should become \\"content: '\\\\\\\\00d7';\\". diff --git a/packages/css/test/selectivity.test.js b/packages/css/test/selectivity.test.js index 18586f811..fe2d2d037 100644 --- a/packages/css/test/selectivity.test.js +++ b/packages/css/test/selectivity.test.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/legacy-env' import { css, sheet, flush } from '@emotion/css' diff --git a/packages/css/test/sheet.dom.test.js b/packages/css/test/sheet.dom.test.js index 98c75a680..740fd4a42 100644 --- a/packages/css/test/sheet.dom.test.js +++ b/packages/css/test/sheet.dom.test.js @@ -1,4 +1,3 @@ -// @flow import { sheet } from '@emotion/css' describe('sheet', () => { diff --git a/packages/css/test/warnings.test.js b/packages/css/test/warnings.test.js index b8403c2e3..8baa36382 100644 --- a/packages/css/test/warnings.test.js +++ b/packages/css/test/warnings.test.js @@ -1,11 +1,9 @@ -// @flow import 'test-utils/legacy-env' import { css } from '@emotion/css' import createCss from '@emotion/css/create-instance' import * as React from 'react' import renderer from 'react-test-renderer' -// $FlowFixMe console.error = jest.fn() const validValues = [ @@ -66,7 +64,7 @@ it('does warn when @import rule is being inserted after order-insensitive rules' injectGlobal`.thing {display:flex;}` injectGlobal`@import 'custom.css';` - expect((console.error: any).mock.calls).toMatchInlineSnapshot(` + expect(console.error.mock.calls).toMatchInlineSnapshot(` Array [ Array [ "You're attempting to insert the following rule: diff --git a/packages/eslint-plugin/src/index.js b/packages/eslint-plugin/src/index.js index e626a190c..b9f503616 100644 --- a/packages/eslint-plugin/src/index.js +++ b/packages/eslint-plugin/src/index.js @@ -1,5 +1,3 @@ -// @flow - import importFromEmotion from './rules/import-from-emotion' import noVanilla from './rules/no-vanilla' import syntaxPreference from './rules/syntax-preference' diff --git a/packages/hash/src/index.js b/packages/hash/src/index.js index dacf52f90..0e6b4422a 100644 --- a/packages/hash/src/index.js +++ b/packages/hash/src/index.js @@ -1,9 +1,8 @@ -// @flow /* eslint-disable */ // Inspired by https://github.com/garycourt/murmurhash-js // Ported from https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L37-L86 -export default function murmur2(str: string) { +export default function murmur2(str /*: string */) { // 'm' and 'r' are mixing constants generated offline. // They're not really 'magic', they just happen to work well. diff --git a/packages/is-prop-valid/src/index.js b/packages/is-prop-valid/src/index.js index 12b5424de..d40911675 100644 --- a/packages/is-prop-valid/src/index.js +++ b/packages/is-prop-valid/src/index.js @@ -1,8 +1,10 @@ -// @flow import memoize from '@emotion/memoize' +/* declare var codegen: { require: string => RegExp } +*/ +// eslint-disable-next-line no-undef const reactPropsRegex = codegen.require('./props') // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23 diff --git a/packages/is-prop-valid/src/props.js b/packages/is-prop-valid/src/props.js index 1bff7dd6b..3880a8b21 100644 --- a/packages/is-prop-valid/src/props.js +++ b/packages/is-prop-valid/src/props.js @@ -1,4 +1,3 @@ -// @flow const props = { // react props // https://github.com/facebook/react/blob/5495a7f24aef85ba6937truetrue1ce962673ca9f5fde6/src/renderers/dom/shared/hooks/ReactDOMUnknownPropertyHook.js diff --git a/packages/jest/src/create-enzyme-serializer.js b/packages/jest/src/create-enzyme-serializer.js index 9208b49b3..94d21772f 100644 --- a/packages/jest/src/create-enzyme-serializer.js +++ b/packages/jest/src/create-enzyme-serializer.js @@ -1,5 +1,4 @@ -// @flow -import type { Options } from './create-serializer' +/* import type { Options } from './create-serializer' */ import { createSerializer as createEmotionSerializer } from './create-serializer' import * as enzymeTickler from './enzyme-tickler' import { createSerializer as createEnzymeToJsonSerializer } from 'enzyme-to-json' @@ -9,22 +8,22 @@ const enzymeSerializer = createEnzymeToJsonSerializer({}) export function createEnzymeSerializer({ classNameReplacer, DOMElements = true -}: Options = {}) { +} /*: Options */ = {}) { const emotionSerializer = createEmotionSerializer({ classNameReplacer, DOMElements }) return { - test(node: *) { + test(node) { return enzymeSerializer.test(node) || emotionSerializer.test(node) }, serialize( - node: *, - config: *, - indentation: string, - depth: number, - refs: *, - printer: Function + node, + config, + indentation /*: string */, + depth /*: number */, + refs, + printer /*: Function */ ) { if (enzymeSerializer.test(node)) { const tickled = enzymeTickler.tickle(node) diff --git a/packages/jest/src/create-serializer.js b/packages/jest/src/create-serializer.js index 506bb7cae..f12c1bc85 100644 --- a/packages/jest/src/create-serializer.js +++ b/packages/jest/src/create-serializer.js @@ -1,4 +1,3 @@ -// @flow import prettify from '@emotion/css-prettifier' import { replaceClassNames } from './replace-class-names' import * as enzymeTickler from './enzyme-tickler' @@ -49,13 +48,13 @@ function deepTransform(node, transform) { return node.map(child => deepTransform(child, transform)) } - const transformed: any = transform(node) + const transformed = transform(node) if (transformed !== node && transformed.children) { return copyProps(transformed, { // flatMap to allow a child of to be transformed to children: flatMap( - (deepTransform(transformed.children, transform): any), + deepTransform(transformed.children, transform), id => id ) }) @@ -65,17 +64,19 @@ function deepTransform(node, transform) { } function getPrettyStylesFromClassNames( - classNames: Array, - elements: Array, - indentation: string + classNames /*: Array */, + elements /*: Array */, + indentation /*: string */ ) { return prettify(getStylesFromClassNames(classNames, elements), indentation) } +/* export type Options = { classNameReplacer?: (className: string, index: number) => string, DOMElements?: boolean } +*/ function filterEmotionProps(props = {}) { const { @@ -101,9 +102,9 @@ function getLabelsFromClassName(keys, className) { } function isShallowEnzymeElement( - element: any, - keys: string[], - labels: string[] + element /*: any */, + keys /*: string[] */, + labels /*: string[] */ ) { const childClassNames = (element.children || []) .map(({ props = {} }) => props.className || '') @@ -115,9 +116,10 @@ function isShallowEnzymeElement( }) } -const createConvertEmotionElements = (keys: string[], printer: *) => ( - node: any -) => { +const createConvertEmotionElements = ( + keys /*: string[] */, + printer +) => node => { if (isPrimitive(node)) { return node } @@ -157,7 +159,7 @@ const createConvertEmotionElements = (keys: string[], printer: *) => ( return node } -function clean(node: any, classNames: string[]) { +function clean(node, classNames /*: string[] */) { if (Array.isArray(node)) { for (const child of node) { clean(child, classNames) @@ -186,17 +188,17 @@ function clean(node: any, classNames: string[]) { export function createSerializer({ classNameReplacer, DOMElements = true -}: Options = {}) { +} /*: Options */ = {}) { const cache = new WeakSet() const isTransformed = val => cache.has(val) function serialize( - val: *, - config: *, - indentation: string, - depth: number, - refs: *, - printer: Function + val, + config, + indentation /*: string */, + depth /*: number */, + refs, + printer /*: Function */ ) { const elements = getStyleElements() const keys = getKeys(elements) @@ -225,7 +227,7 @@ export function createSerializer({ } return { - test(val: *) { + test(val) { return ( val && (!isTransformed(val) && diff --git a/packages/jest/src/enzyme-serializer.js b/packages/jest/src/enzyme-serializer.js index 78c5bba6c..2b7396297 100644 --- a/packages/jest/src/enzyme-serializer.js +++ b/packages/jest/src/enzyme-serializer.js @@ -1,3 +1,2 @@ -// @flow import { createEnzymeSerializer } from './create-enzyme-serializer' export const { test, serialize } = createEnzymeSerializer() diff --git a/packages/jest/src/enzyme.js b/packages/jest/src/enzyme.js index 929a5b359..72fdee8bd 100644 --- a/packages/jest/src/enzyme.js +++ b/packages/jest/src/enzyme.js @@ -1,3 +1,2 @@ -// @flow export { createEnzymeSerializer } from './create-enzyme-serializer' export { matchers } from './matchers' diff --git a/packages/jest/src/index.js b/packages/jest/src/index.js index 0b67c3dd0..c675404fd 100644 --- a/packages/jest/src/index.js +++ b/packages/jest/src/index.js @@ -1,3 +1,2 @@ -// @flow export { createSerializer } from './create-serializer' export { matchers } from './matchers' diff --git a/packages/jest/src/matchers.js b/packages/jest/src/matchers.js index 60fcf0878..50e112d2d 100644 --- a/packages/jest/src/matchers.js +++ b/packages/jest/src/matchers.js @@ -1,4 +1,3 @@ -// @flow import chalk from 'chalk' import * as stylis from 'stylis' import * as specificity from 'specificity' @@ -40,10 +39,10 @@ function valueMatches(declaration, value) { } function toHaveStyleRule( - received: *, - property: *, - value: *, - options?: { target?: string, media?: string } = {} + received, + property, + value, + options /* ?: { target?: string, media?: string } */ = {} ) { const { target, media } = options const classNames = getClassNamesFromNodes([received]) diff --git a/packages/jest/src/replace-class-names.js b/packages/jest/src/replace-class-names.js index 892b67081..713b7c8b2 100644 --- a/packages/jest/src/replace-class-names.js +++ b/packages/jest/src/replace-class-names.js @@ -1,4 +1,3 @@ -// @flow function defaultClassNameReplacer(className, index) { return `emotion-${index}` } @@ -6,14 +5,14 @@ function defaultClassNameReplacer(className, index) { const componentSelectorClassNamePattern = /^e[a-zA-Z0-9]+[0-9]+$/ export const replaceClassNames = ( - classNames: Array, - styles: string, - code: string, - keys: Array, - classNameReplacer: ( + classNames /*: Array */, + styles /*: string */, + code /*: string */, + keys /*: Array */, + classNameReplacer /*: ( className: string, index: number - ) => string = defaultClassNameReplacer + ) => string */ = defaultClassNameReplacer ) => { let index = 0 let keyPattern = new RegExp(`^(${keys.join('|')})-`) diff --git a/packages/jest/src/serializer.js b/packages/jest/src/serializer.js index 3f6afed57..941aa4368 100644 --- a/packages/jest/src/serializer.js +++ b/packages/jest/src/serializer.js @@ -1,3 +1,2 @@ -// @flow import { createSerializer } from './create-serializer' export const { test, serialize } = createSerializer() diff --git a/packages/jest/src/utils.js b/packages/jest/src/utils.js index 7b0d71cb6..50b0c1395 100644 --- a/packages/jest/src/utils.js +++ b/packages/jest/src/utils.js @@ -1,16 +1,20 @@ -// @flow - const isBrowser = typeof document !== 'undefined' function last(arr) { return arr.length > 0 ? arr[arr.length - 1] : undefined } -export function flatMap(arr: T[], iteratee: (arg: T) => S[] | S): S[] { +export function flatMap /* */( + arr /*: T[] */, + iteratee /*: (arg: T) => S[] | S */ +) /*: S[] */ { return [].concat(...arr.map(iteratee)) } -export function findLast(arr: T[], predicate: T => boolean) { +export function findLast /* */( + arr /*: T[] */, + predicate /*: T => boolean */ +) { for (let i = arr.length - 1; i >= 0; i--) { if (predicate(arr[i])) { return arr[i] @@ -18,10 +22,10 @@ export function findLast(arr: T[], predicate: T => boolean) { } } -export function findIndexFrom( - arr: T[], - fromIndex: number, - predicate: T => boolean +export function findIndexFrom /* */( + arr /*: T[] */, + fromIndex /*: number */, + predicate /*: T => boolean */ ) { for (let i = fromIndex; i < arr.length; i++) { if (predicate(arr[i])) { @@ -32,7 +36,7 @@ export function findIndexFrom( return -1 } -function getClassNames(selectors: any, classes?: string) { +function getClassNames(selectors, classes /* ?: string */) { return classes ? selectors.concat(classes.split(' ')) : selectors } @@ -72,18 +76,18 @@ function getClassNamesFromCheerio(selectors, node) { return getClassNames(selectors, classes) } -function getClassNamesFromDOMElement(selectors, node: any) { +function getClassNamesFromDOMElement(selectors, node) { return getClassNames(selectors, node.getAttribute('class')) } -export function isReactElement(val: any): boolean { +export function isReactElement(val) /*: boolean */ { return ( val.$$typeof === Symbol.for('react.test.json') || val.$$typeof === Symbol.for('react.element') ) } -export function isEmotionCssPropElementType(val: any): boolean { +export function isEmotionCssPropElementType(val) /*: boolean */ { return ( val.$$typeof === Symbol.for('react.element') && val.type.$$typeof === Symbol.for('react.forward_ref') && @@ -91,7 +95,7 @@ export function isEmotionCssPropElementType(val: any): boolean { ) } -export function isEmotionCssPropEnzymeElement(val: any): boolean { +export function isEmotionCssPropEnzymeElement(val) /*: boolean */ { return ( val.$$typeof === Symbol.for('react.test.json') && val.type === 'EmotionCssPropInternal' @@ -99,7 +103,7 @@ export function isEmotionCssPropEnzymeElement(val: any): boolean { } const domElementPattern = /^((HTML|SVG)\w*)?Element$/ -export function isDOMElement(val: any): boolean { +export function isDOMElement(val) /*: boolean */ { return ( val.nodeType === 1 && val.constructor && @@ -108,15 +112,15 @@ export function isDOMElement(val: any): boolean { ) } -function isEnzymeElement(val: any): boolean { +function isEnzymeElement(val) /*: boolean */ { return typeof val.findWhere === 'function' } -function isCheerioElement(val: any): boolean { +function isCheerioElement(val) /*: boolean */ { return val.cheerio === '[cheerio object]' } -export function getClassNamesFromNodes(nodes: Array) { +export function getClassNamesFromNodes(nodes /*: Array */) { return nodes.reduce((selectors, node) => { if (isEnzymeElement(node)) { return getClassNamesFromEnzyme(selectors, node) @@ -133,7 +137,7 @@ const keyframesPattern = /^@keyframes\s+(animation-[^{\s]+)+/ const removeCommentPattern = /\/\*[\s\S]*?\*\//g -const getElementRules = (element: HTMLStyleElement): string[] => { +const getElementRules = (element /*: HTMLStyleElement */) /*: string[] */ => { const nonSpeedyRule = element.textContent if (nonSpeedyRule) { return [nonSpeedyRule] @@ -141,7 +145,6 @@ const getElementRules = (element: HTMLStyleElement): string[] => { if (!element.sheet) { return [] } - // $FlowFixMe - flow doesn't know about `cssRules` property return [].slice.call(element.sheet.cssRules).map(cssRule => cssRule.cssText) } @@ -159,9 +162,9 @@ const getKeyframesMap = rules => }, {}) export function getStylesFromClassNames( - classNames: Array, - elements: Array -): string { + classNames /*: Array */, + elements /*: Array */ +) /*: string */ { if (!classNames.length) { return '' } @@ -191,7 +194,7 @@ export function getStylesFromClassNames( const rules = flatMap(elements, getElementRules) let styles = rules - .map((rule: string) => { + .map((rule /*: string */) => { const match = rule.match(selectorPattern) if (!match) { return null @@ -238,35 +241,30 @@ export function getStylesFromClassNames( return (keyframesStyles + styles).replace(removeCommentPattern, '') } -export function getStyleElements(): Array { +export function getStyleElements() /*: Array */ { if (!isBrowser) { throw new Error( 'jest-emotion requires jsdom. See https://jestjs.io/docs/en/configuration#testenvironment-string for more information.' ) } const elements = Array.from(document.querySelectorAll('style[data-emotion]')) - // $FlowFixMe return elements } const unique = arr => Array.from(new Set(arr)) -export function getKeys(elements: Array) { +export function getKeys(elements /*: Array */) { const keys = unique( - elements.map( - element => - // $FlowFixMe we know it exists since we query for elements with this attribute - (element.getAttribute('data-emotion'): string) - ) + elements.map(element => element.getAttribute('data-emotion')) ).filter(Boolean) return keys } export function hasClassNames( - classNames: Array, - selectors: Array, - target?: string | RegExp -): boolean { + classNames /*: Array */, + selectors /*: Array */, + target /* ?: string | RegExp */ +) /*: boolean */ { // selectors is the classNames of specific css rule return selectors.some(selector => { // if no target, use className of the specific css rule and try to find it @@ -286,7 +284,10 @@ export function hasClassNames( }) } -export function getMediaRules(rules: Array, media: string): Array { +export function getMediaRules( + rules /*: Array */, + media /*: string */ +) /*: Array */ { return flatMap( rules.filter(rule => { if (rule.type !== '@media') { @@ -298,10 +299,10 @@ export function getMediaRules(rules: Array, media: string): Array { ) } -export function isPrimitive(test: any) { +export function isPrimitive(test) { return test !== Object(test) } -export function hasIntersection(left: any[], right: any[]) { +export function hasIntersection(left /* any[] */, right /* any[] */) { return left.some(value => right.includes(value)) } diff --git a/packages/jest/test/printer.test.js b/packages/jest/test/printer.test.js index 645737a40..ef5e3c926 100644 --- a/packages/jest/test/printer.test.js +++ b/packages/jest/test/printer.test.js @@ -1,4 +1,3 @@ -// @flow import React from 'react' import ReactDOM from 'react-dom' import 'test-utils/legacy-env' diff --git a/packages/memoize/src/index.js b/packages/memoize/src/index.js index b1e3741a1..104830902 100644 --- a/packages/memoize/src/index.js +++ b/packages/memoize/src/index.js @@ -1,9 +1,9 @@ -// @flow - -export default function memoize(fn: string => V): string => V { +export default function memoize /* */( + fn /*: string => V */ +) /*: string => V */ { const cache = Object.create(null) - return (arg: string) => { + return (arg /*: string */) => { if (cache[arg] === undefined) cache[arg] = fn(arg) return cache[arg] } diff --git a/packages/native/test/native-css.test.js b/packages/native/test/native-css.test.js index ac63ae78f..f3f0bf870 100644 --- a/packages/native/test/native-css.test.js +++ b/packages/native/test/native-css.test.js @@ -31,7 +31,6 @@ describe('Emotion native css', () => { // this test checks the keys instead of the objects // because we care about the order of the keys expect( - // $FlowFixMe Object.keys( StyleSheet.flatten( css({ color: 'green' }, `background-color:yellow;`, { flex: 2 }) @@ -39,7 +38,6 @@ describe('Emotion native css', () => { ) ).toEqual(['color', 'backgroundColor', 'flex']) expect( - // $FlowFixMe Object.keys( StyleSheet.flatten( css([ @@ -52,7 +50,6 @@ describe('Emotion native css', () => { ) ).toEqual(['color', 'backgroundColor', 'flex']) expect( - // $FlowFixMe Object.keys( StyleSheet.flatten( css([ @@ -68,7 +65,6 @@ describe('Emotion native css', () => { ) ).toEqual(['color', 'backgroundColor', 'flex']) expect( - // $FlowFixMe Object.keys( StyleSheet.flatten( css([ diff --git a/packages/primitives-core/src/css.js b/packages/primitives-core/src/css.js index d8ede82e3..80e8bc091 100644 --- a/packages/primitives-core/src/css.js +++ b/packages/primitives-core/src/css.js @@ -1,4 +1,3 @@ -// @flow import transform from 'css-to-react-native' import { interleave } from './utils' @@ -11,7 +10,11 @@ let generated = {} let buffer = '' let lastType -function handleInterpolation(interpolation: *, i: number, arr: Array<*>) { +function handleInterpolation( + interpolation, + i /*: number */, + arr /*: Array<*> */ +) { let type = typeof interpolation if (type === 'string') { @@ -31,15 +34,7 @@ function handleInterpolation(interpolation: *, i: number, arr: Array<*>) { ) } } else { - handleInterpolation.call( - this, - interpolation( - // $FlowFixMe - this - ), - i, - arr - ) + handleInterpolation.call(this, interpolation(this), i, arr) } return } @@ -79,8 +74,8 @@ function handleInterpolation(interpolation: *, i: number, arr: Array<*>) { // Use platform specific StyleSheet method for creating the styles. // This enables us to use the css``/css({}) in any environment (Native | Sketch | Web) -export function createCss(StyleSheet: Object) { - return function css(...args: any) { +export function createCss(StyleSheet /*: Object */) { + return function css(...args) { const prevBuffer = buffer let vals @@ -130,7 +125,7 @@ function convertPropertyValue(style) { } } -function convertStyles(str: string) { +function convertStyles(str /*: string */) { if (str.trim() === '') return const stylePairs = [] diff --git a/packages/primitives-core/src/styled.js b/packages/primitives-core/src/styled.js index f5771552e..4911c6ed0 100644 --- a/packages/primitives-core/src/styled.js +++ b/packages/primitives-core/src/styled.js @@ -1,4 +1,3 @@ -// @flow import * as React from 'react' import { interleave } from './utils' import { ThemeContext } from '@emotion/react' @@ -6,6 +5,7 @@ import { createCss } from './css' let testOmitPropsOnComponent = prop => prop !== 'theme' && prop !== 'as' +/* type CreateStyledOptions = { getShouldForwardProp: (cmp: React.ElementType) => (prop: string) => boolean } @@ -13,18 +13,19 @@ type CreateStyledOptions = { type StyledOptions = { shouldForwardProp?: (prop: string) => boolean } +*/ export function createStyled( - StyleSheet: Object, + StyleSheet /*: Object */, { getShouldForwardProp = () => testOmitPropsOnComponent - }: CreateStyledOptions = {} + } /*: CreateStyledOptions */ = {} ) { const css = createCss(StyleSheet) return function createEmotion( - component: React.ElementType, - options?: StyledOptions + component /*: React.ElementType */, + options /* ?: StyledOptions */ ) { let shouldForwardProp = options && options.shouldForwardProp @@ -34,7 +35,7 @@ export function createStyled( shouldForwardProp || getShouldForwardProp(component) let shouldUseAs = !defaultShouldForwardProp('as') - return function createStyledComponent(...rawStyles: *) { + return function createStyledComponent(...rawStyles) { let styles if (rawStyles[0] == null || rawStyles[0].raw === undefined) { @@ -44,7 +45,6 @@ export function createStyled( } // do we really want to use the same infra as the web since it only really uses theming? - // $FlowFixMe let Styled = React.forwardRef((props, ref) => { const finalTag = (shouldUseAs && props.as) || component @@ -75,11 +75,9 @@ export function createStyled( newProps.style = [css.apply(mergedProps, styles), props.style] newProps.ref = ref - // $FlowFixMe return React.createElement(finalTag, newProps) }) - // $FlowFixMe - Styled.withComponent = (newComponent: React.ElementType) => + Styled.withComponent = (newComponent /*: React.ElementType */) => createEmotion(newComponent)(...styles) Styled.displayName = `emotion(${getDisplayName(component)})` diff --git a/packages/primitives-core/src/utils.js b/packages/primitives-core/src/utils.js index 953c2043d..e423c078c 100644 --- a/packages/primitives-core/src/utils.js +++ b/packages/primitives-core/src/utils.js @@ -1,6 +1,4 @@ -// @flow - -export function interleave(vals: Array<*>) { +export function interleave(vals /*: Array */) { let strings = vals[0] let finalArray = [strings[0]] for (let i = 1, len = vals.length; i < len; i++) { diff --git a/packages/primitives/src/index.js b/packages/primitives/src/index.js index 0dcb3a0d0..a7155513c 100644 --- a/packages/primitives/src/index.js +++ b/packages/primitives/src/index.js @@ -1,4 +1,3 @@ -// @flow import { StyleSheet, Text, View, Image } from 'react-primitives' import { createCss } from '@emotion/primitives-core' diff --git a/packages/primitives/src/styled.js b/packages/primitives/src/styled.js index 894812d67..6e67d9b9f 100644 --- a/packages/primitives/src/styled.js +++ b/packages/primitives/src/styled.js @@ -1,4 +1,3 @@ -// @flow import * as React from 'react' import { StyleSheet, View, Text, Image } from 'react-primitives' import { createStyled } from '@emotion/primitives-core' @@ -7,7 +6,7 @@ import { testPickPropsOnOtherComponent } from './test-props' -function getShouldForwardProp(component: React.ElementType) { +function getShouldForwardProp(component /*: React.ElementType */) { switch (component) { case View: case Text: @@ -22,6 +21,7 @@ function getShouldForwardProp(component: React.ElementType) { * a function that returns a styled component which render styles on multiple targets with same code */ +/* type CreateStyledComponent = ( ...styles: any ) => React.StatelessFunctionalComponent & { @@ -35,7 +35,8 @@ export type Styled = BaseStyled & { Text: CreateStyledComponent, Image: CreateStyledComponent } +*/ -let styled: Styled = createStyled(StyleSheet, { getShouldForwardProp }) +let styled /*: Styled */ = createStyled(StyleSheet, { getShouldForwardProp }) export { styled } diff --git a/packages/primitives/src/test-props.js b/packages/primitives/src/test-props.js index aa19f7f78..ad72f3037 100644 --- a/packages/primitives/src/test-props.js +++ b/packages/primitives/src/test-props.js @@ -1,4 +1,3 @@ -// @flow import isPropValid from '@emotion/is-prop-valid' const forwardableProps = { @@ -49,7 +48,7 @@ const forwardableProps = { textBreakStrategy: true } -export function testPickPropsOnPrimitiveComponent(prop: string) { +export function testPickPropsOnPrimitiveComponent(prop /*: string */) { return ( forwardableProps[prop] === true || // This will allow the standard react props @@ -59,6 +58,6 @@ export function testPickPropsOnPrimitiveComponent(prop: string) { ) } -export function testPickPropsOnOtherComponent(prop: string) { +export function testPickPropsOnOtherComponent(prop /*: string */) { return prop !== 'theme' } diff --git a/packages/primitives/test/css.test.js b/packages/primitives/test/css.test.js index 93fc9b219..a5b0882d3 100644 --- a/packages/primitives/test/css.test.js +++ b/packages/primitives/test/css.test.js @@ -1,4 +1,3 @@ -// @flow import { css } from '@emotion/primitives' import { StyleSheet } from 'react-native' @@ -29,7 +28,6 @@ test('order with string and object', () => { // this test checks the keys instead of the objects // because we care about the order of the keys expect( - // $FlowFixMe Object.keys( StyleSheet.flatten( css({ color: 'green' }, `background-color:yellow;`, { flex: 2 }) @@ -37,7 +35,6 @@ test('order with string and object', () => { ) ).toEqual(['color', 'backgroundColor', 'flex']) expect( - // $FlowFixMe Object.keys( StyleSheet.flatten( css([ @@ -50,7 +47,6 @@ test('order with string and object', () => { ) ).toEqual(['color', 'backgroundColor', 'flex']) expect( - // $FlowFixMe Object.keys( StyleSheet.flatten( css([ @@ -66,7 +62,6 @@ test('order with string and object', () => { ) ).toEqual(['color', 'backgroundColor', 'flex']) expect( - // $FlowFixMe Object.keys( StyleSheet.flatten( css([ diff --git a/packages/primitives/test/emotion-primitives.test.js b/packages/primitives/test/emotion-primitives.test.js index 7a23ef9cc..bd3ad00b8 100644 --- a/packages/primitives/test/emotion-primitives.test.js +++ b/packages/primitives/test/emotion-primitives.test.js @@ -1,4 +1,3 @@ -// @flow import * as React from 'react' import renderer from 'react-test-renderer' import { Text, StyleSheet } from 'react-primitives' @@ -17,7 +16,6 @@ describe('Emotion primitives', () => { }) test('should throw an error when used invalid primitive', () => { - // $FlowFixMe: expect error expect(() => styled.TEXT({})).toThrow() }) @@ -29,7 +27,6 @@ describe('Emotion primitives', () => { ` const tree = renderer .create( - // $FlowFixMe Emotion Primitives @@ -46,7 +43,6 @@ describe('Emotion primitives', () => { const tree = renderer .create( - {/* $FlowFixMe */} Hello World ) @@ -64,7 +60,6 @@ describe('Emotion primitives', () => { render( - {/* $FlowFixMe */} Hello World @@ -81,7 +76,6 @@ describe('Emotion primitives', () => { color: props.decor })) const tree = renderer - // $FlowFixMe .create(Emotion Primitives) .toJSON() expect(tree).toMatchSnapshot() @@ -92,10 +86,7 @@ describe('Emotion primitives', () => { color: hotpink; ` const tree = renderer - .create( - // $FlowFixMe - Emotion primitives - ) + .create(Emotion primitives) .toJSON() expect(tree).toMatchSnapshot() }) @@ -107,7 +98,6 @@ describe('Emotion primitives', () => { ` const tree = renderer - // $FlowFixMe .create(Emotion Primitives) .toJSON() expect(tree).toMatchSnapshot() @@ -117,7 +107,6 @@ describe('Emotion primitives', () => { const StyledText = styled.Text` color: ${props => props.decor}; ` - // $FlowFixMe const Name = StyledText.withComponent(Text) const tree = renderer.create(Mike).toJSON() expect(tree).toMatchSnapshot() @@ -127,13 +116,11 @@ describe('Emotion primitives', () => { const Text = styled.Text` color: hotpink; ` - // $FlowFixMe const Title = () => Hello World const StyledTitle = styled(Title)` font-size: 20px; font-style: ${props => props.sty}; ` - // $FlowFixMe const tree = renderer.create().toJSON() expect(tree).toMatchSnapshot() }) @@ -144,7 +131,6 @@ describe('Emotion primitives', () => { ` let ref = React.createRef() const rootNode = document.createElement('div') - // $FlowFixMe render(, rootNode) expect(ref.current).toBe(rootNode.firstElementChild) unmountComponentAtNode(rootNode) @@ -154,9 +140,7 @@ describe('Emotion primitives', () => { const ViewOne = styled.View` background-color: ${props => props.color}; ` - // $FlowFixMe const treeOne = renderer.create() - // $FlowFixMe const ViewTwo = ViewOne.withComponent(Text) const treeTwo = renderer.create() @@ -170,7 +154,6 @@ describe('Emotion primitives', () => { ` const tree = renderer .create( - // $FlowFixMe { test('custom shouldForwardProp works', () => { const Text = styled.Text`` const Title = props => - // $FlowFixMe const StyledTitle = styled(Title, { shouldForwardProp: prop => prop !== 'color' && prop !== 'theme' })` diff --git a/packages/primitives/test/no-babel/basic.test.js b/packages/primitives/test/no-babel/basic.test.js index be39d3ab1..7697ac125 100644 --- a/packages/primitives/test/no-babel/basic.test.js +++ b/packages/primitives/test/no-babel/basic.test.js @@ -1,4 +1,3 @@ -// @flow import * as React from 'react' import styled, { css } from '@emotion/primitives' import renderer from 'react-test-renderer' @@ -48,7 +47,6 @@ test('should render the primitive when styles applied using object style notatio ` const tree = renderer .create( - // $FlowFixMe Emotion Primitives diff --git a/packages/primitives/test/warnings.test.js b/packages/primitives/test/warnings.test.js index 7aa51c2bb..12e5ef993 100644 --- a/packages/primitives/test/warnings.test.js +++ b/packages/primitives/test/warnings.test.js @@ -1,7 +1,5 @@ -// @flow import { css } from '@emotion/primitives' -// $FlowFixMe console.error = jest.fn() afterEach(() => { diff --git a/packages/react/__tests__/at-import.js b/packages/react/__tests__/at-import.js index 6b0297477..cb3470b13 100644 --- a/packages/react/__tests__/at-import.js +++ b/packages/react/__tests__/at-import.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/prod-mode' import * as React from 'react' /** @jsx jsx */ @@ -7,9 +6,7 @@ import { render, unmountComponentAtNode } from 'react-dom' import { Global, css } from '@emotion/react' beforeEach(() => { - // $FlowFixMe document.head.innerHTML = '' - // $FlowFixMe document.body.innerHTML = `
` }) @@ -26,7 +23,7 @@ test('basic', () => { } `} /> - , // $FlowFixMe + , document.getElementById('root') ) expect(document.head).toMatchSnapshot() @@ -34,7 +31,6 @@ test('basic', () => { let elements = document.querySelectorAll('style') let rules = [] for (let element of elements) { - // $FlowFixMe for (let cssRule of element.sheet.cssRules) { rules.push(cssRule.cssText) } diff --git a/packages/react/__tests__/babel/__snapshots__/source-map-server.js.snap b/packages/react/__tests__/babel/__snapshots__/source-map-server.js.snap index 75854f868..701a78c0a 100644 --- a/packages/react/__tests__/babel/__snapshots__/source-map-server.js.snap +++ b/packages/react/__tests__/babel/__snapshots__/source-map-server.js.snap @@ -1,3 +1,3 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`basic 1`] = `"
some hotpink text
"`; +exports[`basic 1`] = `"
some hotpink text
"`; diff --git a/packages/react/__tests__/babel/source-map-server.js b/packages/react/__tests__/babel/source-map-server.js index 60ecf1857..e55735edf 100644 --- a/packages/react/__tests__/babel/source-map-server.js +++ b/packages/react/__tests__/babel/source-map-server.js @@ -1,7 +1,7 @@ /** @jsx jsx * @jest-environment node */ -// @flow + import 'test-utils/dev-mode' import { jsx } from '@emotion/react' import { renderToString } from 'react-dom/server' diff --git a/packages/react/__tests__/class-names.js b/packages/react/__tests__/class-names.js index d165f3b59..7fe0c2305 100644 --- a/packages/react/__tests__/class-names.js +++ b/packages/react/__tests__/class-names.js @@ -1,4 +1,3 @@ -// @flow import * as React from 'react' import 'test-utils/next-env' import { ClassNames, ThemeProvider } from '@emotion/react' diff --git a/packages/react/__tests__/clone-element.js b/packages/react/__tests__/clone-element.js index dedd52c62..8a73c2393 100644 --- a/packages/react/__tests__/clone-element.js +++ b/packages/react/__tests__/clone-element.js @@ -1,4 +1,3 @@ -// @flow /** @jsx jsx */ import { jsx } from '@emotion/react' import * as React from 'react' diff --git a/packages/react/__tests__/compat/browser.js b/packages/react/__tests__/compat/browser.js index a6c8c02d4..44fe94e3f 100644 --- a/packages/react/__tests__/compat/browser.js +++ b/packages/react/__tests__/compat/browser.js @@ -1,4 +1,3 @@ -// @flow /** @jsx jsx */ import 'test-utils/dev-mode' import { throwIfFalsy } from 'test-utils' diff --git a/packages/react/__tests__/compat/server.js b/packages/react/__tests__/compat/server.js index 08218a251..4e72d857c 100644 --- a/packages/react/__tests__/compat/server.js +++ b/packages/react/__tests__/compat/server.js @@ -1,6 +1,5 @@ /** @jsx jsx * @jest-environment node - * @flow */ import { jsx, Global } from '@emotion/react' import createEmotionServer from '@emotion/server/create-instance' diff --git a/packages/react/__tests__/css-cache-hash.js b/packages/react/__tests__/css-cache-hash.js index 5e1a4fd55..f7428bf46 100644 --- a/packages/react/__tests__/css-cache-hash.js +++ b/packages/react/__tests__/css-cache-hash.js @@ -1,4 +1,3 @@ -// @flow /** @jsx jsx */ import 'test-utils/next-env' import { jsx, css } from '@emotion/react' diff --git a/packages/react/__tests__/css.js b/packages/react/__tests__/css.js index 2d7e99285..2b37cb7b0 100644 --- a/packages/react/__tests__/css.js +++ b/packages/react/__tests__/css.js @@ -1,4 +1,3 @@ -// @flow /** @jsx jsx */ import 'test-utils/next-env' import { safeQuerySelector } from 'test-utils' @@ -8,9 +7,7 @@ import { render } from '@testing-library/react' import renderer from 'react-test-renderer' import createCache from '@emotion/cache' -// $FlowFixMe console.error = jest.fn() -// $FlowFixMe console.warn = jest.fn() afterEach(() => { @@ -18,12 +15,11 @@ afterEach(() => { safeQuerySelector('body').innerHTML = '' }) -const SomeComponent = (props: { lol: true }) => (props.lol ? 'yes' : 'no') +const SomeComponent = (props /*: { lol: true } */) => (props.lol ? 'yes' : 'no') // test to make sure flow prop errors work. // should probably try to make it so that components that require className props // and have the css prop passed to them don't have type errors -// $FlowFixMe ; // eslint-disable-line no-unused-expressions test('thing', () => { @@ -223,7 +219,7 @@ test('autoLabel without babel (sanitized)', () => { }) test('overwrite styles from parent', () => { - let SomeComponent = (props: Object) => ( + let SomeComponent = (props /*: Object */) => (
{ }) test('applies class when css prop is set to nil on wrapper component', () => { - const Button = (props: any) => ( - + } */ + ) => const tree = renderer.create( @@ -341,6 +337,6 @@ it("doesn't try to insert invalid rules caused by object style's value being fal ) - expect((console.error: any).mock.calls).toMatchInlineSnapshot(`Array []`) - expect((console.warn: any).mock.calls).toMatchInlineSnapshot(`Array []`) + expect(console.error.mock.calls).toMatchInlineSnapshot(`Array []`) + expect(console.warn.mock.calls).toMatchInlineSnapshot(`Array []`) }) diff --git a/packages/react/__tests__/custom-cache.js b/packages/react/__tests__/custom-cache.js index 1fb975c8c..82bb595d9 100644 --- a/packages/react/__tests__/custom-cache.js +++ b/packages/react/__tests__/custom-cache.js @@ -1,4 +1,3 @@ -// @flow /** @jsx jsx */ import 'test-utils/next-env' import createCache from '@emotion/cache' diff --git a/packages/react/__tests__/global-with-theme.js b/packages/react/__tests__/global-with-theme.js index f8b66b430..b4706fe1d 100644 --- a/packages/react/__tests__/global-with-theme.js +++ b/packages/react/__tests__/global-with-theme.js @@ -1,13 +1,10 @@ -// @flow import 'test-utils/dev-mode' import * as React from 'react' import { render, unmountComponentAtNode } from 'react-dom' import { Global, ThemeProvider } from '@emotion/react' beforeEach(() => { - // $FlowFixMe document.head.innerHTML = '' - // $FlowFixMe document.body.innerHTML = `
` }) @@ -22,7 +19,6 @@ test('basic', () => { })} /> , - // $FlowFixMe document.getElementById('root') ) expect(document.documentElement).toMatchSnapshot() @@ -39,7 +35,7 @@ test('array', () => { theme => ({ html: { fontSize: theme.fontSize } }) ]} /> - , // $FlowFixMe + , document.getElementById('root') ) expect(document.documentElement).toMatchSnapshot() diff --git a/packages/react/__tests__/global.js b/packages/react/__tests__/global.js index 6e88b2704..366751657 100644 --- a/packages/react/__tests__/global.js +++ b/packages/react/__tests__/global.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/dev-mode' import * as React from 'react' import { render, unmountComponentAtNode } from 'react-dom' @@ -6,9 +5,7 @@ import { Global, keyframes, css, CacheProvider } from '@emotion/react' import createCache from '@emotion/cache' beforeEach(() => { - // $FlowFixMe document.head.innerHTML = '' - // $FlowFixMe document.body.innerHTML = `
` }) @@ -41,7 +38,6 @@ test('basic', () => { ]} /> , - // $FlowFixMe document.getElementById('root') ) expect(document.head).toMatchSnapshot() @@ -58,7 +54,6 @@ test('updating more than 1 global rule', () => { , - // $FlowFixMe document.getElementById('root') ) diff --git a/packages/react/__tests__/globals-are-the-worst.js b/packages/react/__tests__/globals-are-the-worst.js index 2d40fa367..be98404ae 100644 --- a/packages/react/__tests__/globals-are-the-worst.js +++ b/packages/react/__tests__/globals-are-the-worst.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/dev-mode' import { throwIfFalsy } from 'test-utils' import * as React from 'react' diff --git a/packages/react/__tests__/import-prod.js b/packages/react/__tests__/import-prod.js index bf3bcb3a7..1162cf011 100644 --- a/packages/react/__tests__/import-prod.js +++ b/packages/react/__tests__/import-prod.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/prod-mode' import * as React from 'react' import { css, Global } from '@emotion/react' diff --git a/packages/react/__tests__/keyframes.js b/packages/react/__tests__/keyframes.js index acf849f7d..481f866e0 100644 --- a/packages/react/__tests__/keyframes.js +++ b/packages/react/__tests__/keyframes.js @@ -1,4 +1,3 @@ -// @flow /** @jsx jsx */ import 'test-utils/next-env' import { jsx, css, keyframes } from '@emotion/react' diff --git a/packages/react/__tests__/legacy-class-name.js b/packages/react/__tests__/legacy-class-name.js index dd1d13dbf..82345c420 100644 --- a/packages/react/__tests__/legacy-class-name.js +++ b/packages/react/__tests__/legacy-class-name.js @@ -1,4 +1,3 @@ -// @flow /** @jsx jsx */ import 'test-utils/next-env' import { jsx, css } from '@emotion/react' diff --git a/packages/react/__tests__/ref.js b/packages/react/__tests__/ref.js index bb9766602..0b82cce60 100644 --- a/packages/react/__tests__/ref.js +++ b/packages/react/__tests__/ref.js @@ -1,4 +1,3 @@ -// @flow /** @jsx jsx */ import { jsx } from '@emotion/react' import * as React from 'react' diff --git a/packages/react/__tests__/rehydration.js b/packages/react/__tests__/rehydration.js index c415100c6..ec5ce96e8 100644 --- a/packages/react/__tests__/rehydration.js +++ b/packages/react/__tests__/rehydration.js @@ -1,10 +1,7 @@ -// @flow /** @jsx jsx */ import { safeQuerySelector } from 'test-utils' -// $FlowFixMe console.error = jest.fn() -// $FlowFixMe console.warn = jest.fn() afterEach(() => { @@ -44,11 +41,10 @@ const removeGlobalProp = prop => { writable: true, configurable: true }) - // $FlowFixMe return () => Object.defineProperty(global, prop, descriptor) } -const disableBrowserEnvTemporarily = (fn: () => T): T => { +const disableBrowserEnvTemporarily = /* */ (fn /*: () => T */) /*: T */ => { let restoreDocument = removeGlobalProp('document') let restoreWindow = removeGlobalProp('window') let restoreHTMLElement = removeGlobalProp('HTMLElement') @@ -92,8 +88,8 @@ test("cache created in render doesn't cause a hydration mismatch", () => { ReactDOM.hydrate(, safeQuerySelector('#root')) - expect((console.error: any).mock.calls).toMatchInlineSnapshot(`Array []`) - expect((console.warn: any).mock.calls).toMatchInlineSnapshot(`Array []`) + expect(console.error.mock.calls).toMatchInlineSnapshot(`Array []`) + expect(console.warn.mock.calls).toMatchInlineSnapshot(`Array []`) }) test('initializing another Emotion instance should not move already moved styles elements', () => { diff --git a/packages/react/__tests__/server.js b/packages/react/__tests__/server.js index c6625a385..44197477f 100644 --- a/packages/react/__tests__/server.js +++ b/packages/react/__tests__/server.js @@ -1,7 +1,7 @@ /** @jsx jsx * @jest-environment node */ -// @flow + import 'test-utils/dev-mode' import * as React from 'react' import testCases from 'jest-in-case' diff --git a/packages/react/__tests__/theme-provider.dom.js b/packages/react/__tests__/theme-provider.dom.js index ef0a6deda..6e74165b1 100644 --- a/packages/react/__tests__/theme-provider.dom.js +++ b/packages/react/__tests__/theme-provider.dom.js @@ -1,4 +1,3 @@ -// @flow /** @jsx jsx */ import 'test-utils/next-env' import 'test-utils/dev-mode' @@ -8,7 +7,7 @@ import { jsx, ThemeProvider } from '@emotion/react' import { render } from 'react-dom' test('provider with theme value that changes', () => { - class ThemeTest extends React.Component<*, *> { + class ThemeTest extends React.Component { state = { theme: { color: 'hotpink', padding: 4 } } render() { return ( diff --git a/packages/react/__tests__/theme-provider.js b/packages/react/__tests__/theme-provider.js index d9a06c079..1e6b84bc6 100644 --- a/packages/react/__tests__/theme-provider.js +++ b/packages/react/__tests__/theme-provider.js @@ -1,4 +1,3 @@ -// @flow /** @jsx jsx */ import 'test-utils/next-env' import { ignoreConsoleErrors } from 'test-utils' @@ -57,7 +56,6 @@ cases( expect(() => { renderer.create( - {/* $FlowFixMe */}
({ diff --git a/packages/react/__tests__/use-theme.js b/packages/react/__tests__/use-theme.js index cbf5d8ca7..301b5c3f0 100644 --- a/packages/react/__tests__/use-theme.js +++ b/packages/react/__tests__/use-theme.js @@ -1,4 +1,3 @@ -// @flow /** @jsx jsx */ import 'test-utils/next-env' import * as renderer from 'react-test-renderer' diff --git a/packages/react/__tests__/warnings.js b/packages/react/__tests__/warnings.js index 820dc3241..e15633111 100644 --- a/packages/react/__tests__/warnings.js +++ b/packages/react/__tests__/warnings.js @@ -1,11 +1,9 @@ -// @flow /** @jsx jsx */ import 'test-utils/next-env' import { jsx, css, Global, keyframes, ClassNames } from '@emotion/react' import renderer from 'react-test-renderer' import { render } from '@testing-library/react' -// $FlowFixMe console.error = jest.fn() const validValues = [ @@ -44,7 +42,6 @@ it('does not warn when valid values are passed for the content property', () => const invalidValues = ['this is not valid', ''] it('does warn when invalid values are passed for the content property', () => { - // $FlowFixMe invalidValues.forEach(value => { expect(() => renderer.create(
) @@ -74,7 +71,7 @@ describe('unsafe pseudo classes', () => { color: hotpink; } ` - const match = (pseudoClass.match(/(:first|:nth|:nth-last)-child/): any) + const match = pseudoClass.match(/(:first|:nth|:nth-last)-child/) expect(match).not.toBeNull() expect(renderer.create(
).toJSON()).toMatchSnapshot() expect(console.error).toBeCalledWith( @@ -121,9 +118,7 @@ describe('unsafe pseudo classes', () => { /\/\* \S+ \*\//g, '/* [flag] */' )}" in a style ${type}`, () => { - const match = (pseudoClass.match( - /(:first|:nth|:nth-last)-child/ - ): any) + const match = pseudoClass.match(/(:first|:nth|:nth-last)-child/) expect(match).not.toBeNull() expect( renderer.create(
).toJSON() @@ -138,7 +133,6 @@ describe('unsafe pseudo classes', () => { test('global with css prop', () => { let tree = renderer .create( - // $FlowFixMe { css({ '@media (min-width 800px)': undefined }) css({ '--primary-color': 'hotpink' }) css({ ':last-of-type': null }) - expect((console.error: any).mock.calls).toMatchInlineSnapshot(` + expect(console.error.mock.calls).toMatchInlineSnapshot(` Array [ Array [ "Using kebab-case for css properties in objects is not supported. Did you mean backgroundColor?", @@ -194,7 +188,7 @@ test('keyframes interpolated into plain string', () => { renderer.create(
) - expect((console.error: any).mock.calls).toMatchInlineSnapshot(` + expect(console.error.mock.calls).toMatchInlineSnapshot(` Array [ Array [ "\`keyframes\` output got interpolated into plain string, please wrap it with \`css\`. @@ -237,7 +231,6 @@ test('`css` opaque object passed to `cx` from ', () => { {({ cx }) => (
', () => { ) - expect((console.error: any).mock.calls).toMatchInlineSnapshot(` + expect(console.error.mock.calls).toMatchInlineSnapshot(` Array [ Array [ "You have passed styles created with \`css\` from \`@emotion/react\` package to the \`cx\`. @@ -271,7 +264,7 @@ test('@import nested in scoped `css`', () => { /> ) - expect((console.error: any).mock.calls).toMatchInlineSnapshot(` + expect(console.error.mock.calls).toMatchInlineSnapshot(` Array [ Array [ "\`@import\` rules can't be nested inside other rules. Please move it to the top level and put it before regular rules. Keep in mind that they can only be used within global styles.", @@ -293,7 +286,7 @@ test('@import prepended with other rules', () => { /> ) - expect((console.error: any).mock.calls).toMatchInlineSnapshot(` + expect(console.error.mock.calls).toMatchInlineSnapshot(` Array [ Array [ "\`@import\` rules can't be after other rules. Please put your \`@import\` rules before your other rules.", @@ -312,7 +305,7 @@ test('@import prepended by other @import', () => { /> ) - expect((console.error: any).mock.calls).toMatchInlineSnapshot(`Array []`) + expect(console.error.mock.calls).toMatchInlineSnapshot(`Array []`) }) test('when using `jsx` multiple static children should not result in a key-related warning', () => { @@ -322,5 +315,5 @@ test('when using `jsx` multiple static children should not result in a key-relat
) - expect((console.error: any).mock.calls).toMatchInlineSnapshot(`Array []`) + expect(console.error.mock.calls).toMatchInlineSnapshot(`Array []`) }) diff --git a/packages/react/__tests__/with-theme.js b/packages/react/__tests__/with-theme.js index 4512dc47e..95c0b9c98 100644 --- a/packages/react/__tests__/with-theme.js +++ b/packages/react/__tests__/with-theme.js @@ -1,10 +1,9 @@ -// @flow import * as React from 'react' import * as renderer from 'react-test-renderer' import { withTheme, ThemeProvider } from '@emotion/react' test('withTheme works', () => { - class SomeComponent extends React.Component<{ theme: Object }> { + class SomeComponent extends React.Component /* <{ theme: Object }> */ { render() { return this.props.theme.color } @@ -22,7 +21,7 @@ test('withTheme works', () => { }) test(`withTheme(Comp) hoists non-react static class properties`, () => { - class ExampleComponent extends React.Component<*> { + class ExampleComponent extends React.Component { static displayName = 'foo' static someSpecialStatic = 'bar' } @@ -30,14 +29,13 @@ test(`withTheme(Comp) hoists non-react static class properties`, () => { const ComponentWithTheme = withTheme(ExampleComponent) expect(ComponentWithTheme.displayName).toBe('WithTheme(foo)') - // $FlowFixMe hoist-non-react-statics doesn't work with AbstractComponent https://github.com/facebook/flow/issues/7612 expect(ComponentWithTheme.someSpecialStatic).toBe( ExampleComponent.someSpecialStatic ) }) it('should forward the ref', () => { - class SomeComponent extends React.Component<*> { + class SomeComponent extends React.Component { render() { return this.props.theme.color } diff --git a/packages/react/macro.js.flow b/packages/react/macro.js.flow deleted file mode 100644 index 63ae97e66..000000000 --- a/packages/react/macro.js.flow +++ /dev/null @@ -1,2 +0,0 @@ -// @flow -export * from './src/index.js' diff --git a/packages/react/src/class-names.js b/packages/react/src/class-names.js index bb44d02e4..f605add75 100644 --- a/packages/react/src/class-names.js +++ b/packages/react/src/class-names.js @@ -1,4 +1,3 @@ -// @flow import * as React from 'react' import { getRegisteredStyles, insertStyles } from '@emotion/utils' import { serializeStyles } from '@emotion/serialize' @@ -6,6 +5,7 @@ import { withEmotionCache } from './context' import { ThemeContext } from './theming' import { isBrowser } from './utils' +/* type ClassNameArg = | string | boolean @@ -13,8 +13,9 @@ type ClassNameArg = | Array | null | void +*/ -let classnames = (args: Array): string => { +let classnames = (args /*: Array */) /*: string */ => { let len = args.length let i = 0 let cls = '' @@ -62,9 +63,9 @@ let classnames = (args: Array): string => { return cls } function merge( - registered: Object, - css: (...args: Array) => string, - className: string + registered /*: Object */, + css /*: (...args: Array) => string */, + className /*: string */ ) { const registeredStyles = [] @@ -80,6 +81,7 @@ function merge( return rawClassName + css(registeredStyles) } +/* type Props = { children: ({ css: (...args: any) => string, @@ -87,61 +89,64 @@ type Props = { theme: Object }) => React.Node } +*/ -export const ClassNames: React.AbstractComponent< +export const ClassNames /*: React.AbstractComponent< Props -> = /* #__PURE__ */ withEmotionCache((props, cache) => { - let rules = '' - let serializedHashes = '' - let hasRendered = false +> */ = /* #__PURE__ */ withEmotionCache( + (props, cache) => { + let rules = '' + let serializedHashes = '' + let hasRendered = false - let css = (...args: Array) => { - if (hasRendered && process.env.NODE_ENV !== 'production') { - throw new Error('css can only be used during render') + let css = (...args /*: Array */) => { + if (hasRendered && process.env.NODE_ENV !== 'production') { + throw new Error('css can only be used during render') + } + let serialized = serializeStyles(args, cache.registered) + if (isBrowser) { + insertStyles(cache, serialized, false) + } else { + let res = insertStyles(cache, serialized, false) + if (res !== undefined) { + rules += res + } + } + if (!isBrowser) { + serializedHashes += ` ${serialized.name}` + } + return `${cache.key}-${serialized.name}` } - let serialized = serializeStyles(args, cache.registered) - if (isBrowser) { - insertStyles(cache, serialized, false) - } else { - let res = insertStyles(cache, serialized, false) - if (res !== undefined) { - rules += res + let cx = (...args /*: Array */) => { + if (hasRendered && process.env.NODE_ENV !== 'production') { + throw new Error('cx can only be used during render') } + return merge(cache.registered, css, classnames(args)) } - if (!isBrowser) { - serializedHashes += ` ${serialized.name}` + let content = { + css, + cx, + theme: React.useContext(ThemeContext) } - return `${cache.key}-${serialized.name}` - } - let cx = (...args: Array) => { - if (hasRendered && process.env.NODE_ENV !== 'production') { - throw new Error('cx can only be used during render') + let ele = props.children(content) + hasRendered = true + if (!isBrowser && rules.length !== 0) { + return ( + <> + ` } diff --git a/packages/server/src/index.js b/packages/server/src/index.js index 94000e3e6..9e00e4424 100644 --- a/packages/server/src/index.js +++ b/packages/server/src/index.js @@ -1,4 +1,3 @@ -// @flow import createEmotionServer from './create-instance' import { cache } from '@emotion/css' diff --git a/packages/server/test/extract-critical-to-chunks.test.js b/packages/server/test/extract-critical-to-chunks.test.js index b035592fc..f68eb679d 100644 --- a/packages/server/test/extract-critical-to-chunks.test.js +++ b/packages/server/test/extract-critical-to-chunks.test.js @@ -1,11 +1,10 @@ /** * @jest-environment node - * @flow */ import React from 'react' import { renderToString } from 'react-dom/server' -import type { Emotion } from '@emotion/css/create-instance' +/* import type { Emotion } from '@emotion/css/create-instance' */ import { prettifyCriticalChunks } from './util' let emotion = require('@emotion/css') @@ -13,8 +12,8 @@ let reactEmotion = require('@emotion/styled') let emotionServer = require('@emotion/server') export const getComponents = ( - emotion: Emotion, - { default: styled }: { default: Function } + emotion /*: Emotion */, + { default: styled } /*: { default: Function } */ ) => { let Provider = require('@emotion/react').CacheProvider let Global = require('@emotion/react').Global diff --git a/packages/server/test/index.test.js b/packages/server/test/index.test.js index 9e655cc87..85baf7089 100644 --- a/packages/server/test/index.test.js +++ b/packages/server/test/index.test.js @@ -1,6 +1,5 @@ /** * @jest-environment node - * @flow */ import React from 'react' @@ -39,7 +38,7 @@ describe('extractCritical', () => { ) ) - expect((console.error: any).mock.calls).toMatchObject([]) + expect(console.error.mock.calls).toMatchObject([]) }) }) }) diff --git a/packages/server/test/inline.test.js b/packages/server/test/inline.test.js index 17464c587..c3542e2f6 100644 --- a/packages/server/test/inline.test.js +++ b/packages/server/test/inline.test.js @@ -1,6 +1,5 @@ /** * @jest-environment node - * @flow */ import { JSDOM } from 'jsdom' diff --git a/packages/server/test/stream.test.js b/packages/server/test/stream.test.js index ce7cf5680..519f2d707 100644 --- a/packages/server/test/stream.test.js +++ b/packages/server/test/stream.test.js @@ -1,6 +1,5 @@ /** * @jest-environment node - * @flow */ import { JSDOM } from 'jsdom' diff --git a/packages/server/test/util.js b/packages/server/test/util.js index 23896d0ca..2eacbdaf7 100644 --- a/packages/server/test/util.js +++ b/packages/server/test/util.js @@ -1,23 +1,23 @@ -// @flow /* eslint-env jest */ import * as React from 'react' import prettify from '@emotion/css-prettifier' -import type { Emotion } from '@emotion/css/create-instance' -// $FlowFixMe +/* import type { Emotion } from '@emotion/css/create-instance' */ import { renderToNodeStream } from 'react-dom/server' import HTMLSerializer from 'jest-serializer-html' +/* type EmotionServer = { renderStylesToNodeStream: () => *, extractCritical: string => { html: string, css: string, ids: Array }, renderStylesToString: string => string } +*/ expect.addSnapshotSerializer(HTMLSerializer) export const getComponents = ( - emotion: Emotion, - { default: styled }: { default: Function } + emotion /*: Emotion */, + { default: styled } /*: { default: Function } */ ) => { let Provider = require('@emotion/react').CacheProvider let { injectGlobal, keyframes, css } = emotion @@ -127,8 +127,8 @@ export const getComponents = ( const maxColors = Math.pow(16, 6) -export const createBigComponent = ({ injectGlobal, css }: Emotion) => { - const BigComponent = ({ count }: { count: number }) => { +export const createBigComponent = ({ injectGlobal, css } /*: Emotion */) => { + const BigComponent = ({ count } /*: { count: number } */) => { if (count === 0) return null injectGlobal` .some-global-${count} { @@ -154,15 +154,13 @@ export const createBigComponent = ({ injectGlobal, css }: Emotion) => { return BigComponent } -export const prettifyCritical = ({ - html, - css, - ids -}: { +export const prettifyCritical = ( + { html, css, ids } /*: { html: string, css: string, ids: Array -}) => { +} */ +) => { return { css: prettify(css), ids, @@ -170,17 +168,20 @@ export const prettifyCritical = ({ } } -export const prettifyCriticalChunks = ({ - html, - styles -}: { +export const prettifyCriticalChunks = ( + { + html, + styles + } /*: { html: string, styles: Array<{ key: string, css: string, ids: Array }> -}) => { +} */ +) => { return { - // $FlowFixMe - styles: styles.map<{ key: string, css: string, ids: Array }>( - (item): { key: string, css: string, ids: Array } => { + styles: styles.map( + /* <{ key: string, css: string, ids: Array }> */ ( + item + ) /*: { key: string, css: string, ids: Array } */ => { return { css: prettify(item.css || ''), ids: item.ids, key: item.key } } ), @@ -189,20 +190,19 @@ export const prettifyCriticalChunks = ({ } const isSSRedStyle = node => { - const attrib = ((node.getAttribute(`data-emotion`): any): string).split(' ') + const attrib = node.getAttribute(`data-emotion`).split(' ') // SSRed styles have also serialized names set here return attrib.length > 1 } -export const getCssFromChunks = (emotion: Emotion, document: Document) => { +export const getCssFromChunks = ( + emotion /*: Emotion */, + document /*: Document */ +) => { const chunks = Array.from( - // $FlowFixMe emotion.sheet.tags[0].parentNode.querySelectorAll(`[data-emotion]`) ).filter(isSSRedStyle) - expect( - // $FlowFixMe - document.body.querySelector(`[data-emotion]`) - ).toBeNull() + expect(document.body.querySelector(`[data-emotion]`)).toBeNull() let css = chunks.map(chunk => chunk.textContent || '').join('') return prettify(css) } @@ -215,7 +215,7 @@ export const getInjectedRules = () => .join('') ) -export const setHtml = (html: string, document: Document) => { +export const setHtml = (html /*: string */, document /*: Document */) => { if (document.body !== null) { document.body.innerHTML = html } else { @@ -224,9 +224,9 @@ export const setHtml = (html: string, document: Document) => { } export const renderToStringWithStream = ( - element: React.Element<*>, - { renderStylesToNodeStream }: EmotionServer -): Promise => + element /*: React.Element<*> */, + { renderStylesToNodeStream } /*: EmotionServer */ +) /*: Promise */ => new Promise((resolve, reject) => { const stream = renderToNodeStream(element).pipe(renderStylesToNodeStream()) let html = '' diff --git a/packages/sheet/__tests__/index.js b/packages/sheet/__tests__/index.js index 2a8c6fc3d..7139a0339 100644 --- a/packages/sheet/__tests__/index.js +++ b/packages/sheet/__tests__/index.js @@ -1,4 +1,3 @@ -// @flow import { safeQuerySelector } from 'test-utils' import { StyleSheet } from '@emotion/sheet' @@ -10,7 +9,6 @@ let defaultOptions = { container: safeQuerySelector('head') } -// $FlowFixMe console.error = jest.fn() afterEach(() => { @@ -44,7 +42,6 @@ describe('StyleSheet', () => { sheet.insert(rule) expect(document.documentElement).toMatchSnapshot() expect( - // $FlowFixMe document.querySelector('[data-emotion]').getAttribute('data-emotion') ).toBe(key) sheet.flush() @@ -62,7 +59,6 @@ describe('StyleSheet', () => { sheet.insert(rule) expect(document.documentElement).toMatchSnapshot() expect(sheet.tags).toHaveLength(1) - // $FlowFixMe expect(sheet.tags[0].sheet.cssRules).toMatchSnapshot() sheet.flush() }) @@ -71,7 +67,7 @@ describe('StyleSheet', () => { const sheet = new StyleSheet({ ...defaultOptions, speedy: true }) sheet.insert('.asdfasdf4###112121211{') expect(console.error).toHaveBeenCalledTimes(1) - expect((console.error: any).mock.calls[0][0]).toBe( + expect(console.error.mock.calls[0][0]).toBe( 'There was a problem inserting the following rule: ".asdfasdf4###112121211{"' ) sheet.flush() @@ -89,7 +85,6 @@ describe('StyleSheet', () => { it("should use the container option instead of document.head to insert style elements into if it's passed", () => { const container = document.createElement('div') - // $FlowFixMe document.body.appendChild(container) const sheet = new StyleSheet({ ...defaultOptions, container }) expect(sheet.container).toBe(container) @@ -98,7 +93,6 @@ describe('StyleSheet', () => { expect(sheet.tags).toHaveLength(1) expect(sheet.tags[0].parentNode).toBe(container) sheet.flush() - // $FlowFixMe document.body.removeChild(container) }) diff --git a/packages/sheet/src/index.js b/packages/sheet/src/index.js index 768bde0f0..b5fb62890 100644 --- a/packages/sheet/src/index.js +++ b/packages/sheet/src/index.js @@ -1,4 +1,3 @@ -// @flow /* Based off glamor's StyleSheet, thanks Sunil ❤️ @@ -22,10 +21,8 @@ styleSheet.flush() */ -// $FlowFixMe -function sheetForTag(tag: HTMLStyleElement): CSSStyleSheet { +function sheetForTag(tag /*: HTMLStyleElement */) /*: CSSStyleSheet */ { if (tag.sheet) { - // $FlowFixMe return tag.sheet } @@ -33,12 +30,12 @@ function sheetForTag(tag: HTMLStyleElement): CSSStyleSheet { /* istanbul ignore next */ for (let i = 0; i < document.styleSheets.length; i++) { if (document.styleSheets[i].ownerNode === tag) { - // $FlowFixMe return document.styleSheets[i] } } } +/* export type Options = { nonce?: string, key: string, @@ -46,11 +43,14 @@ export type Options = { speedy?: boolean, prepend?: boolean } +*/ -function createStyleElement(options: { +function createStyleElement( + options /*: { key: string, nonce: string | void -}): HTMLStyleElement { +} */ +) /*: HTMLStyleElement */ { let tag = document.createElement('style') tag.setAttribute('data-emotion', options.key) if (options.nonce !== undefined) { @@ -62,15 +62,15 @@ function createStyleElement(options: { } export class StyleSheet { - isSpeedy: boolean - ctr: number - tags: HTMLStyleElement[] - container: HTMLElement - key: string - nonce: string | void - prepend: boolean | void - before: Element | null - constructor(options: Options) { + isSpeedy /*: boolean */ + ctr /*: number */ + tags /*: HTMLStyleElement[] */ + container /*: HTMLElement */ + key /*: string */ + nonce /*: string | void */ + prepend /*: boolean | void */ + before /*: Element | null */ + constructor(options /*: Options */) { this.isSpeedy = options.speedy === undefined ? process.env.NODE_ENV === 'production' @@ -85,7 +85,7 @@ export class StyleSheet { this.before = null } - _insertTag = (tag: HTMLStyleElement) => { + _insertTag = (tag /*: HTMLStyleElement */) => { let before if (this.tags.length === 0) { before = this.prepend ? this.container.firstChild : this.before @@ -96,11 +96,11 @@ export class StyleSheet { this.tags.push(tag) } - hydrate(nodes: HTMLStyleElement[]) { + hydrate(nodes /*: HTMLStyleElement[] */) { nodes.forEach(this._insertTag) } - insert(rule: string) { + insert(rule /*: string */) { // the max length is how many rules we have per style tag, it's 65000 in speedy mode // it's 1 in dev because we insert source maps that map a single rule to a location // and you can only have one source map per style tag @@ -113,7 +113,7 @@ export class StyleSheet { const isImportRule = rule.charCodeAt(0) === 64 && rule.charCodeAt(1) === 105 - if (isImportRule && (this: any)._alreadyInsertedOrderInsensitiveRule) { + if (isImportRule && this._alreadyInsertedOrderInsensitiveRule) { // this would only cause problem in speedy mode // but we don't want enabling speedy to affect the observable behavior // so we report this error at all times @@ -124,8 +124,8 @@ export class StyleSheet { ) } - ;(this: any)._alreadyInsertedOrderInsensitiveRule = - (this: any)._alreadyInsertedOrderInsensitiveRule || !isImportRule + this._alreadyInsertedOrderInsensitiveRule = + this._alreadyInsertedOrderInsensitiveRule || !isImportRule } if (this.isSpeedy) { @@ -154,12 +154,11 @@ export class StyleSheet { } flush() { - // $FlowFixMe this.tags.forEach(tag => tag.parentNode.removeChild(tag)) this.tags = [] this.ctr = 0 if (process.env.NODE_ENV !== 'production') { - ;(this: any)._alreadyInsertedOrderInsensitiveRule = false + this._alreadyInsertedOrderInsensitiveRule = false } } } diff --git a/packages/styled/__tests__/as-prop.js b/packages/styled/__tests__/as-prop.js index 26bfd1049..69c57c437 100644 --- a/packages/styled/__tests__/as-prop.js +++ b/packages/styled/__tests__/as-prop.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/next-env' import React from 'react' import { render, cleanup } from '@testing-library/react' diff --git a/packages/styled/__tests__/edge-cases.js b/packages/styled/__tests__/edge-cases.js index ec1070375..3bf21f72f 100644 --- a/packages/styled/__tests__/edge-cases.js +++ b/packages/styled/__tests__/edge-cases.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/next-env' import * as React from 'react' import renderer from 'react-test-renderer' diff --git a/packages/styled/__tests__/styled-dom.js b/packages/styled/__tests__/styled-dom.js index cd5b54cb0..91d35fae0 100644 --- a/packages/styled/__tests__/styled-dom.js +++ b/packages/styled/__tests__/styled-dom.js @@ -1,4 +1,3 @@ -// @flow import * as React from 'react' import styled from '@emotion/styled' import { render, cleanup } from '@testing-library/react' diff --git a/packages/styled/__tests__/styled.js b/packages/styled/__tests__/styled.js index 3cd6047fb..62093e173 100644 --- a/packages/styled/__tests__/styled.js +++ b/packages/styled/__tests__/styled.js @@ -1,4 +1,3 @@ -// @flow /** @jsx jsx */ import 'test-utils/next-env' import renderer from 'react-test-renderer' @@ -588,7 +587,6 @@ describe('styled', () => { test('throws if undefined is passed as the component', () => { expect( () => - // $FlowFixMe styled(undefined)` display: flex; ` diff --git a/packages/styled/__tests__/warnings.js b/packages/styled/__tests__/warnings.js index b0cfcebca..417753ed4 100644 --- a/packages/styled/__tests__/warnings.js +++ b/packages/styled/__tests__/warnings.js @@ -1,11 +1,9 @@ -// @flow import 'test-utils/legacy-env' import * as React from 'react' import { css } from '@emotion/react' import styled from '@emotion/styled' import { render } from '@testing-library/react' -// $FlowFixMe console.error = jest.fn() afterEach(() => { @@ -19,7 +17,7 @@ it('warns about illegal escape sequences inside first quasi of template literal' } ` - expect((console.error: any).mock.calls[0]).toMatchInlineSnapshot(` + expect(console.error.mock.calls[0]).toMatchInlineSnapshot(` Array [ "You have illegal escape sequence in your template literal, most likely inside content's property value. Because you write your CSS inside a JavaScript string you actually have to do double escaping, so for example \\"content: '\\\\00d7';\\" should become \\"content: '\\\\\\\\00d7';\\". @@ -41,7 +39,7 @@ it('warns about illegal escape sequences inside non-first quasi of template lite } ` - expect((console.error: any).mock.calls[0]).toMatchInlineSnapshot(` + expect(console.error.mock.calls[0]).toMatchInlineSnapshot(` Array [ "You have illegal escape sequence in your template literal, most likely inside content's property value. Because you write your CSS inside a JavaScript string you actually have to do double escaping, so for example \\"content: '\\\\00d7';\\" should become \\"content: '\\\\\\\\00d7';\\". @@ -53,12 +51,11 @@ it('warns about illegal escape sequences inside non-first quasi of template lite it("warns about undefined being passed as object style's key", () => { let ListItem - // $FlowFixMe const List = styled.ul({ [ListItem]: { color: 'hotpink' } }) render() - expect((console.error: any).mock.calls[0]).toMatchInlineSnapshot(` + expect(console.error.mock.calls[0]).toMatchInlineSnapshot(` Array [ "You have passed in falsy value as style object's key (can happen when in example you pass unexported component as computed key).", ] diff --git a/packages/styled/flow-tests/base.js b/packages/styled/flow-tests/base.js deleted file mode 100644 index 9ab45ca9f..000000000 --- a/packages/styled/flow-tests/base.js +++ /dev/null @@ -1,21 +0,0 @@ -/* eslint-disable no-unused-vars */ -// @flow -import React from 'react' -import createStyled from '../src/base' -import type { CreateStyledComponent, StyledComponent } from '../src/utils' - -const valid: StyledComponent = createStyled('div')({ - color: 'red' -}) - -// $FlowFixMe: expect error - we can't cast a StyledComponent to string -const invalid: string = createStyled('div')({ color: 'red' }) - -const styled = createStyled('div') - -// $FlowFixMe: expect error - we don't expose the private StyledComponent properties -const invalidPropAccess = styled().__emotion_base - -// We allow styled components not to specify their props types -// NOTE: this is allowed only if you don't attempt to export it! -const untyped: StyledComponent = styled({}) diff --git a/packages/styled/flow-tests/index.js b/packages/styled/flow-tests/index.js deleted file mode 100644 index f941917ae..000000000 --- a/packages/styled/flow-tests/index.js +++ /dev/null @@ -1,20 +0,0 @@ -/* eslint-disable no-unused-vars */ -// @flow -import * as React from 'react' -import styled from '../src' - -type Props = { color: string } -const Foo = styled.div({ - color: 'red' -}) - -const valid = - -// $FlowFixMe: expect error - color must be string -const invalid = - -// components defined using the root method should be identical -// to the ones generated using the shortcuts -const root: typeof Foo = styled('div')` - colors: red; -` diff --git a/packages/styled/flow-tests/styled.js b/packages/styled/flow-tests/styled.js deleted file mode 100644 index 7ede72471..000000000 --- a/packages/styled/flow-tests/styled.js +++ /dev/null @@ -1,25 +0,0 @@ -/* eslint-disable no-unused-vars */ -// @flow -import React from 'react' -import styled from '../src' -import type { CreateStyledComponent, StyledComponent } from '../src/utils' - -type Props = { color: string } -const Div = styled.div({ color: 'red' }) - -const validProp =
- -// $FlowFixMe: expect error - color property should be a string -const invalidProp =
- -styled(props =>
{props.color}
)` - color: ${props => props.color}; -` - -styled(props => { - const color: string = props.color - const className: string = props.className - // $FlowFixMe: expect error - color should be a string - const colorTest: number = props.color - return
{props.color}
-})`` diff --git a/packages/styled/macro.js.flow b/packages/styled/macro.js.flow deleted file mode 100644 index b2d58a66c..000000000 --- a/packages/styled/macro.js.flow +++ /dev/null @@ -1,3 +0,0 @@ -// @flow -export * from './src/index.js' -export { default } from './src/index.js' diff --git a/packages/styled/package.json b/packages/styled/package.json index 1eebe5b32..ac026b3e9 100644 --- a/packages/styled/package.json +++ b/packages/styled/package.json @@ -45,8 +45,7 @@ "base", "types/*.d.ts", "macro.d.ts", - "macro.js", - "macro.js.flow" + "macro.js" ], "umd:main": "dist/emotion-styled.umd.min.js", "browser": { diff --git a/packages/styled/src/base.js b/packages/styled/src/base.js index aa64f9d95..8e327a3c4 100644 --- a/packages/styled/src/base.js +++ b/packages/styled/src/base.js @@ -1,12 +1,13 @@ -// @flow import * as React from 'react' import { getDefaultShouldForwardProp, - composeShouldForwardProps, + composeShouldForwardProps + /* type StyledOptions, type CreateStyled, type PrivateStyledComponent, type StyledElementType + */ } from './utils' import { withEmotionCache, ThemeContext } from '@emotion/react' import { getRegisteredStyles, insertStyles } from '@emotion/utils' @@ -19,7 +20,10 @@ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_liter let isBrowser = typeof document !== 'undefined' -let createStyled: CreateStyled = (tag: any, options?: StyledOptions) => { +let createStyled /*: CreateStyled */ = ( + tag /*: any */, + options /* ?: StyledOptions */ +) => { if (process.env.NODE_ENV !== 'production') { if (tag === undefined) { throw new Error( @@ -42,7 +46,8 @@ let createStyled: CreateStyled = (tag: any, options?: StyledOptions) => { shouldForwardProp || getDefaultShouldForwardProp(baseTag) const shouldUseAs = !defaultShouldForwardProp('as') - return function(): PrivateStyledComponent { + /* return function(): PrivateStyledComponent { */ + return function() { let args = arguments let styles = isReal && tag.__emotion_styles !== undefined @@ -69,8 +74,7 @@ let createStyled: CreateStyled = (tag: any, options?: StyledOptions) => { } } - // $FlowFixMe: we need to cast StatelessFunctionalComponent to our PrivateStyledComponent class - const Styled: PrivateStyledComponent = withEmotionCache( + const Styled /*: PrivateStyledComponent */ = withEmotionCache( (props, cache, ref) => { const finalTag = (shouldUseAs && props.as) || baseTag @@ -120,10 +124,7 @@ let createStyled: CreateStyled = (tag: any, options?: StyledOptions) => { for (let key in props) { if (shouldUseAs && key === 'as') continue - if ( - // $FlowFixMe - finalShouldForwardProp(key) - ) { + if (finalShouldForwardProp(key)) { newProps[key] = props[key] } } @@ -179,18 +180,16 @@ let createStyled: CreateStyled = (tag: any, options?: StyledOptions) => { ) { return 'NO_COMPONENT_SELECTOR' } - // $FlowFixMe: coerce undefined to string return `.${targetClassName}` } }) Styled.withComponent = ( - nextTag: StyledElementType, - nextOptions?: StyledOptions + nextTag /*: StyledElementType */, + nextOptions /* ?: StyledOptions */ ) => { return createStyled(nextTag, { ...options, - // $FlowFixMe ...nextOptions, shouldForwardProp: composeShouldForwardProps(Styled, nextOptions, true) })(...styles) diff --git a/packages/styled/src/index.js b/packages/styled/src/index.js index 420f7f476..dd11a7c90 100644 --- a/packages/styled/src/index.js +++ b/packages/styled/src/index.js @@ -1,4 +1,3 @@ -// @flow import styled from './base' import { tags } from './tags' @@ -6,7 +5,6 @@ import { tags } from './tags' const newStyled = styled.bind() tags.forEach(tagName => { - // $FlowFixMe: we can ignore this because its exposed type is defined by the CreateStyled type newStyled[tagName] = newStyled(tagName) }) diff --git a/packages/styled/src/tags.js b/packages/styled/src/tags.js index e33db9d7e..19bd40236 100644 --- a/packages/styled/src/tags.js +++ b/packages/styled/src/tags.js @@ -1,4 +1,3 @@ -// @flow export const tags = [ 'a', 'abbr', diff --git a/packages/styled/src/utils.js b/packages/styled/src/utils.js index 1ae27ebfc..83a999d19 100644 --- a/packages/styled/src/utils.js +++ b/packages/styled/src/utils.js @@ -1,11 +1,11 @@ -// @flow -import type { +/* import type { ElementType, StatelessFunctionalComponent, AbstractComponent -} from 'react' +} from 'react' */ import isPropValid from '@emotion/is-prop-valid' +/* export type Interpolations = Array export type StyledElementType = @@ -33,11 +33,12 @@ export type PrivateStyledComponent = StyledComponent & { __emotion_styles: any, __emotion_forwardProp: any } +*/ const testOmitPropsOnStringTag = isPropValid -const testOmitPropsOnComponent = (key: string) => key !== 'theme' +const testOmitPropsOnComponent = (key /*: string */) => key !== 'theme' -export const getDefaultShouldForwardProp = (tag: ElementType) => +export const getDefaultShouldForwardProp = (tag /*: ElementType */) => typeof tag === 'string' && // 96 is one less than the char code // for "a" so this is checking that @@ -47,16 +48,16 @@ export const getDefaultShouldForwardProp = (tag: ElementType) => : testOmitPropsOnComponent export const composeShouldForwardProps = ( - tag: PrivateStyledComponent, - options: StyledOptions | void, - isReal: boolean + tag /*: PrivateStyledComponent */, + options /*: StyledOptions | void */, + isReal /*: boolean */ ) => { let shouldForwardProp if (options) { const optionsShouldForwardProp = options.shouldForwardProp shouldForwardProp = tag.__emotion_forwardProp && optionsShouldForwardProp - ? (propName: string) => + ? (propName /*: string */) => tag.__emotion_forwardProp(propName) && optionsShouldForwardProp(propName) : optionsShouldForwardProp @@ -69,6 +70,7 @@ export const composeShouldForwardProps = ( return shouldForwardProp } +/* export type CreateStyledComponent = ( ...args: Interpolations ) => StyledComponent @@ -81,3 +83,4 @@ export type CreateStyled = { [key: string]: CreateStyledComponent, bind: () => CreateStyled } +*/ diff --git a/packages/styled/test/__snapshots__/source-map.test.js.snap b/packages/styled/test/__snapshots__/source-map.test.js.snap index f165bb74b..5f1f21cf4 100644 --- a/packages/styled/test/__snapshots__/source-map.test.js.snap +++ b/packages/styled/test/__snapshots__/source-map.test.js.snap @@ -8,7 +8,7 @@ exports[`inserts source map 1`] = ` data-s="" > - .css-1igngve-Comp{color:hotpink;}/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNvdXJjZS1tYXAudGVzdC5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFNdUIiLCJmaWxlIjoic291cmNlLW1hcC50ZXN0LmpzIiwic291cmNlc0NvbnRlbnQiOlsiLy8gQGZsb3dcbmltcG9ydCBSZWFjdCBmcm9tICdyZWFjdCdcbmltcG9ydCBzdHlsZWQgZnJvbSAnQGVtb3Rpb24vc3R5bGVkJ1xuaW1wb3J0IHJlbmRlcmVyIGZyb20gJ3JlYWN0LXRlc3QtcmVuZGVyZXInXG5cbnRlc3QoJ2luc2VydHMgc291cmNlIG1hcCcsICgpID0+IHtcbiAgbGV0IENvbXAgPSBzdHlsZWQuZGl2YFxuICAgIGNvbG9yOiBob3RwaW5rO1xuICBgXG4gIHJlbmRlcmVyLmNyZWF0ZSg8Q29tcCAvPilcbiAgZXhwZWN0KGRvY3VtZW50LmRvY3VtZW50RWxlbWVudCkudG9NYXRjaFNuYXBzaG90KClcbn0pXG4iXX0= */ + .css-1igngve-Comp{color:hotpink;}/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNvdXJjZS1tYXAudGVzdC5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFLdUIiLCJmaWxlIjoic291cmNlLW1hcC50ZXN0LmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IFJlYWN0IGZyb20gJ3JlYWN0J1xuaW1wb3J0IHN0eWxlZCBmcm9tICdAZW1vdGlvbi9zdHlsZWQnXG5pbXBvcnQgcmVuZGVyZXIgZnJvbSAncmVhY3QtdGVzdC1yZW5kZXJlcidcblxudGVzdCgnaW5zZXJ0cyBzb3VyY2UgbWFwJywgKCkgPT4ge1xuICBsZXQgQ29tcCA9IHN0eWxlZC5kaXZgXG4gICAgY29sb3I6IGhvdHBpbms7XG4gIGBcbiAgcmVuZGVyZXIuY3JlYXRlKDxDb21wIC8+KVxuICBleHBlY3QoZG9jdW1lbnQuZG9jdW1lbnRFbGVtZW50KS50b01hdGNoU25hcHNob3QoKVxufSlcbiJdfQ== */ diff --git a/packages/styled/test/babel-plugin.test.js b/packages/styled/test/babel-plugin.test.js index fc8cbdbe3..c1c9492f2 100644 --- a/packages/styled/test/babel-plugin.test.js +++ b/packages/styled/test/babel-plugin.test.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/legacy-env' import React from 'react' import * as renderer from 'react-test-renderer' diff --git a/packages/styled/test/composition.test.js b/packages/styled/test/composition.test.js index b96e620ce..df26d912c 100644 --- a/packages/styled/test/composition.test.js +++ b/packages/styled/test/composition.test.js @@ -1,4 +1,3 @@ -// @flow /** @jsx jsx */ import 'test-utils/legacy-env' import * as renderer from 'react-test-renderer' diff --git a/packages/styled/test/index.test.js b/packages/styled/test/index.test.js index e73594200..84aac65bc 100644 --- a/packages/styled/test/index.test.js +++ b/packages/styled/test/index.test.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/legacy-env' import React from 'react' import * as renderer from 'react-test-renderer' @@ -301,7 +300,6 @@ describe('styled', () => { test('throws if undefined is passed as the component', () => { expect( () => - // $FlowFixMe styled(undefined)` display: flex; ` @@ -391,7 +389,7 @@ describe('styled', () => { }) test('name with class component', () => { - class SomeComponent extends React.Component<{ className: string }> { + class SomeComponent extends React.Component /* <{ className: string }> */ { render() { return
} diff --git a/packages/styled/test/prop-filtering.test.js b/packages/styled/test/prop-filtering.test.js index 34e4be0e7..7d776bf19 100644 --- a/packages/styled/test/prop-filtering.test.js +++ b/packages/styled/test/prop-filtering.test.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/legacy-env' import React from 'react' import * as renderer from 'react-test-renderer' diff --git a/packages/styled/test/source-map.test.js b/packages/styled/test/source-map.test.js index 380bb69bd..41b9284cb 100644 --- a/packages/styled/test/source-map.test.js +++ b/packages/styled/test/source-map.test.js @@ -1,4 +1,3 @@ -// @flow import React from 'react' import styled from '@emotion/styled' import renderer from 'react-test-renderer' diff --git a/packages/styled/test/theming.dom.test.js b/packages/styled/test/theming.dom.test.js index fcb219edd..bae7d46f7 100644 --- a/packages/styled/test/theming.dom.test.js +++ b/packages/styled/test/theming.dom.test.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/legacy-env' import React from 'react' import styled from '@emotion/styled' diff --git a/packages/styled/test/theming.test.js b/packages/styled/test/theming.test.js index da9578b42..69a1431d6 100644 --- a/packages/styled/test/theming.test.js +++ b/packages/styled/test/theming.test.js @@ -1,4 +1,3 @@ -// @flow import 'test-utils/legacy-env' import React from 'react' import * as renderer from 'react-test-renderer' diff --git a/packages/unitless/src/index.js b/packages/unitless/src/index.js index fe8ae2653..797533b59 100644 --- a/packages/unitless/src/index.js +++ b/packages/unitless/src/index.js @@ -1,6 +1,4 @@ -// @flow - -let unitlessKeys: { [key: string]: 1 } = { +let unitlessKeys /*: { [key: string]: 1 } */ = { animationIterationCount: 1, borderImageOutset: 1, borderImageSlice: 1, diff --git a/packages/utils/src/index.js b/packages/utils/src/index.js index 647f1c810..2fdfe9a9f 100644 --- a/packages/utils/src/index.js +++ b/packages/utils/src/index.js @@ -1,12 +1,11 @@ -// @flow -import type { RegisteredCache, EmotionCache, SerializedStyles } from './types' +/* import type { RegisteredCache, EmotionCache, SerializedStyles } from './types' */ const isBrowser = typeof document !== 'undefined' export function getRegisteredStyles( - registered: RegisteredCache, - registeredStyles: string[], - classNames: string + registered /*: RegisteredCache */, + registeredStyles /*: string[] */, + classNames /*: string */ ) { let rawClassName = '' @@ -21,9 +20,9 @@ export function getRegisteredStyles( } export const insertStyles = ( - cache: EmotionCache, - serialized: SerializedStyles, - isStringTag: boolean + cache /*: EmotionCache */, + serialized /*: SerializedStyles */, + isStringTag /*: boolean */ ) => { let className = `${cache.key}-${serialized.name}` if ( diff --git a/packages/utils/src/types.js b/packages/utils/src/types.js index 173b5063e..59b8667c2 100644 --- a/packages/utils/src/types.js +++ b/packages/utils/src/types.js @@ -1,6 +1,6 @@ -// @flow -import type { StyleSheet } from '@emotion/sheet' +/* import type { StyleSheet } from '@emotion/sheet' */ +/* export type RegisteredCache = { [string]: string } export type Interpolation = any @@ -26,3 +26,4 @@ export type EmotionCache = { shouldCache: boolean ) => string | void } +*/ diff --git a/packages/weak-memoize/src/index.js b/packages/weak-memoize/src/index.js index e512fe175..8dcbd91a9 100644 --- a/packages/weak-memoize/src/index.js +++ b/packages/weak-memoize/src/index.js @@ -1,10 +1,9 @@ -// @flow -let weakMemoize = function(func: Arg => Return): Arg => Return { - // $FlowFixMe flow doesn't include all non-primitive types as allowed for weakmaps - let cache: WeakMap = new WeakMap() +let weakMemoize = function( + /* */ func /*: Arg => Return */ +) /*: Arg => Return */ { + let cache /*: WeakMap */ = new WeakMap() return arg => { if (cache.has(arg)) { - // $FlowFixMe return cache.get(arg) } let ret = func(arg) diff --git a/playgrounds/cra/src/App.js b/playgrounds/cra/src/App.js index 4a4e97cf2..4bc222c3c 100644 --- a/playgrounds/cra/src/App.js +++ b/playgrounds/cra/src/App.js @@ -1,4 +1,3 @@ -// @flow import * as React from 'react' /** @jsx jsx */ import { Global, jsx, keyframes } from '@emotion/react' diff --git a/playgrounds/cra/src/index.js b/playgrounds/cra/src/index.js index 2ba54d3e5..de1c42044 100644 --- a/playgrounds/cra/src/index.js +++ b/playgrounds/cra/src/index.js @@ -1,4 +1,3 @@ -// @flow import * as React from 'react' import { render } from 'react-dom' import App from './App' diff --git a/playgrounds/razzle/src/App.js b/playgrounds/razzle/src/App.js index ab6e3a127..05397fd1a 100644 --- a/playgrounds/razzle/src/App.js +++ b/playgrounds/razzle/src/App.js @@ -1,4 +1,3 @@ -// @flow import * as React from 'react' import Route from 'react-router-dom/Route' import Switch from 'react-router-dom/Switch' diff --git a/playgrounds/razzle/src/Home.js b/playgrounds/razzle/src/Home.js index b8df8ed2c..e1372e77b 100644 --- a/playgrounds/razzle/src/Home.js +++ b/playgrounds/razzle/src/Home.js @@ -1,9 +1,8 @@ -// @flow /** @jsx jsx */ import { jsx } from '@emotion/react' import * as React from 'react' -class Home extends React.Component<{}, { isBrowser: boolean }> { +class Home extends React.Component /* <{}, { isBrowser: boolean }> */ { state = { isBrowser: false } componentDidMount() { this.setState({ isBrowser: true }) diff --git a/playgrounds/razzle/src/client.js b/playgrounds/razzle/src/client.js index 3aafb0fcc..be9b7a746 100644 --- a/playgrounds/razzle/src/client.js +++ b/playgrounds/razzle/src/client.js @@ -1,4 +1,3 @@ -// @flow import App from './App' import BrowserRouter from 'react-router-dom/BrowserRouter' import * as React from 'react' @@ -17,8 +16,6 @@ hydrate( root ) -// $FlowFixMe if (module.hot) { - // $FlowFixMe module.hot.accept() } diff --git a/playgrounds/razzle/src/index.js b/playgrounds/razzle/src/index.js index 5f0c00988..d069adfd7 100644 --- a/playgrounds/razzle/src/index.js +++ b/playgrounds/razzle/src/index.js @@ -1,4 +1,3 @@ -// @flow import app from './server' import http from 'http' @@ -12,10 +11,10 @@ server.listen(process.env.PORT || 3000, error => { } console.log('🚀 started') -}) // $FlowFixMe +}) + if (module.hot) { console.log('✅ Server-side HMR Enabled!') - // $FlowFixMe module.hot.accept('./server', () => { console.log('🔁 HMR Reloading `./server`...') server.removeListener('request', currentApp) diff --git a/playgrounds/razzle/src/server.js b/playgrounds/razzle/src/server.js index bec262448..7663623e8 100644 --- a/playgrounds/razzle/src/server.js +++ b/playgrounds/razzle/src/server.js @@ -1,4 +1,3 @@ -// @flow import App from './App' import * as React from 'react' import { StaticRouter } from 'react-router-dom' @@ -8,7 +7,6 @@ import { renderStylesToString } from '@emotion/server' import { cache } from '@emotion/css' import { CacheProvider } from '@emotion/react' -// $FlowFixMe const assets = require(process.env.RAZZLE_ASSETS_MANIFEST) const server = express() diff --git a/scripts/babel-preset-emotion-dev/package.json b/scripts/babel-preset-emotion-dev/package.json index 866bce576..2e77860b7 100644 --- a/scripts/babel-preset-emotion-dev/package.json +++ b/scripts/babel-preset-emotion-dev/package.json @@ -8,7 +8,6 @@ }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.13.0", - "@babel/plugin-transform-flow-strip-types": "^7.13.0", "babel-plugin-add-basic-constructor-for-react-components": "^0.1.0", "babel-plugin-fix-dce-for-classes-with-statics": "^0.1.0" } diff --git a/scripts/babel-preset-emotion-dev/src/index.js b/scripts/babel-preset-emotion-dev/src/index.js index 4556166ba..c6f3c2812 100644 --- a/scripts/babel-preset-emotion-dev/src/index.js +++ b/scripts/babel-preset-emotion-dev/src/index.js @@ -18,7 +18,6 @@ module.exports = (api, options = {}) => { 'babel-plugin-add-basic-constructor-for-react-components' ), require.resolve('babel-plugin-fix-dce-for-classes-with-statics'), - require.resolve('@babel/plugin-transform-flow-strip-types'), require.resolve('babel-plugin-codegen'), [ require.resolve('@babel/plugin-transform-runtime'), diff --git a/scripts/babel-tester/src/index.js b/scripts/babel-tester/src/index.js index 95020ad68..0589d33f8 100644 --- a/scripts/babel-tester/src/index.js +++ b/scripts/babel-tester/src/index.js @@ -1,4 +1,3 @@ -// @flow /* eslint-env jest */ import jestInCase from 'jest-in-case' import * as babel from '@babel/core' @@ -47,8 +46,8 @@ function doThing(dirname) { } export default ( - name: string, - cases: + name /*: string */, + cases /*: | { [key: string]: { code: string, @@ -56,13 +55,13 @@ export default ( babelFileName?: string } } - | string, - opts?: { + | string */, + opts /* ?: { plugins?: Array<*>, presets?: Array<*>, transform?: string => string, filename?: string - } = {} + } */ = {} ) => { if (typeof cases === 'string') { cases = doThing(cases).reduce((accum, filename) => { @@ -86,6 +85,5 @@ export default ( }, {}) } - // $FlowFixMe return jestInCase(name, tester(opts), cases) } diff --git a/scripts/benchmarks/.babelrc b/scripts/benchmarks/.babelrc index 8fecfd4cf..4e025bd5b 100644 --- a/scripts/benchmarks/.babelrc +++ b/scripts/benchmarks/.babelrc @@ -1,7 +1,6 @@ { "presets": [ ["@babel/env", { "modules": false, "loose": true }], - "@babel/flow", "@babel/react" ], "plugins": [ diff --git a/scripts/benchmarks/run.js b/scripts/benchmarks/run.js index aeccd4dd3..d7049af47 100644 --- a/scripts/benchmarks/run.js +++ b/scripts/benchmarks/run.js @@ -1,5 +1,5 @@ // some of this is from https://github.com/styled-components/styled-components/blob/master/benchmarks/run-headless.js -// @flow + const path = require('path') const puppeteer = require('puppeteer') const { createServer } = require('http-server') diff --git a/scripts/benchmarks/src/app/App.js b/scripts/benchmarks/src/app/App.js index 2fe3c1e0c..bbd69bf5e 100644 --- a/scripts/benchmarks/src/app/App.js +++ b/scripts/benchmarks/src/app/App.js @@ -16,7 +16,7 @@ import { colors } from './theme' const Overlay = () => -export default class App extends Component<{}> { +export default class App extends Component { static displayName = '@app/App' constructor(props, context) { diff --git a/scripts/benchmarks/src/app/Benchmark/index.js b/scripts/benchmarks/src/app/Benchmark/index.js index a5b74eb00..bf11aff07 100644 --- a/scripts/benchmarks/src/app/Benchmark/index.js +++ b/scripts/benchmarks/src/app/Benchmark/index.js @@ -4,19 +4,17 @@ * https://github.com/paularmstrong/react-component-benchmark */ -/* global $Values */ -/** - * @flow - */ import * as Timing from './timing' import React, { Component } from 'react' import { getMean, getMedian, getStdDev } from './math' +/* import type { BenchResultsType, FullSampleTimingType, SampleTimingType } from './types' +*/ export const BenchmarkType = { MOUNT: 'mount', @@ -25,9 +23,9 @@ export const BenchmarkType = { } const shouldRender = ( - cycle: number, - type: $Values -): boolean => { + cycle /*: number */, + type /*: $Values */ +) /*: boolean */ => { switch (type) { // Render every odd iteration (first, third, etc) // Mounts and unmounts the component @@ -43,9 +41,9 @@ const shouldRender = ( } const shouldRecord = ( - cycle: number, - type: $Values -): boolean => { + cycle /*: number */, + type /*: $Values */ +) /*: boolean */ => { switch (type) { // Record every odd iteration (when mounted: first, third, etc) case BenchmarkType.MOUNT: @@ -62,10 +60,10 @@ const shouldRecord = ( } const isDone = ( - cycle: number, - sampleCount: number, - type: $Values -): boolean => { + cycle /*: number */, + sampleCount /*: number */, + type /*: $Values */ +) /*: boolean */ => { switch (type) { case BenchmarkType.MOUNT: return cycle >= sampleCount * 2 - 1 @@ -78,8 +76,9 @@ const isDone = ( } } -const sortNumbers = (a: number, b: number): number => a - b +const sortNumbers = (a /*: number */, b /*: number */) /*: number */ => a - b +/* type BenchmarkPropsType = { component: typeof React.Component, forceLayout?: boolean, @@ -95,19 +94,19 @@ type BenchmarkStateType = { cycle: number, running: boolean } +*/ /** * Benchmark * TODO: documentation */ -export default class Benchmark extends Component< +export default class Benchmark extends Component /* < BenchmarkPropsType, BenchmarkStateType -> { - _raf: ?Function - _startTime: number - _samples: Array - +> */ { + _raf /*: ?Function */ + _startTime /*: number */ + _samples /*: Array */ static displayName = 'Benchmark' static defaultProps = { @@ -118,7 +117,7 @@ export default class Benchmark extends Component< static Type = BenchmarkType - constructor(props: BenchmarkPropsType, context?: {}) { + constructor(props /*: BenchmarkPropsType */, context /* ?: {} */) { super(props, context) const cycle = 0 const componentProps = props.getComponentProps({ cycle }) @@ -131,7 +130,7 @@ export default class Benchmark extends Component< this._samples = [] } - componentWillReceiveProps(nextProps: BenchmarkPropsType) { + componentWillReceiveProps(nextProps /*: BenchmarkPropsType */) { if (nextProps) { this.setState(state => ({ componentProps: nextProps.getComponentProps(state.cycle) @@ -140,8 +139,8 @@ export default class Benchmark extends Component< } componentWillUpdate( - nextProps: BenchmarkPropsType, - nextState: BenchmarkStateType + nextProps /*: BenchmarkPropsType */, + nextState /*: BenchmarkStateType */ ) { if (nextState.running && !this.state.running) { this._startTime = Timing.now() @@ -217,24 +216,24 @@ export default class Benchmark extends Component< } this._raf = window.requestAnimationFrame(() => { - this.setState((state: BenchmarkStateType) => ({ + this.setState((state /*: BenchmarkStateType */) => ({ cycle: state.cycle + 1, componentProps })) }) } - getSamples(): Array { + getSamples() /*: Array */ { return this._samples.reduce( ( - memo: Array, + memo /*: Array */, { scriptingStart, scriptingEnd, layoutStart, layoutEnd - }: SampleTimingType - ): Array => { + } /*: SampleTimingType */ + ) /*: Array */ => { memo.push({ start: scriptingStart, end: layoutEnd || scriptingEnd || 0, @@ -249,7 +248,7 @@ export default class Benchmark extends Component< ) } - _handleComplete(endTime: number) { + _handleComplete(endTime /*: number */) { const { onComplete } = this.props const samples = this.getSamples() diff --git a/scripts/benchmarks/src/app/Benchmark/math.js b/scripts/benchmarks/src/app/Benchmark/math.js index 210493026..65983e098 100644 --- a/scripts/benchmarks/src/app/Benchmark/math.js +++ b/scripts/benchmarks/src/app/Benchmark/math.js @@ -1,4 +1,3 @@ -// @flow import stats from 'stats-analysis' type ValuesType = Array diff --git a/scripts/benchmarks/src/app/Benchmark/timing.js b/scripts/benchmarks/src/app/Benchmark/timing.js index 297efcc17..1a7e19ecd 100644 --- a/scripts/benchmarks/src/app/Benchmark/timing.js +++ b/scripts/benchmarks/src/app/Benchmark/timing.js @@ -1,5 +1,3 @@ -// @flow - const NS_PER_MS = 1e6 const MS_PER_S = 1e3 diff --git a/scripts/benchmarks/src/app/Benchmark/types.js b/scripts/benchmarks/src/app/Benchmark/types.js index 8bbc5a233..abba17c3b 100644 --- a/scripts/benchmarks/src/app/Benchmark/types.js +++ b/scripts/benchmarks/src/app/Benchmark/types.js @@ -1,32 +1,30 @@ -/** - * @flow - */ - +/* export type FullSampleTimingType = { - start: number, - end: number, - scriptingStart: number, - scriptingEnd: number, - layoutStart?: number, + start: number + end: number + scriptingStart: number + scriptingEnd: number + layoutStart?: number layoutEnd?: number } export type BenchResultsType = { - startTime: number, - endTime: number, - runTime: number, - sampleCount: number, - samples: Array, - max: number, - min: number, - median: number, - mean: number, + startTime: number + endTime: number + runTime: number + sampleCount: number + samples: Array + max: number + min: number + median: number + mean: number stdDev: number } export type SampleTimingType = { - scriptingStart: number, - scriptingEnd?: number, - layoutStart?: number, + scriptingStart: number + scriptingEnd?: number + layoutStart?: number layoutEnd?: number } +*/ diff --git a/scripts/benchmarks/src/app/Button.js b/scripts/benchmarks/src/app/Button.js index 7ad43c7ab..c1cb5af22 100644 --- a/scripts/benchmarks/src/app/Button.js +++ b/scripts/benchmarks/src/app/Button.js @@ -2,7 +2,7 @@ import { StyleSheet, TouchableHighlight, Text } from 'react-native' import React, { Component } from 'react' import { bool, func, string } from 'prop-types' -export default class Button extends Component<*> { +export default class Button extends Component { static displayName = '@app/Button' static propTypes = { diff --git a/scripts/benchmarks/src/app/ReportCard.js b/scripts/benchmarks/src/app/ReportCard.js index 94a4826c3..112c63b0f 100644 --- a/scripts/benchmarks/src/app/ReportCard.js +++ b/scripts/benchmarks/src/app/ReportCard.js @@ -2,12 +2,12 @@ import Text from './Text' import { StyleSheet, View } from 'react-native' import React from 'react' -const fmt = (time: number) => { +const fmt = (time /*: number */) => { const i = Number(Math.round(time + 'e2') + 'e-2').toFixed(2) return 10 / i > 1 ? `0${i}` : i } -class ReportCard extends React.PureComponent<{||}> { +class ReportCard extends React.PureComponent { render() { const { benchmarkName, diff --git a/scripts/benchmarks/src/impl.js b/scripts/benchmarks/src/impl.js index 462fc463e..ef87f0bfb 100644 --- a/scripts/benchmarks/src/impl.js +++ b/scripts/benchmarks/src/impl.js @@ -1,24 +1,24 @@ -// @flow import * as React from 'react' -// $FlowFixMe let impls = require('./implementations/*/index.js') console.log(impls) +/* type ComponentsType = { - Box: React.ElementType, - Dot: React.ElementType, - Provider: React.ElementType, + Box: React.ElementType + Dot: React.ElementType + Provider: React.ElementType View: React.ElementType } type ImplementationType = { - components: ComponentsType, + components: ComponentsType name: string } +*/ -const implementations: Array = Object.keys(impls).map( +const implementations /*: Array */ = Object.keys(impls).map( name => { const components = impls[name] return { components, name } @@ -26,8 +26,8 @@ const implementations: Array = Object.keys(impls).map( ) const toObject = ( - impls: Array -): { [name: string]: ImplementationType } => + impls /*: Array */ +) /*: { [name: string]: ImplementationType } */ => impls.reduce((acc, impl) => { acc[impl.name] = impl return acc diff --git a/scripts/benchmarks/src/implementations/emotion-css-prop/Provider.js b/scripts/benchmarks/src/implementations/emotion-css-prop/Provider.js index a625d2e8a..f365483a2 100644 --- a/scripts/benchmarks/src/implementations/emotion-css-prop/Provider.js +++ b/scripts/benchmarks/src/implementations/emotion-css-prop/Provider.js @@ -1,4 +1,3 @@ -// @flow import * as React from 'react' import { CacheProvider } from '@emotion/react' import createCache from '@emotion/cache' diff --git a/scripts/benchmarks/src/implementations/emotion-styled/Provider.js b/scripts/benchmarks/src/implementations/emotion-styled/Provider.js index a625d2e8a..f365483a2 100644 --- a/scripts/benchmarks/src/implementations/emotion-styled/Provider.js +++ b/scripts/benchmarks/src/implementations/emotion-styled/Provider.js @@ -1,4 +1,3 @@ -// @flow import * as React from 'react' import { CacheProvider } from '@emotion/react' import createCache from '@emotion/cache' diff --git a/scripts/benchmarks/src/index.js b/scripts/benchmarks/src/index.js index fd8e61019..d8e6fa532 100644 --- a/scripts/benchmarks/src/index.js +++ b/scripts/benchmarks/src/index.js @@ -1,4 +1,3 @@ -// @flow import App from './app/App' import impl from './impl' import Tree from './cases/Tree' diff --git a/scripts/ssr-benchmarks/bench.js b/scripts/ssr-benchmarks/bench.js index 38fa20180..1512ff7e0 100644 --- a/scripts/ssr-benchmarks/bench.js +++ b/scripts/ssr-benchmarks/bench.js @@ -70,7 +70,6 @@ let CssFuncTriangle = createTriangle(({ x, y, size, color, ...props }) => { ...props }) }) -// $FlowFixMe let CacheContext = CacheProvider._context let hasOwnProperty = Object.prototype.hasOwnProperty diff --git a/scripts/test-utils/enzyme-env.js b/scripts/test-utils/enzyme-env.js index 69078bc17..88c8c3b32 100644 --- a/scripts/test-utils/enzyme-env.js +++ b/scripts/test-utils/enzyme-env.js @@ -1,4 +1,3 @@ -// @flow import Enzyme from 'enzyme' import Adapter from 'enzyme-adapter-react-16' diff --git a/scripts/test-utils/legacy-env.js b/scripts/test-utils/legacy-env.js index 21a64fb4c..6810e1cbc 100644 --- a/scripts/test-utils/legacy-env.js +++ b/scripts/test-utils/legacy-env.js @@ -1,7 +1,5 @@ -// @flow /* eslint-env jest */ import 'test-utils/enzyme-env' import { createEnzymeSerializer } from '@emotion/jest/enzyme' -// $FlowFixMe jest flow type definitions don't include new plugin API expect.addSnapshotSerializer(createEnzymeSerializer()) diff --git a/scripts/test-utils/next-env.js b/scripts/test-utils/next-env.js index c8cc86069..1ad269974 100644 --- a/scripts/test-utils/next-env.js +++ b/scripts/test-utils/next-env.js @@ -1,6 +1,4 @@ -// @flow /* eslint-env jest */ import { createSerializer } from '@emotion/jest' -// $FlowFixMe jest flow type definitions don't include new plugin API expect.addSnapshotSerializer(createSerializer()) diff --git a/scripts/test-utils/src/index.js b/scripts/test-utils/src/index.js index 4c019d9cc..70e862675 100644 --- a/scripts/test-utils/src/index.js +++ b/scripts/test-utils/src/index.js @@ -1,27 +1,24 @@ -// @flow /* eslint-env jest */ -export function throwIfFalsy(something: *) { +export function throwIfFalsy(something) { if (something) { return something } throw new Error('something is falsy') } -export function ignoreConsoleErrors(cb: () => mixed) { +export function ignoreConsoleErrors(cb /*: () => mixed */) { let oldConsoleError = console.error - // $FlowFixMe console.error = jest.fn() try { cb() } finally { - // $FlowFixMe console.error = oldConsoleError } } -export let safeQuerySelector = (selector: string): HTMLElement => { +export let safeQuerySelector = (selector /*: string */) /*: HTMLElement */ => { let element = document.querySelector(selector) if (!element) { throw new Error(`Could not find element matching selector "${selector}"`) diff --git a/site/plugins/gatsby-plugin-emotion-next-compat/gatsby-browser.js b/site/plugins/gatsby-plugin-emotion-next-compat/gatsby-browser.js index ceb042c3b..b40d2325d 100644 --- a/site/plugins/gatsby-plugin-emotion-next-compat/gatsby-browser.js +++ b/site/plugins/gatsby-plugin-emotion-next-compat/gatsby-browser.js @@ -1,4 +1,3 @@ -// @flow import * as React from 'react' import { cache } from '@emotion/css' import { CacheProvider } from '@emotion/react' diff --git a/site/plugins/gatsby-plugin-emotion-next-compat/gatsby-ssr.js b/site/plugins/gatsby-plugin-emotion-next-compat/gatsby-ssr.js index 13162e0f6..971116d9f 100644 --- a/site/plugins/gatsby-plugin-emotion-next-compat/gatsby-ssr.js +++ b/site/plugins/gatsby-plugin-emotion-next-compat/gatsby-ssr.js @@ -1,4 +1,3 @@ -// @flow import * as React from 'react' import { renderToString } from 'react-dom/server' import { extractCritical } from '@emotion/server' @@ -9,7 +8,7 @@ export const replaceRenderer = ({ replaceBodyHTMLString, bodyComponent, setHeadComponents -}: *) => { +}) => { let { html, ids, css } = extractCritical( renderToString({bodyComponent}) ) diff --git a/site/src/components/Box.js b/site/src/components/Box.js index c6f9966d3..3e3dca19c 100644 --- a/site/src/components/Box.js +++ b/site/src/components/Box.js @@ -1,4 +1,3 @@ -// @flow import styled from '@emotion/styled' import { space, @@ -36,6 +35,7 @@ const column = props => (props.column ? 'flex-direction:column;' : null) * ${justify}; * ` */ +/* type Props = $Shape<{ className: ?string, flex: number | string, @@ -47,7 +47,9 @@ type Props = $Shape<{ justify: string, align: string }> -const Box = styled.div( +*/ + +const Box = styled.div( display, space, width, diff --git a/site/src/components/DocMetadata.js b/site/src/components/DocMetadata.js index 248ff34f6..6d3181864 100644 --- a/site/src/components/DocMetadata.js +++ b/site/src/components/DocMetadata.js @@ -1,14 +1,14 @@ -// @flow import * as React from 'react' import { StaticQuery, graphql } from 'gatsby' +/* type Props = { render: ( data: Array<{ node: { frontmatter: { title: string - }, + } fields: { slug: string } @@ -16,8 +16,9 @@ type Props = { }> ) => React.Node } +*/ -const DocMetadata = (props: Props) => { +const DocMetadata = (props /*: Props */) => { return ( void -}) { +} */ +) { return (