mirror of
https://github.com/ritz078/transform.git
synced 2026-11-20 16:22:53 +03:00
Custom config and variants support in css-to-tailwind (#243)
* Tailwind variants support (hover, focus, placeholder, etc. cases are transformed now) * Settings page let user define custom Tailwind configs, and "Tailwind preprocessor input" * Default tailwind.css built with SSG * Many fixes for corner cases
This commit is contained in:
1 parent
ea48bf3345
commit
2c50187d5e
11 files changed
+1125
-645
No files matched your search
@@ -60,6 +60,7 @@ Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds
|
||||
|
||||
<!-- markdownlint-enable -->
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
<!-- ALL-CONTRIBUTORS-LIST:END -->
|
||||
|
||||
This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind welcome!
|
||||
@@ -102,6 +102,7 @@ const ConversionPanel: React.FunctionComponent<ConversionPanelProps> = function(
|
||||
setResult(prettyResult);
|
||||
setMessage("");
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
setMessage(e.message);
|
||||
}
|
||||
toggleUpdateSpinner(false);
|
||||
|
||||
@@ -8,6 +8,12 @@ languages.typescript.typescriptDefaults.setDiagnosticsOptions({
|
||||
noSyntaxValidation: true
|
||||
});
|
||||
|
||||
languages.css.cssDefaults.setDiagnosticsOptions({
|
||||
lint: {
|
||||
unknownAtRules: "ignore"
|
||||
} as any
|
||||
});
|
||||
|
||||
// @ts-ignore
|
||||
self.MonacoEnvironment = {
|
||||
getWorkerUrl: function(_moduleId, label) {
|
||||
@@ -165,7 +171,7 @@ export default React.memo(
|
||||
({
|
||||
innerRef,
|
||||
...props
|
||||
}: MonacoProps & { innerRef: React.RefObject<MonacoEditor> }) => (
|
||||
}: MonacoProps & { innerRef?: React.RefObject<MonacoEditor> }) => (
|
||||
<MonacoEditor {...props} ref={innerRef} />
|
||||
)
|
||||
);
|
||||
@@ -0,0 +1,8 @@
|
||||
import dynamic from "next/dynamic";
|
||||
import React from "react";
|
||||
|
||||
const NoSSR = props => <React.Fragment>{props.children}</React.Fragment>;
|
||||
|
||||
export default dynamic(() => Promise.resolve(NoSSR), {
|
||||
ssr: false
|
||||
});
|
||||
+40
-40
@@ -45,7 +45,7 @@ export const css2 = `.alert {
|
||||
position: relative;
|
||||
padding: 1.6rem 4.6rem;
|
||||
margin-bottom: 1.6rem;
|
||||
border: 1px solid #9ae6b4;
|
||||
border: 1px solid #c53030;
|
||||
color: #fff;
|
||||
border-radius: 0.2rem;
|
||||
width: 100%;
|
||||
@@ -58,22 +58,48 @@ export const css2 = `.alert {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.separator {
|
||||
background: unset;
|
||||
}
|
||||
|
||||
.container {
|
||||
background: #ffffff;
|
||||
border: 1px solid #fff5f5;
|
||||
.button {
|
||||
background: #81e6d9;
|
||||
padding: 1.6rem 4.6rem;
|
||||
letter-spacing: 0.03rem;
|
||||
border-radius: 0.2rem;
|
||||
}
|
||||
|
||||
.header {
|
||||
font-weight: 400;
|
||||
font-size: 2rem;
|
||||
letter-spacing: 0.03rem;
|
||||
padding: 2.4rem;
|
||||
border-bottom: 1px solid #fff5f5;
|
||||
.button:hover {
|
||||
background: #2c7a7b;
|
||||
}
|
||||
|
||||
@media (min-width: 640px) {
|
||||
.button {
|
||||
padding: 0.5rem 1rem;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 1280px) {
|
||||
.button {
|
||||
padding: 3rem 7rem;
|
||||
margin-bottom: 2.4rem;
|
||||
}
|
||||
}
|
||||
|
||||
.username {
|
||||
color: #718096;
|
||||
border-color: #bee3f8;
|
||||
}
|
||||
|
||||
.username:focus {
|
||||
border-color: #3182ce;
|
||||
}
|
||||
|
||||
.username::placeholder {
|
||||
color: #cbd5e0;
|
||||
}
|
||||
|
||||
@media (min-width: 1280px) {
|
||||
.username {
|
||||
width: 50%;
|
||||
}
|
||||
}
|
||||
|
||||
.footer {
|
||||
@@ -85,32 +111,6 @@ export const css2 = `.alert {
|
||||
padding: 2.4rem 3rem;
|
||||
border-top: 1px solid #fff5f5;
|
||||
}
|
||||
|
||||
.content--with-side-content {
|
||||
width: 50%;
|
||||
}
|
||||
|
||||
.content--with-separator {
|
||||
border-right: 1px solid #fff5f5;
|
||||
}
|
||||
|
||||
.content-inner {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
flex-direction: column;
|
||||
margin: 0;
|
||||
padding: 3rem;
|
||||
}
|
||||
|
||||
.side-content {
|
||||
width: 50%;
|
||||
background: #425634;
|
||||
padding: 3rem;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
flex-direction: column;
|
||||
}
|
||||
`;
|
||||
|
||||
export const javascript = `const container = css({
|
||||
|
||||
+3
-1
@@ -42,11 +42,12 @@
|
||||
"@svgr/plugin-jsx": "^5.4.0",
|
||||
"@types/jsonld": "^1.5.1",
|
||||
"@walmartlabs/json-to-simple-graphql-schema": "^2.0.3",
|
||||
"autoprefixer": "^9.8.6",
|
||||
"babel-plugin-json-to-proptypes": "^0.1.0",
|
||||
"babel-plugin-object-styles-to-template": "^0.2.2",
|
||||
"babel-standalone": "^6.26.0",
|
||||
"clipboard-copy": "^3.1.0",
|
||||
"css-to-tailwind": "^0.1.3",
|
||||
"css-to-tailwind": "^1.0.3",
|
||||
"evergreen-ui": "^4.28.0",
|
||||
"flowgen": "^1.11.0",
|
||||
"formik": "^2.1.4",
|
||||
@@ -81,6 +82,7 @@
|
||||
"stringify-object": "^3.3.0",
|
||||
"svg-to-dataurl": "^1.0.0",
|
||||
"svgo": "^1.3.2",
|
||||
"tailwindcss": "^1.7.3",
|
||||
"tempy": "^0.6.0",
|
||||
"text-encoding-utf-8": "^1.0.2",
|
||||
"transform-json-types": "^0.7.0",
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import tailwindCss from "@utils/tailwindcss";
|
||||
|
||||
export default async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
try {
|
||||
const { tailwindConfig, postCssInput } = JSON.parse(req.body);
|
||||
const css = await tailwindCss(tailwindConfig, postCssInput);
|
||||
res.status(200).send(css);
|
||||
} catch (e) {
|
||||
res.status(500).send(e.message);
|
||||
}
|
||||
};
|
||||
+297
-25
@@ -1,39 +1,268 @@
|
||||
import ConversionPanel, { Transformer } from "@components/ConversionPanel";
|
||||
import NoSSR from "@components/NoSSR";
|
||||
import { editor } from "monaco-editor";
|
||||
import * as React from "react";
|
||||
import { useCallback } from "react";
|
||||
import cssToTailwind from "css-to-tailwind";
|
||||
import { useState, useCallback, useMemo } from "react";
|
||||
import request from "@utils/request";
|
||||
import tailwindCss from "@utils/tailwindcss";
|
||||
import { promises as fs } from "fs";
|
||||
import path from "path";
|
||||
import cssToTailwind from "css-to-tailwind/browser";
|
||||
import isEqual from "lodash/isEqual";
|
||||
import { useSettings } from "@hooks/useSettings";
|
||||
import {
|
||||
Dialog,
|
||||
Pane,
|
||||
Tablist,
|
||||
Tab,
|
||||
Alert,
|
||||
Button,
|
||||
Icon,
|
||||
Tooltip,
|
||||
toaster
|
||||
} from "evergreen-ui";
|
||||
import tailwindResolve from "tailwindcss/resolveConfig";
|
||||
import dynamic from "next/dynamic";
|
||||
|
||||
export default function() {
|
||||
const transformer = useCallback<Transformer>(async ({ value }) => {
|
||||
const results = await cssToTailwind(value);
|
||||
const output = results
|
||||
.map(result => {
|
||||
const { selector, tailwind, missing } = result;
|
||||
const Monaco = dynamic(() => import("../components/Monaco"), {
|
||||
ssr: false
|
||||
});
|
||||
|
||||
let output = `/* ℹ️ ${selector} */`;
|
||||
const options: editor.IEditorOptions = {
|
||||
fontSize: 14,
|
||||
readOnly: false,
|
||||
codeLens: false,
|
||||
fontFamily: "Menlo, Consolas, monospace, sans-serif",
|
||||
minimap: {
|
||||
enabled: false
|
||||
},
|
||||
quickSuggestions: false,
|
||||
lineNumbers: "on"
|
||||
};
|
||||
|
||||
if (tailwind.length) {
|
||||
output += `\n/* ✨ "${tailwind}" */`;
|
||||
const tabs = [
|
||||
{ label: "TailwindCSS Config", language: "javascript" },
|
||||
{ label: "PostCSS Input", language: "css" }
|
||||
];
|
||||
|
||||
if (missing.length) {
|
||||
output += `\n/* ⚠️ Some rules could not have been tranformed. Use @apply to extend base classes: */
|
||||
${selector} {
|
||||
@apply ${tailwind};
|
||||
${missing.map(([prop, value]) => `${prop}: ${value};`).join("\n ")}
|
||||
}`;
|
||||
function CssToTailwindSettings({ open, toggle, onConfirm, settings }) {
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const [isConfirmLoading, setConfirmLoading] = useState(false);
|
||||
const [tailwindConfigValue, setTailwindConfigValue] = useState(
|
||||
settings.tailwindConfig
|
||||
);
|
||||
const [postCssInputValue, setPostCssInputValue] = useState(
|
||||
settings.postCssInput
|
||||
);
|
||||
return (
|
||||
<Dialog
|
||||
title={
|
||||
<>
|
||||
TailwindCSS Settings
|
||||
<a
|
||||
href="https://tailwindcss.com/docs/configuration"
|
||||
target="_blank"
|
||||
style={{ verticalAlign: "middle" }}
|
||||
>
|
||||
<Tooltip content="Open the TailwindCSS docs...">
|
||||
<Icon icon="help" color="info" marginLeft={16} />
|
||||
</Tooltip>
|
||||
</a>
|
||||
</>
|
||||
}
|
||||
isShown={open}
|
||||
isConfirmLoading={isConfirmLoading}
|
||||
confirmLabel={isConfirmLoading ? "Running PostCSS..." : "Confirm"}
|
||||
onCloseComplete={toggle}
|
||||
onConfirm={async close => {
|
||||
setConfirmLoading(true);
|
||||
const isSuccess = await onConfirm({
|
||||
tailwindConfigValue,
|
||||
postCssInputValue
|
||||
});
|
||||
setConfirmLoading(false);
|
||||
if (isSuccess) {
|
||||
close();
|
||||
}
|
||||
}}
|
||||
onCancel={close => {
|
||||
setTailwindConfigValue(settings.tailwindConfig);
|
||||
setPostCssInputValue(settings.postCssInput);
|
||||
close();
|
||||
}}
|
||||
>
|
||||
<>
|
||||
<Tablist marginBottom={16} flexBasis={240} marginRight={24}>
|
||||
{tabs.map(({ label }, index) => (
|
||||
<Tab
|
||||
key={label}
|
||||
onSelect={() => setSelectedIndex(index)}
|
||||
isSelected={index === selectedIndex}
|
||||
>
|
||||
{label}
|
||||
</Tab>
|
||||
))}
|
||||
</Tablist>
|
||||
<Pane padding={16} flex="1">
|
||||
<Pane height={300}>
|
||||
<Monaco
|
||||
language={tabs[selectedIndex].language}
|
||||
value={
|
||||
selectedIndex === 0 ? tailwindConfigValue : postCssInputValue
|
||||
}
|
||||
onChange={
|
||||
selectedIndex === 0
|
||||
? setTailwindConfigValue
|
||||
: setPostCssInputValue
|
||||
}
|
||||
options={options}
|
||||
height="300"
|
||||
/>
|
||||
</Pane>
|
||||
</Pane>
|
||||
</>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function SettingsInfo({ isDefaultConfig, resetSettings }) {
|
||||
if (isDefaultConfig) {
|
||||
return null;
|
||||
}
|
||||
// opting out from SSR, because something goes wrong with the Alert component otherwise
|
||||
return (
|
||||
<NoSSR>
|
||||
<div style={{ minHeight: 20 }}>
|
||||
<Alert
|
||||
intent="warning"
|
||||
backgroundColor="#FEF8E7"
|
||||
title={
|
||||
<>
|
||||
Custom config is applied to TailwindCSS
|
||||
<Pane
|
||||
display="inline-block"
|
||||
position="absolute"
|
||||
right="10px"
|
||||
marginTop="-2px"
|
||||
>
|
||||
<Button
|
||||
appearance="minimal"
|
||||
intent="warning"
|
||||
height={24}
|
||||
onClick={resetSettings}
|
||||
>
|
||||
Reset
|
||||
</Button>
|
||||
</Pane>
|
||||
</>
|
||||
}
|
||||
} else {
|
||||
output += `\n/* ❌ Could not match any Tailwind classes. */`;
|
||||
/>
|
||||
</div>
|
||||
</NoSSR>
|
||||
);
|
||||
}
|
||||
|
||||
function formatOutput(results) {
|
||||
const content = results
|
||||
.map(result => {
|
||||
const { selector, tailwind, missing } = result;
|
||||
|
||||
let output = `/* ℹ️ Base selector: ${selector} */`;
|
||||
|
||||
if (tailwind.length) {
|
||||
output += `\n/* ✨ TailwindCSS: "${tailwind}" */`;
|
||||
|
||||
const { base, ...missingVariants } = missing;
|
||||
|
||||
if (base && base.length) {
|
||||
output += `\n/* ⚠️ Some properties could not be matched with Tailwind classes. Use @apply to extend a CSS rule: */
|
||||
${selector} {
|
||||
@apply ${tailwind};
|
||||
${base.map(([prop, value]) => `${prop}: ${value};`).join("\n ")}
|
||||
}`;
|
||||
}
|
||||
|
||||
return output;
|
||||
})
|
||||
.join("\n\n");
|
||||
if (Object.keys(missingVariants).length) {
|
||||
output += `\n/* ⚠️ Some properties are requiring specific variants, but the variant does not support those. Consider extending your Tailwind config.\n`;
|
||||
Object.entries(missingVariants).forEach(([variant, values]) => {
|
||||
const properties = (values as [string, string])
|
||||
.map(([prop, value]) => `\t${prop}: ${value};`)
|
||||
.join("\n ");
|
||||
output += `${variant}:\n${properties}\n`;
|
||||
});
|
||||
output += "*/";
|
||||
}
|
||||
} else {
|
||||
output += `\n/* ❌ Could not match any TailwindCSS classes. */`;
|
||||
}
|
||||
|
||||
const successfulCount = results.filter(result => result.tailwind.length)
|
||||
.length;
|
||||
return output;
|
||||
})
|
||||
.join("\n\n");
|
||||
|
||||
return `/* ${successfulCount}/${results.length} rules are converted successfully. */\n\n${output}`;
|
||||
const success = results.filter(result => result.tailwind.length);
|
||||
|
||||
(window as any).cssToTailwindResults = results;
|
||||
|
||||
return `/* ${success.length}/${results.length} base rules are converted successfully. */\n/* Gather results from the console with \`copy(window.cssToTailwindResults)\` */\n\n${content}`;
|
||||
}
|
||||
|
||||
export default function({ defaultSettings }) {
|
||||
const [settings, setSettings] = useSettings(
|
||||
"css-to-tailwind",
|
||||
defaultSettings
|
||||
);
|
||||
|
||||
const onSettingsSubmit = useCallback(
|
||||
async ({ tailwindConfigValue, postCssInputValue }) => {
|
||||
try {
|
||||
const resolvedTailwindConfig = tailwindResolve(
|
||||
eval(`const module = {}; ${tailwindConfigValue}; module.exports;`)
|
||||
);
|
||||
|
||||
try {
|
||||
const newTailwindCss = await request("/api/build-tailwind-css", {
|
||||
tailwindConfig: resolvedTailwindConfig,
|
||||
postCssInput: postCssInputValue
|
||||
});
|
||||
toaster.success("Custom TailwindCSS config is successfully applied");
|
||||
|
||||
setSettings({
|
||||
tailwindConfig: tailwindConfigValue,
|
||||
postCssInput: postCssInputValue,
|
||||
tailwindCss: newTailwindCss
|
||||
});
|
||||
|
||||
// indicate submit was successful
|
||||
return true;
|
||||
} catch (e) {
|
||||
toaster.danger(
|
||||
"Something went wrong trying to build TailwindCSS with custom config",
|
||||
{
|
||||
description: "Now the default config is used instead"
|
||||
}
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
toaster.danger(
|
||||
"Something went wrong trying to resolve TailwindCSS config",
|
||||
{
|
||||
description: e.message
|
||||
}
|
||||
);
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const transformer = useCallback<Transformer>(async ({ value }) => {
|
||||
const results = await cssToTailwind(value, settings.tailwindCss);
|
||||
|
||||
return formatOutput(results);
|
||||
}, []);
|
||||
|
||||
const resetSettings = useCallback(() => {
|
||||
setSettings(defaultSettings);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
@@ -44,6 +273,49 @@ export default function() {
|
||||
editorDefaultValue="css2"
|
||||
resultTitle="TailwindCSS"
|
||||
resultLanguage={"css"}
|
||||
editorProps={{
|
||||
settingElement: ({ open, toggle }) => {
|
||||
return (
|
||||
<CssToTailwindSettings
|
||||
key={`${settings.tailwindConfig}${settings.postCssInput}`}
|
||||
open={open}
|
||||
toggle={toggle}
|
||||
onConfirm={onSettingsSubmit}
|
||||
settings={settings}
|
||||
/>
|
||||
);
|
||||
},
|
||||
topNotifications: () => {
|
||||
return (
|
||||
<SettingsInfo
|
||||
isDefaultConfig={isEqual(settings, defaultSettings)}
|
||||
resetSettings={resetSettings}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export async function getStaticProps() {
|
||||
const tailwindConfig = await fs.readFile(
|
||||
path.resolve("./node_modules/tailwindcss/stubs/simpleConfig.stub.js"),
|
||||
"utf-8"
|
||||
);
|
||||
const postCssInput = await fs.readFile(
|
||||
path.resolve("./node_modules/tailwindcss/tailwind.css"),
|
||||
"utf-8"
|
||||
);
|
||||
const config = eval(`const module = {}; ${tailwindConfig}; module.exports;`);
|
||||
const css = await tailwindCss(config, postCssInput);
|
||||
return {
|
||||
props: {
|
||||
defaultSettings: {
|
||||
tailwindConfig,
|
||||
postCssInput,
|
||||
tailwindCss: css
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
Vendored
+37
@@ -260,4 +260,41 @@ declare module "evergreen-ui" {
|
||||
}
|
||||
|
||||
export class Select extends React.PureComponent<SelectProps> {}
|
||||
|
||||
export interface TabProps extends TextProps {
|
||||
onSelect?(): void;
|
||||
isSelected?: boolean;
|
||||
disabled?: boolean;
|
||||
appearance?: DefaultAppearance;
|
||||
}
|
||||
|
||||
export class Tab extends React.PureComponent<TabProps> {}
|
||||
|
||||
export type TablistProps = React.ComponentPropsWithoutRef<typeof Box>;
|
||||
|
||||
export class Tablist extends React.PureComponent<TablistProps> {}
|
||||
|
||||
export type TabNavigationProps = BoxProps<"nav">;
|
||||
|
||||
export class TabNavigation extends React.PureComponent<TabNavigationProps> {}
|
||||
|
||||
export interface TagInputProps
|
||||
extends Omit<React.ComponentPropsWithoutRef<typeof Box>, "onChange"> {
|
||||
addOnBlur?: boolean;
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
height?: number;
|
||||
inputProps?: TextProps;
|
||||
inputRef?: (input: HTMLInputElement | null) => void;
|
||||
onAdd?: (values: string[]) => void | false;
|
||||
onBlur?: (event: React.FocusEvent) => void;
|
||||
onChange?: (values: string[]) => void | false;
|
||||
onFocus?: (event: React.FocusEvent) => void;
|
||||
onInputChange?: (event: React.ChangeEvent) => void;
|
||||
onRemove?: (value: string | React.ReactNode, index: number) => void;
|
||||
separator?: string;
|
||||
tagSubmitKey?: "enter" | "space";
|
||||
tagProps?: any;
|
||||
values?: string[];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import postcss from "postcss";
|
||||
import tailwindcss from "tailwindcss";
|
||||
import defaultConfig from "tailwindcss/stubs/simpleConfig.stub.js";
|
||||
import autoprefixer from "autoprefixer";
|
||||
|
||||
export default async function buildTailwindCss(
|
||||
tailwindConfig: any,
|
||||
postCssInput: string
|
||||
): Promise<string> {
|
||||
const { css } = await postcss([
|
||||
tailwindConfig ? tailwindcss(tailwindConfig) : tailwindcss(defaultConfig),
|
||||
autoprefixer
|
||||
]).process(postCssInput, { from: "tailwind.css" });
|
||||
|
||||
return css;
|
||||
}
|
||||
Reference in new issue
Block a user