Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Convert @emotion/cache's source code to TypeScript #3277

Merged
merged 12 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fluffy-garlics-smash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@emotion/cache': minor
---

Source code has been migrated to TypeScript. From now on type declarations will be emitted based on that, instead of being hand-written.
1 change: 1 addition & 0 deletions packages/cache/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
"devDependencies": {
"@definitelytyped/dtslint": "0.0.112",
"@emotion/hash": "*",
"@types/stylis": "^4.2.6",
"typescript": "^5.4.5"
},
"files": [
Expand Down
2 changes: 0 additions & 2 deletions packages/cache/src/index.d.ts

This file was deleted.

88 changes: 36 additions & 52 deletions packages/cache/src/index.js → packages/cache/src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { StyleSheet } from '@emotion/sheet'
/* import { type EmotionCache, type SerializedStyles } from '@emotion/utils' */
import { type EmotionCache, type SerializedStyles } from '@emotion/utils'
import {
serialize,
compile,
middleware,
rulesheet,
stringify,
COMMENT
COMMENT,
type Element as StylisElement
} from 'stylis'
import weakMemoize from '@emotion/weak-memoize'
import memoize from '@emotion/memoize'
Expand All @@ -19,32 +20,26 @@ import {
incorrectImportAlarm
} from './stylis-plugins'
import { prefixer } from './prefixer'
/* import type { StylisPlugin } from './types' */
import { StylisPlugin } from './types'

/*
export type Options = {
nonce?: string,
stylisPlugins?: StylisPlugin[],
key: string,
container?: HTMLElement,
speedy?: boolean,
prepend?: boolean,
export interface Options {
nonce?: string
stylisPlugins?: Array<StylisPlugin>
key: string
container?: Node
speedy?: boolean
/** @deprecate use `insertionPoint` instead */
prepend?: boolean
insertionPoint?: HTMLElement
}
*/

let getServerStylisCache = isBrowser
? undefined
: weakMemoize(() =>
memoize(() => {
let cache = {}
return name => cache[name]
Copy link
Member Author

Choose a reason for hiding this comment

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

funny thing, I think this was incorrect since #1817 . It was working because we were able to store properties on this function that was returned from here. We should be returning an object though. The caller is responsible both for reading and writing to this "cache"

})
)
: weakMemoize(() => memoize<Record<string, string>>(() => ({})))

const defaultStylisPlugins = [prefixer]

let getSourceMap
let getSourceMap: ((styles: string) => string | undefined) | undefined
if (isDevelopment) {
let sourceMapPattern =
/\/\*#\ssourceMappingURL=data:application\/json;\S+\s+\*\//g
Expand All @@ -55,7 +50,7 @@ if (isDevelopment) {
}
}

