@cfp-studio/plugin-react 17.1.0 → 17.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -0
- package/dist/index.d.mts +5760 -4
- package/dist/index.mjs +1 -141
- package/package.json +41 -18
- package/preview/index.tsx +0 -1
- package/preview/root.ts +0 -1
- package/preview/tsconfig.json +9 -9
- package/types/csstype/LICENSE +19 -0
- package/types/csstype/README.md +277 -0
- package/types/csstype/index.d.ts +21297 -0
- package/types/csstype/index.js.flow +6612 -0
- package/types/csstype/package.json +66 -0
- package/types/prop-types/LICENSE +21 -0
- package/types/prop-types/README.md +15 -0
- package/types/prop-types/index.d.ts +131 -0
- package/types/prop-types/package.json +36 -0
- package/types/react/LICENSE +21 -0
- package/types/react/README.md +15 -0
- package/types/react/canary.d.ts +166 -0
- package/types/react/experimental.d.ts +132 -0
- package/types/react/global.d.ts +160 -0
- package/types/react/index.d.ts +4553 -0
- package/types/react/jsx-dev-runtime.d.ts +45 -0
- package/types/react/jsx-runtime.d.ts +36 -0
- package/types/react/package.json +206 -0
- package/types/react/ts5.0/canary.d.ts +166 -0
- package/types/react/ts5.0/experimental.d.ts +132 -0
- package/types/react/ts5.0/global.d.ts +160 -0
- package/types/react/ts5.0/index.d.ts +4540 -0
- package/types/react/ts5.0/jsx-dev-runtime.d.ts +44 -0
- package/types/react/ts5.0/jsx-runtime.d.ts +35 -0
- package/types/react-dom/LICENSE +21 -0
- package/types/react-dom/README.md +16 -0
- package/types/react-dom/canary.d.ts +184 -0
- package/types/react-dom/client.d.ts +72 -0
- package/types/react-dom/experimental.d.ts +36 -0
- package/types/react-dom/index.d.ts +150 -0
- package/types/react-dom/package.json +88 -0
- package/types/react-dom/server.d.ts +126 -0
- package/types/react-dom/test-utils/index.d.ts +402 -0
- package/dist/index.d.ts +0 -12
package/dist/index.mjs
CHANGED
|
@@ -1,141 +1 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import react from '@vitejs/plugin-react';
|
|
3
|
-
import { polyfillNode } from 'esbuild-plugin-polyfill-node';
|
|
4
|
-
import path from 'node:path';
|
|
5
|
-
import url from 'node:url';
|
|
6
|
-
|
|
7
|
-
const reactImportRegExp = /import (\* as )?React[ ,]/;
|
|
8
|
-
function reactImportsPlugin() {
|
|
9
|
-
return {
|
|
10
|
-
/**
|
|
11
|
-
* 插件名称,用于在 Vite 构建过程中标识此插件。
|
|
12
|
-
*/
|
|
13
|
-
name: "previewjs:react-js-imports",
|
|
14
|
-
/**
|
|
15
|
-
* 转换钩子,在 Vite 处理模块时调用。
|
|
16
|
-
*
|
|
17
|
-
* @param code - 模块的原始代码。
|
|
18
|
-
* @param id - 模块的唯一标识符,通常是文件路径。
|
|
19
|
-
* @returns 返回转换后的代码,如果不需要转换则返回原始代码。
|
|
20
|
-
*/
|
|
21
|
-
async transform(code, id) {
|
|
22
|
-
if (id.includes("node_modules") || path.extname(id) !== ".js" || reactImportRegExp.test(code)) {
|
|
23
|
-
return code;
|
|
24
|
-
}
|
|
25
|
-
return `import React from 'react';${code}`;
|
|
26
|
-
}
|
|
27
|
-
};
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
const reactFrameworkPlugin = {
|
|
31
|
-
/**
|
|
32
|
-
* 插件的基本信息
|
|
33
|
-
*/
|
|
34
|
-
info: {
|
|
35
|
-
/**
|
|
36
|
-
* 插件的 API 版本
|
|
37
|
-
*/
|
|
38
|
-
apiVersion: 5,
|
|
39
|
-
/**
|
|
40
|
-
* 插件的名称
|
|
41
|
-
*/
|
|
42
|
-
name: "@cfp-studio/plugin-react"
|
|
43
|
-
},
|
|
44
|
-
/**
|
|
45
|
-
* 检查当前项目是否与该插件兼容
|
|
46
|
-
* @param dependencies - 项目依赖项对象
|
|
47
|
-
* @returns 如果兼容返回 true,否则返回 false
|
|
48
|
-
*/
|
|
49
|
-
isCompatible: async (dependencies) => {
|
|
50
|
-
const version = await dependencies.react?.readInstalledVersion();
|
|
51
|
-
if (!version) {
|
|
52
|
-
return false;
|
|
53
|
-
}
|
|
54
|
-
const [major, minor] = version.split(".").map((n) => Number.parseInt(n));
|
|
55
|
-
if (Number.isNaN(major) || Number.isNaN(minor)) {
|
|
56
|
-
return false;
|
|
57
|
-
}
|
|
58
|
-
return major >= 17 || major === 16 && minor >= 14;
|
|
59
|
-
},
|
|
60
|
-
/**
|
|
61
|
-
* 创建插件实例
|
|
62
|
-
* @param param0 - 包含根目录、读取器、日志记录器和依赖项的对象
|
|
63
|
-
* @returns 插件实例对象
|
|
64
|
-
*/
|
|
65
|
-
async create({ rootDir, reader, logger, dependencies }) {
|
|
66
|
-
const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
|
|
67
|
-
const analyzerPlugin = createAnalyzer({
|
|
68
|
-
rootDir,
|
|
69
|
-
reader,
|
|
70
|
-
logger
|
|
71
|
-
});
|
|
72
|
-
const previewDirPath = path.join(__dirname, "..", "preview");
|
|
73
|
-
return {
|
|
74
|
-
// 默认的包装器文件路径
|
|
75
|
-
defaultWrapperPath: "__previewjs__/Wrapper.tsx",
|
|
76
|
-
// 预览目录的路径
|
|
77
|
-
previewDirPath,
|
|
78
|
-
// 展开分析器插件实例的属性
|
|
79
|
-
...analyzerPlugin,
|
|
80
|
-
/**
|
|
81
|
-
* 配置 Vite 的配置选项
|
|
82
|
-
* @param configuredPlugins - 已配置的 Vite 插件数组
|
|
83
|
-
* @returns Vite 配置对象
|
|
84
|
-
*/
|
|
85
|
-
viteConfig: (configuredPlugins) => {
|
|
86
|
-
const hasReactPlugin = configuredPlugins.find(
|
|
87
|
-
(plugin) => plugin.name.startsWith("vite:react-")
|
|
88
|
-
);
|
|
89
|
-
return {
|
|
90
|
-
// 优化依赖项的配置
|
|
91
|
-
optimizeDeps: {
|
|
92
|
-
esbuildOptions: {
|
|
93
|
-
// 如果项目依赖中包含 next,则添加 polyfillNode 插件
|
|
94
|
-
plugins: dependencies.next ? [polyfillNode()] : []
|
|
95
|
-
}
|
|
96
|
-
},
|
|
97
|
-
// 路径解析配置
|
|
98
|
-
resolve: {
|
|
99
|
-
alias: {
|
|
100
|
-
// 将 react-native 别名映射到 react-native-web
|
|
101
|
-
"react-native": "react-native-web"
|
|
102
|
-
}
|
|
103
|
-
},
|
|
104
|
-
// Vite 插件数组
|
|
105
|
-
plugins: [
|
|
106
|
-
// 添加 reactImportsPlugin 插件
|
|
107
|
-
reactImportsPlugin(),
|
|
108
|
-
// 展开已配置的插件
|
|
109
|
-
...configuredPlugins,
|
|
110
|
-
// 如果已配置的插件中不包含 Vite 的 React 插件,则添加 react 插件
|
|
111
|
-
...!hasReactPlugin ? [react()] : [],
|
|
112
|
-
{
|
|
113
|
-
// 插件名称
|
|
114
|
-
name: "previewjs:update-react-import",
|
|
115
|
-
/**
|
|
116
|
-
* 转换代码的钩子函数
|
|
117
|
-
* @param code - 要转换的代码
|
|
118
|
-
* @param id - 文件的 ID
|
|
119
|
-
* @returns 转换后的代码,如果不需要转换则返回 undefined
|
|
120
|
-
*/
|
|
121
|
-
async transform(code, id) {
|
|
122
|
-
if (!id.endsWith("__previewjs_internal__/renderer/index.tsx")) {
|
|
123
|
-
return;
|
|
124
|
-
}
|
|
125
|
-
const reactVersion = Number.parseInt(
|
|
126
|
-
await dependencies.react?.readInstalledVersion() || "0"
|
|
127
|
-
);
|
|
128
|
-
return code.replace(
|
|
129
|
-
/__PREVIEWJS_PLUGIN_REACT_IMPORT_PATH__/g,
|
|
130
|
-
reactVersion >= 18 ? "./render-18" : "./render-16"
|
|
131
|
-
);
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
]
|
|
135
|
-
};
|
|
136
|
-
}
|
|
137
|
-
};
|
|
138
|
-
}
|
|
139
|
-
};
|
|
140
|
-
|
|
141
|
-
export { reactFrameworkPlugin as default };
|
|
1
|
+
import{factoryWithDefaultOptions as e}from"@cfp-studio/analyzer-api/factory";import{EMPTY_OBJECT_TYPE as t,NODE_TYPE as n,UNKNOWN_TYPE as r,arrayType as i,createTypeAnalyzer as a,dereferenceType as o,functionType as s,helpers as c,maybeOptionalType as l,objectType as u,stripUnusedTypes as d}from"@cfp-studio/type-analyzer";import{createFileSystemReader as f,createStackedReader as p}from"@cfp-studio/vfs";import m from"node:fs";import h from"node:path";import g from"typescript";import _ from"node:url";import{decodePreviewableId as v,generatePreviewableId as y}from"@cfp-studio/analyzer-api";import{parseSerializableValue as b}from"@cfp-studio/serializable-values";import{extractArgs as x,extractCsf3Stories as S,extractStoriesInfo as C,resolvePreviewableId as w}from"@cfp-studio/storybook-helpers";import T from"@vitejs/plugin-react";import{polyfillNode as E}from"esbuild-plugin-polyfill-node";function D(e,t){for(let n of e.statements)if(g.isExpressionStatement(n)&&g.isBinaryExpression(n.expression)&&n.expression.operatorToken.kind===g.SyntaxKind.EqualsToken&&g.isPropertyAccessExpression(n.expression.left)&&g.isIdentifier(n.expression.left.expression)){if(n.expression.left.expression.text!==t)continue;if(n.expression.left.name.text===`propTypes`)return n.expression.right}else if(g.isClassDeclaration(n)&&n.name){if(n.name.text!==t)continue;for(let e of n.members)if(g.isPropertyDeclaration(e)&&e.initializer&&e.name.getText()===`propTypes`)return e.initializer}return null}function O(e,t,n,r,i){let a=t.sourceFile(n),o=null;a&&(o=D(a,r));let s=null;return s=o?A(t,o):k(e,t,i),{props:s.type,types:{...s.collected}}}function k(e,n,i){let a=i.getParameters()[0];if(!a)return{type:t,collected:{}};if(!a.valueDeclaration)return{type:r,collected:{}};let s=n.checker.getTypeOfSymbolAtLocation(a,a.valueDeclaration);try{let{type:e,collected:t}=n.resolveType(s);if([e]=o(e,t,[]),e.kind===`object`&&g.isParameter(a.valueDeclaration)&&g.isObjectBindingPattern(a.valueDeclaration.name)){let t=a.valueDeclaration.name,n=new Set,r=new Set,i=!1;for(let e of t.elements){if(e.dotDotDotToken){i=!0;break}let t=e.propertyName||e.name;if(!g.isIdentifier(t)){i=!0;break}n.add(t.text),e.initializer&&r.add(t.text)}i||(e=u(Object.fromEntries(Object.entries(e.fields).filter(([e])=>n.has(e)).map(([e,t])=>[e,l(t,r.has(e))]))))}return{type:e,collected:t}}catch(t){e.warn(`Unable to resolve props type for ${n.checker.typeToString(s)}`),e.error(t.toString())}return{type:r,collected:{}}}function A(e,t){let n=e.checker.getTypeAtLocation(t),i={},a={};for(let t of n.getProperties())i[t.name]=(()=>{if(!t.valueDeclaration)return r;let n=e.checker.getTypeAtLocation(t.valueDeclaration),i=e.resolveTypeArguments(n),o=i.types[0];return o?(a={...a,...i.collected},l(o,n.symbol.name===`Requireable`)):r})();let o=u(i);return{type:o,collected:d(a,[o])}}async function j(e,t,n,i){let a=t.sourceFile(i);if(!a)return[];let o=[];for(let e of a.statements)if(g.isExportAssignment(e)){if(g.isIdentifier(e.expression))continue;o.push([`default`,e,e.expression])}else if(g.isVariableStatement(e))for(let t of e.declarationList.declarations)!g.isIdentifier(t.name)||!t.initializer||o.push([t.name.text,e,t.initializer]);else if(g.isFunctionDeclaration(e)){let t=!!e.modifiers?.find(e=>e.kind===g.SyntaxKind.ExportKeyword)&&!!e.modifiers?.find(e=>e.kind===g.SyntaxKind.DefaultKeyword),n=e.name?.text;(t||n)&&o.push([n||`default`,e,e])}else g.isClassDeclaration(e)&&e.name&&o.push([e.name.text,e,e]);let s=C(a);e.debug(`**storiresInfo: ${s}`);let l=[],u=x(a),d=c.extractExportedNames(a);async function f(r,a,o){if(o===`default`&&s)return null;let c=u[o],l=o===`default`||!!d[o],f=N(t.checker,a);if(s&&l&&(c||f?.parameters.length===0)){let i=M(e,t,n,s.component);return{...r,analyze:async()=>({args:c?{sourcePosition:{start:c.getStart(),end:c.getEnd()},value:await b(c)}:null}),associatedComponent:i}}return f?{...r,exported:l,analyze:async()=>O(e,t,i,o,f)}:null}for(let[e,t,r]of o){let a=await f({id:y({filePath:h.relative(n,i),name:e}),sourcePosition:{start:t.getStart(),end:t.getEnd()}},r,e);a&&l.push(a)}return[...l,...await S(n,t,a,async i=>{let{filePath:a}=v(i),o=(await j(e,t,n,h.join(n,a))).find(e=>e.id===i);return!o||!(`exported`in o)?{props:r,types:{}}:o.analyze()})]}function M(e,t,n,i){let a=w(n,t.checker,i);return i&&a?{id:a,analyze:async()=>{let o=N(t.checker,i);if(!o)return{props:r,types:{}};let{filePath:s,name:c}=v(a);return O(e,t,h.join(n,s),c,o)}}:null}function N(e,t){let n=e.getTypeAtLocation(t);if(n.flags===g.TypeFlags.Any&&g.isCallExpression(t)&&g.isPropertyAccessExpression(t.expression)&&g.isIdentifier(t.expression.name)&&t.expression.name.text===`bind`){let r=e.getSymbolAtLocation(t.expression.expression);r?.valueDeclaration&&g.isVariableDeclaration(r.valueDeclaration)&&r.valueDeclaration.initializer&&(n=e.getTypeAtLocation(r.valueDeclaration.initializer))}for(let e of n.getCallSignatures())if(P(e.getReturnType()))return e;if(n.symbol){let r=e.getTypeOfSymbolAtLocation(n.symbol,t);for(let e of r.getConstructSignatures())if(e.getReturnType().getProperty(`render`))return e}return null}function P(e){return!!I(e)}const F=new Set([`Element`,`ReactElement`]);function I(e){if(e.isUnion()){for(let t of e.types)if(I(t))return!0}return F.has(e.symbol?.getEscapedName().toString())}const L={Component:n,ComponentClass:s(n),FunctionComponent:s(n),ReactElement:n,ReactNode:n,ReactNodeArray:i(n),ReactPortal:n},R=e(({rootDir:e,reader:t,logger:n})=>{let r=_.fileURLToPath(new URL(`.`,import.meta.url)),i=h.join(r,`..`,`types`),o=h.join(r,`..`,`node_modules`),s=m.existsSync(i)?i:o,c=a({reader:p([t,f({mapping:{from:s,to:h.join(e,`node_modules`)},watch:!1}),...s===i?[f({mapping:{from:i,to:h.join(e,`node_modules`,`@types`)},watch:!1})]:[]]),rootDir:e,specialTypes:L,tsCompilerOptions:{jsx:g.JsxEmit.ReactJSX,jsxImportSource:`react`},warn:n.warn.bind(n)});return{typeAnalyzer:c,crawlFiles:async t=>{let r=t.map(t=>h.isAbsolute(t)?t:h.join(e,t)),i=c.analyze(r),a=[],o=[];for(let t of r)for(let r of await j(n,i,e,t))`exported`in r?a.push(r):o.push(r);return{components:a,stories:o}},dispose:()=>{c.dispose()}}}),z=/import (\* as )?React[ ,]/;function B(){return{name:`previewjs:react-js-imports`,async transform(e,t){return t.includes(`node_modules`)||h.extname(t)!==`.js`||z.test(e)?e:`import React from 'react';${e}`}}}const V={info:{apiVersion:5,name:`@cfp-studio/plugin-react`},isCompatible:async e=>{let t=await e.react?.readInstalledVersion();if(!t)return!1;let[n,r]=t.split(`.`).map(e=>Number.parseInt(e));return Number.isNaN(n)||Number.isNaN(r)?!1:n>=17||n===16&&r>=14},async create({rootDir:e,reader:t,logger:n,dependencies:r}){let i=_.fileURLToPath(new URL(`.`,import.meta.url)),a=R({rootDir:e,reader:t,logger:n});return{defaultWrapperPath:`__previewjs__/Wrapper.tsx`,previewDirPath:h.join(i,`..`,`preview`),...a,viteConfig:e=>{let t=e.find(e=>e.name.startsWith(`vite:react-`));return{optimizeDeps:{esbuildOptions:{plugins:r.next?[E()]:[]}},resolve:{alias:{"react-native":`react-native-web`}},plugins:[B(),...e,...t?[]:[T()],{name:`previewjs:update-react-import`,async transform(e,t){if(!t.endsWith(`__previewjs_internal__/renderer/index.tsx`))return;let n=Number.parseInt(await r.react?.readInstalledVersion()||`0`);return e.replace(/__PREVIEWJS_PLUGIN_REACT_IMPORT_PATH__/g,n>=18?`./render-18`:`./render-16`)}}]}}}}};export{V as default};
|
package/package.json
CHANGED
|
@@ -1,35 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cfp-studio/plugin-react",
|
|
3
|
-
"version": "17.1
|
|
3
|
+
"version": "17.2.1",
|
|
4
4
|
"license": "MIT",
|
|
5
|
-
"sideEffects": false,
|
|
6
|
-
"type": "module",
|
|
7
|
-
"main": "./dist/index.mjs",
|
|
8
|
-
"types": "./dist/index.d.ts",
|
|
9
5
|
"files": [
|
|
10
6
|
"dist",
|
|
11
|
-
"preview"
|
|
7
|
+
"preview",
|
|
8
|
+
"types"
|
|
12
9
|
],
|
|
10
|
+
"type": "module",
|
|
11
|
+
"sideEffects": false,
|
|
12
|
+
"main": "./dist/index.mjs",
|
|
13
|
+
"types": "./dist/index.d.mts",
|
|
13
14
|
"dependencies": {
|
|
14
|
-
"@cfp-studio/analyzer-react": "^0.1.11",
|
|
15
15
|
"@vitejs/plugin-react": "4.3.4",
|
|
16
|
-
"esbuild-plugin-polyfill-node": "0.3.0"
|
|
16
|
+
"esbuild-plugin-polyfill-node": "0.3.0",
|
|
17
|
+
"typescript": "5.9.3",
|
|
18
|
+
"@cfp-studio/analyzer-api": "0.1.12",
|
|
19
|
+
"@cfp-studio/type-analyzer": "10.1.8",
|
|
20
|
+
"@cfp-studio/vfs": "2.1.6",
|
|
21
|
+
"@cfp-studio/storybook-helpers": "6.0.2",
|
|
22
|
+
"@cfp-studio/serializable-values": "9.0.8"
|
|
17
23
|
},
|
|
18
24
|
"devDependencies": {
|
|
19
|
-
"@playwright/test": "1.
|
|
25
|
+
"@playwright/test": "1.64.1",
|
|
26
|
+
"@types/prop-types": "15.7.15",
|
|
20
27
|
"@types/react": "18.3.18",
|
|
21
28
|
"@types/react-dom": "18.3.5",
|
|
22
|
-
"
|
|
23
|
-
"pino
|
|
24
|
-
"
|
|
25
|
-
"
|
|
29
|
+
"csstype": "3.1.3",
|
|
30
|
+
"pino": "9.11.0",
|
|
31
|
+
"pino-pretty": "11.3.0",
|
|
32
|
+
"react": "18.3.1",
|
|
33
|
+
"react-dom": "18.3.1",
|
|
34
|
+
"vite": "6.4.5",
|
|
35
|
+
"vitest": "5.0.5",
|
|
36
|
+
"@cfp-studio/iframe": "18.2.0",
|
|
26
37
|
"@cfp-studio/testing": "14.0.1",
|
|
27
|
-
"@cfp-studio/
|
|
28
|
-
|
|
29
|
-
|
|
38
|
+
"@cfp-studio/core": "1.0.6"
|
|
39
|
+
},
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=20"
|
|
42
|
+
},
|
|
43
|
+
"cfp": {
|
|
44
|
+
"domain": "web-preview",
|
|
45
|
+
"layer": "analysis"
|
|
30
46
|
},
|
|
31
47
|
"scripts": {
|
|
32
|
-
"build": "
|
|
33
|
-
"
|
|
48
|
+
"build": "node scripts/prepare-types.mjs && tsdown",
|
|
49
|
+
"release": "node scripts/prepare-types.mjs && tsdown --minify",
|
|
50
|
+
"prepare:types": "node scripts/prepare-types.mjs",
|
|
51
|
+
"typecheck": "tsc --noEmit && tsc -p preview/tsconfig.json",
|
|
52
|
+
"test": "node scripts/prepare-types.mjs && vitest run",
|
|
53
|
+
"test:watch": "vitest watch",
|
|
54
|
+
"e2e-test": "pnpm --dir tests/apps/react16 install --ignore-workspace --ignore-scripts && pnpm --dir tests/apps/react17 install --ignore-workspace --ignore-scripts && pnpm --dir tests/apps/react18 install --ignore-workspace --ignore-scripts && pnpm --dir tests/apps/react-sass install --ignore-workspace --ignore-scripts && playwright test",
|
|
55
|
+
"lint": "oxlint",
|
|
56
|
+
"format": "oxfmt --write ."
|
|
34
57
|
}
|
|
35
58
|
}
|
package/preview/index.tsx
CHANGED
|
@@ -47,7 +47,6 @@ export const loadRenderer: RendererLoader = async ({
|
|
|
47
47
|
previewableModule.default?.component ||
|
|
48
48
|
Previewable
|
|
49
49
|
: Previewable;
|
|
50
|
-
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
|
|
51
50
|
const Renderer = (props: any) => {
|
|
52
51
|
return (
|
|
53
52
|
<ErrorBoundary renderId={renderId}>
|
package/preview/root.ts
CHANGED
package/preview/tsconfig.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
{
|
|
2
|
-
"extends": "
|
|
3
|
-
"compilerOptions": {
|
|
4
|
-
"module": "ES2022",
|
|
5
|
-
"moduleResolution": "Bundler",
|
|
6
|
-
"jsx": "preserve"
|
|
7
|
-
},
|
|
8
|
-
"exclude": ["types"]
|
|
9
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"extends": "../../../../../tsconfig.base.json",
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"module": "ES2022",
|
|
5
|
+
"moduleResolution": "Bundler",
|
|
6
|
+
"jsx": "preserve"
|
|
7
|
+
},
|
|
8
|
+
"exclude": ["types"]
|
|
9
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Copyright (c) 2017-2018 Fredrik Nicol
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
in the Software without restriction, including without limitation the rights
|
|
6
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
copies or substantial portions of the Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
SOFTWARE.
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
# CSSType
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/csstype)
|
|
4
|
+
|
|
5
|
+
TypeScript and Flow definitions for CSS, generated by [data from MDN](https://github.com/mdn/data). It provides autocompletion and type checking for CSS properties and values.
|
|
6
|
+
|
|
7
|
+
**TypeScript**
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import type * as CSS from 'csstype';
|
|
11
|
+
|
|
12
|
+
const style: CSS.Properties = {
|
|
13
|
+
colour: 'white', // Type error on property
|
|
14
|
+
textAlign: 'middle', // Type error on value
|
|
15
|
+
};
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
**Flow**
|
|
19
|
+
|
|
20
|
+
```js
|
|
21
|
+
// @flow strict
|
|
22
|
+
import * as CSS from 'csstype';
|
|
23
|
+
|
|
24
|
+
const style: CSS.Properties<> = {
|
|
25
|
+
colour: 'white', // Type error on property
|
|
26
|
+
textAlign: 'middle', // Type error on value
|
|
27
|
+
};
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
_Further examples below will be in TypeScript!_
|
|
31
|
+
|
|
32
|
+
## Getting started
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
$ npm install csstype
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Table of content
|
|
39
|
+
|
|
40
|
+
- [Style types](#style-types)
|
|
41
|
+
- [At-rule types](#at-rule-types)
|
|
42
|
+
- [Pseudo types](#pseudo-types)
|
|
43
|
+
- [Generics](#generics)
|
|
44
|
+
- [Usage](#usage)
|
|
45
|
+
- [What should I do when I get type errors?](#what-should-i-do-when-i-get-type-errors)
|
|
46
|
+
- [Version 3.0](#version-30)
|
|
47
|
+
- [Contributing](#contributing)
|
|
48
|
+
|
|
49
|
+
## Style types
|
|
50
|
+
|
|
51
|
+
Properties are categorized in different uses and in several technical variations to provide typings that suits as many as possible.
|
|
52
|
+
|
|
53
|
+
| | Default | `Hyphen` | `Fallback` | `HyphenFallback` |
|
|
54
|
+
| -------------- | -------------------- | -------------------------- | ---------------------------- | ---------------------------------- |
|
|
55
|
+
| **All** | `Properties` | `PropertiesHyphen` | `PropertiesFallback` | `PropertiesHyphenFallback` |
|
|
56
|
+
| **`Standard`** | `StandardProperties` | `StandardPropertiesHyphen` | `StandardPropertiesFallback` | `StandardPropertiesHyphenFallback` |
|
|
57
|
+
| **`Vendor`** | `VendorProperties` | `VendorPropertiesHyphen` | `VendorPropertiesFallback` | `VendorPropertiesHyphenFallback` |
|
|
58
|
+
| **`Obsolete`** | `ObsoleteProperties` | `ObsoletePropertiesHyphen` | `ObsoletePropertiesFallback` | `ObsoletePropertiesHyphenFallback` |
|
|
59
|
+
| **`Svg`** | `SvgProperties` | `SvgPropertiesHyphen` | `SvgPropertiesFallback` | `SvgPropertiesHyphenFallback` |
|
|
60
|
+
|
|
61
|
+
Categories:
|
|
62
|
+
|
|
63
|
+
- **All** - Includes `Standard`, `Vendor`, `Obsolete` and `Svg`
|
|
64
|
+
- **`Standard`** - Current properties and extends subcategories `StandardLonghand` and `StandardShorthand` _(e.g. `StandardShorthandProperties`)_
|
|
65
|
+
- **`Vendor`** - Vendor prefixed properties and extends subcategories `VendorLonghand` and `VendorShorthand` _(e.g. `VendorShorthandProperties`)_
|
|
66
|
+
- **`Obsolete`** - Removed or deprecated properties
|
|
67
|
+
- **`Svg`** - SVG-specific properties
|
|
68
|
+
|
|
69
|
+
Variations:
|
|
70
|
+
|
|
71
|
+
- **Default** - JavaScript (camel) cased property names
|
|
72
|
+
- **`Hyphen`** - CSS (kebab) cased property names
|
|
73
|
+
- **`Fallback`** - Also accepts array of values e.g. `string | string[]`
|
|
74
|
+
|
|
75
|
+
## At-rule types
|
|
76
|
+
|
|
77
|
+
At-rule interfaces with descriptors.
|
|
78
|
+
|
|
79
|
+
**TypeScript**: These will be found in the `AtRule` namespace, e.g. `AtRule.Viewport`.
|
|
80
|
+
**Flow**: These will be prefixed with `AtRule$`, e.g. `AtRule$Viewport`.
|
|
81
|
+
|
|
82
|
+
| | Default | `Hyphen` | `Fallback` | `HyphenFallback` |
|
|
83
|
+
| -------------------- | -------------- | -------------------- | ---------------------- | ---------------------------- |
|
|
84
|
+
| **`@counter-style`** | `CounterStyle` | `CounterStyleHyphen` | `CounterStyleFallback` | `CounterStyleHyphenFallback` |
|
|
85
|
+
| **`@font-face`** | `FontFace` | `FontFaceHyphen` | `FontFaceFallback` | `FontFaceHyphenFallback` |
|
|
86
|
+
| **`@viewport`** | `Viewport` | `ViewportHyphen` | `ViewportFallback` | `ViewportHyphenFallback` |
|
|
87
|
+
|
|
88
|
+
## Pseudo types
|
|
89
|
+
|
|
90
|
+
String literals of pseudo classes and pseudo elements
|
|
91
|
+
|
|
92
|
+
- `Pseudos`
|
|
93
|
+
|
|
94
|
+
Extends:
|
|
95
|
+
|
|
96
|
+
- `AdvancedPseudos`
|
|
97
|
+
|
|
98
|
+
Function-like pseudos e.g. `:not(:first-child)`. The string literal contains the value excluding the parenthesis: `:not`. These are separated because they require an argument that results in infinite number of variations.
|
|
99
|
+
|
|
100
|
+
- `SimplePseudos`
|
|
101
|
+
|
|
102
|
+
Plain pseudos e.g. `:hover` that can only be **one** variation.
|
|
103
|
+
|
|
104
|
+
## Generics
|
|
105
|
+
|
|
106
|
+
All interfaces has two optional generic argument to define length and time: `CSS.Properties<TLength = string | 0, TTime = string>`
|
|
107
|
+
|
|
108
|
+
- **Length** is the first generic parameter and defaults to `string | 0` because `0` is the only [length where the unit identifier is optional](https://drafts.csswg.org/css-values-3/#lengths). You can specify this, e.g. `string | number`, for platforms and libraries that accepts any numeric value as length with a specific unit.
|
|
109
|
+
```tsx
|
|
110
|
+
const style: CSS.Properties<string | number> = {
|
|
111
|
+
width: 100,
|
|
112
|
+
};
|
|
113
|
+
```
|
|
114
|
+
- **Time** is the second generic argument and defaults to `string`. You can specify this, e.g. `string | number`, for platforms and libraries that accepts any numeric value as length with a specific unit.
|
|
115
|
+
```tsx
|
|
116
|
+
const style: CSS.Properties<string | number, number> = {
|
|
117
|
+
transitionDuration: 1000,
|
|
118
|
+
};
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Usage
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
import type * as CSS from 'csstype';
|
|
125
|
+
|
|
126
|
+
const style: CSS.Properties = {
|
|
127
|
+
width: '10px',
|
|
128
|
+
margin: '1em',
|
|
129
|
+
};
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
In some cases, like for CSS-in-JS libraries, an array of values is a way to provide fallback values in CSS. Using `CSS.PropertiesFallback` instead of `CSS.Properties` will add the possibility to use any property value as an array of values.
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
import type * as CSS from 'csstype';
|
|
136
|
+
|
|
137
|
+
const style: CSS.PropertiesFallback = {
|
|
138
|
+
display: ['-webkit-flex', 'flex'],
|
|
139
|
+
color: 'white',
|
|
140
|
+
};
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
There's even string literals for pseudo selectors and elements.
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
import type * as CSS from 'csstype';
|
|
147
|
+
|
|
148
|
+
const pseudos: { [P in CSS.SimplePseudos]?: CSS.Properties } = {
|
|
149
|
+
':hover': {
|
|
150
|
+
display: 'flex',
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Hyphen cased (kebab cased) properties are provided in `CSS.PropertiesHyphen` and `CSS.PropertiesHyphenFallback`. It's not **not** added by default in `CSS.Properties`. To allow both of them, you can simply extend with `CSS.PropertiesHyphen` or/and `CSS.PropertiesHyphenFallback`.
|
|
156
|
+
|
|
157
|
+
```ts
|
|
158
|
+
import type * as CSS from 'csstype';
|
|
159
|
+
|
|
160
|
+
interface Style extends CSS.Properties, CSS.PropertiesHyphen {}
|
|
161
|
+
|
|
162
|
+
const style: Style = {
|
|
163
|
+
'flex-grow': 1,
|
|
164
|
+
'flex-shrink': 0,
|
|
165
|
+
'font-weight': 'normal',
|
|
166
|
+
backgroundColor: 'white',
|
|
167
|
+
};
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
Adding type checked CSS properties to a `HTMLElement`.
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
import type * as CSS from 'csstype';
|
|
174
|
+
|
|
175
|
+
const style: CSS.Properties = {
|
|
176
|
+
color: 'red',
|
|
177
|
+
margin: '1em',
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
let button = document.createElement('button');
|
|
181
|
+
|
|
182
|
+
Object.assign(button.style, style);
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
## What should I do when I get type errors?
|
|
186
|
+
|
|
187
|
+
The goal is to have as perfect types as possible and we're trying to do our best. But with CSS Custom Properties, the CSS specification changing frequently and vendors implementing their own specifications with new releases sometimes causes type errors even if it should work. Here's some steps you could take to get it fixed:
|
|
188
|
+
|
|
189
|
+
_If you're using CSS Custom Properties you can step directly to step 3._
|
|
190
|
+
|
|
191
|
+
1. **First of all, make sure you're doing it right.** A type error could also indicate that you're not :wink:
|
|
192
|
+
|
|
193
|
+
- Some CSS specs that some vendors has implemented could have been officially rejected or haven't yet received any official acceptance and are therefor not included
|
|
194
|
+
- If you're using TypeScript, [type widening](https://blog.mariusschulz.com/2017/02/04/TypeScript-2-1-literal-type-widening) could be the reason you get `Type 'string' is not assignable to...` errors
|
|
195
|
+
|
|
196
|
+
2. **Have a look in [issues](https://github.com/frenic/csstype/issues) to see if an issue already has been filed. If not, create a new one.** To help us out, please refer to any information you have found.
|
|
197
|
+
3. Fix the issue locally with **TypeScript** (Flow further down):
|
|
198
|
+
|
|
199
|
+
- The recommended way is to use **module augmentation**. Here's a few examples:
|
|
200
|
+
|
|
201
|
+
```ts
|
|
202
|
+
// My css.d.ts file
|
|
203
|
+
import type * as CSS from 'csstype';
|
|
204
|
+
|
|
205
|
+
declare module 'csstype' {
|
|
206
|
+
interface Properties {
|
|
207
|
+
// Add a missing property
|
|
208
|
+
WebkitRocketLauncher?: string;
|
|
209
|
+
|
|
210
|
+
// Add a CSS Custom Property
|
|
211
|
+
'--theme-color'?: 'black' | 'white';
|
|
212
|
+
|
|
213
|
+
// Allow namespaced CSS Custom Properties
|
|
214
|
+
[index: `--theme-${string}`]: any;
|
|
215
|
+
|
|
216
|
+
// Allow any CSS Custom Properties
|
|
217
|
+
[index: `--${string}`]: any;
|
|
218
|
+
|
|
219
|
+
// ...or allow any other property
|
|
220
|
+
[index: string]: any;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
- The alternative way is to use **type assertion**. Here's a few examples:
|
|
226
|
+
|
|
227
|
+
```ts
|
|
228
|
+
const style: CSS.Properties = {
|
|
229
|
+
// Add a missing property
|
|
230
|
+
['WebkitRocketLauncher' as any]: 'launching',
|
|
231
|
+
|
|
232
|
+
// Add a CSS Custom Property
|
|
233
|
+
['--theme-color' as any]: 'black',
|
|
234
|
+
};
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
Fix the issue locally with **Flow**:
|
|
238
|
+
|
|
239
|
+
- Use **type assertion**. Here's a few examples:
|
|
240
|
+
|
|
241
|
+
```js
|
|
242
|
+
const style: $Exact<CSS.Properties<*>> = {
|
|
243
|
+
// Add a missing property
|
|
244
|
+
[('WebkitRocketLauncher': any)]: 'launching',
|
|
245
|
+
|
|
246
|
+
// Add a CSS Custom Property
|
|
247
|
+
[('--theme-color': any)]: 'black',
|
|
248
|
+
};
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
## Version 3.0
|
|
252
|
+
|
|
253
|
+
- **All property types are exposed with namespace**
|
|
254
|
+
TypeScript: `Property.AlignContent` (was `AlignContentProperty` before)
|
|
255
|
+
Flow: `Property$AlignContent`
|
|
256
|
+
- **All at-rules are exposed with namespace**
|
|
257
|
+
TypeScript: `AtRule.FontFace` (was `FontFace` before)
|
|
258
|
+
Flow: `AtRule$FontFace`
|
|
259
|
+
- **Data types are NOT exposed**
|
|
260
|
+
E.g. `Color` and `Box`. Because the generation of data types may suddenly be removed or renamed.
|
|
261
|
+
- **TypeScript hack for autocompletion**
|
|
262
|
+
Uses `(string & {})` for literal string unions and `(number & {})` for literal number unions ([related issue](https://github.com/microsoft/TypeScript/issues/29729)). Utilize `PropertyValue<T>` to unpack types from e.g. `(string & {})` to `string`.
|
|
263
|
+
- **New generic for time**
|
|
264
|
+
Read more on the ["Generics"](#generics) section.
|
|
265
|
+
- **Flow types improvements**
|
|
266
|
+
Flow Strict enabled and exact types are used.
|
|
267
|
+
|
|
268
|
+
## Contributing
|
|
269
|
+
|
|
270
|
+
**Never modify `index.d.ts` and `index.js.flow` directly. They are generated automatically and committed so that we can easily follow any change it results in.** Therefor it's important that you run `$ git config merge.ours.driver true` after you've forked and cloned. That setting prevents merge conflicts when doing rebase.
|
|
271
|
+
|
|
272
|
+
### Commands
|
|
273
|
+
|
|
274
|
+
- `npm run build` Generates typings and type checks them
|
|
275
|
+
- `npm run watch` Runs build on each save
|
|
276
|
+
- `npm run test` Runs the tests
|
|
277
|
+
- `npm run lazy` Type checks, lints and formats everything
|