let createCache = (options /*: Options */) /*: EmotionCache */ => {
let createCache = (options: Options): EmotionCache => {
let key = options.key

if (isDevelopment && !key) {
Expand Down Expand Up @@ -100,18 +95,18 @@ let createCache = (options /*: Options */) /*: EmotionCache */ => {
)
}
}
let inserted = {}
let container /* : Node */
const nodesToHydrate = []
let inserted: EmotionCache['inserted'] = {}
let container: Node
const nodesToHydrate: HTMLStyleElement[] = []
if (isBrowser) {
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`).split(' ')
(node: HTMLStyleElement) => {
const attrib = node.getAttribute(`data-emotion`)!.split(' ')
for (let i = 1; i < attrib.length; i++) {
inserted[attrib[i]] = true
}
Expand All @@ -120,12 +115,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 (isDevelopment) {
Expand All @@ -139,13 +134,13 @@ let createCache = (options /*: Options */) /*: EmotionCache */ => {
)
}

if (isBrowser) {
let currentSheet
if (!getServerStylisCache) {
let currentSheet: Pick<StyleSheet, 'insert'>

const finalizingPlugins = [
stringify,
isDevelopment
? element => {
? (element: StylisElement) => {
if (!element.root) {
if (element.return) {
currentSheet.insert(element.return)
Expand All @@ -164,17 +159,12 @@ let createCache = (options /*: Options */) /*: EmotionCache */ => {
const serializer = middleware(
omnipresentPlugins.concat(stylisPlugins, finalizingPlugins)
)
const stylis = styles => serialize(compile(styles), serializer)
const stylis = (styles: string) => serialize(compile(styles), serializer)

insert = (
selector /*: string */,
serialized /*: SerializedStyles */,
sheet /*: StyleSheet */,
shouldCache /*: boolean */
) /*: void */ => {
insert = (selector, serialized, sheet, shouldCache) => {
currentSheet = sheet

if (isDevelopment) {
if (getSourceMap) {
let sourceMap = getSourceMap(serialized.styles)
if (sourceMap) {
currentSheet = {
Expand All @@ -196,13 +186,10 @@ let createCache = (options /*: Options */) /*: EmotionCache */ => {
const serializer = middleware(
omnipresentPlugins.concat(stylisPlugins, finalizingPlugins)
)
const stylis = styles => serialize(compile(styles), serializer)
const stylis = (styles: string) => serialize(compile(styles), serializer)

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(
Expand All @@ -211,12 +198,7 @@ let createCache = (options /*: Options */) /*: EmotionCache */ => {
}
return serverStylisCache[name]
}
insert = (
selector /*: string */,
serialized /*: SerializedStyles */,
sheet /*: StyleSheet */,
shouldCache /*: boolean */
) /*: string | void */ => {
insert = (selector, serialized, sheet, shouldCache) => {
let name = serialized.name
let rules = getRules(selector, serialized)
if (cache.compat === undefined) {
Expand All @@ -226,7 +208,7 @@ let createCache = (options /*: Options */) /*: EmotionCache */ => {
if (shouldCache) {
cache.inserted[name] = true
}
if (isDevelopment) {
if (getSourceMap) {
let sourceMap = getSourceMap(serialized.styles)
if (sourceMap) {
return rules + sourceMap
Expand All @@ -251,11 +233,11 @@ let createCache = (options /*: Options */) /*: EmotionCache */ => {
}
}

const cache /*: EmotionCache */ = {
const cache: EmotionCache = {
key,
sheet: new StyleSheet({
key,
container,
container: container!,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
Expand All @@ -273,3 +255,5 @@ let createCache = (options /*: Options */) /*: EmotionCache */ => {
}

export default createCache
export { EmotionCache }
export type { StylisElement, StylisPlugin, StylisPluginCallback } from './types'
20 changes: 15 additions & 5 deletions packages/cache/src/prefixer.js → packages/cache/src/prefixer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import {
charat,
combine,
copy,
copy as _copy,
DECLARATION,
hash,
indexof,
Expand All @@ -15,12 +15,17 @@ import {
RULESET,
serialize,
strlen,
WEBKIT
WEBKIT,
type Element,
Middleware
} from 'stylis'

// `@types/stylis` are inaccurate, so we temporarily cast to our own definitions until fix lands: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/71310
const copy: (root: Element, props: Partial<Element>) => Element = _copy as any

// this is a copy of [email protected] prefixer, the latter version introduced grid prefixing which we don't want

function prefix(value, length) {
function prefix(value: string, length: number): string {
switch (hash(value, length)) {
// color-adjust
case 5103:
Expand Down Expand Up @@ -279,7 +284,12 @@ function prefix(value, length) {
return value
}

export let prefixer = (element, index, children, callback) => {
export let prefixer = (
element: Element,
index: number,
children: Element[],
callback: Middleware
) => {
if (element.length > -1)
if (!element.return)
switch (element.type) {
Expand All @@ -297,7 +307,7 @@ export let prefixer = (element, index, children, callback) => {
)
case RULESET:
if (element.length)
return combine(element.props, function (value) {
return combine(element.props as string[], function (value) {
switch (match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only':
Expand Down
Loading
Loading