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

Update browser runtime #409

Merged
merged 29 commits into from
Oct 12, 2021
Merged
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
42c4294
Inject styles experiment
mattcompiles Oct 6, 2021
f9d1a15
Get basic inject working
mattcompiles Oct 6, 2021
d2fd45c
Add the inject styles entry point
Oct 7, 2021
b668abe
Switch to injecting styles
Oct 7, 2021
5dcdb77
Deunescape the CSS
Oct 7, 2021
b7446ee
Set optimised deps in the plugin
Oct 8, 2021
daa2789
Use the integration regex
Oct 8, 2021
1375ba9
Strip ?used from ids for fileScope
Oct 8, 2021
69f2ff2
Add a changeset for the used stuff
Oct 8, 2021
c98ad55
Remove the initial drafts of inject styles
Oct 8, 2021
e9f7575
Add a changeset for injectStyles
Oct 8, 2021
9de50c9
Add a changeset for the cssMap.delete thing
Oct 8, 2021
6f3b817
Clean up the injectStyles from integration
Oct 8, 2021
322ff6f
Also update vanilla specific ssr config in vite plugin
Oct 8, 2021
7754d15
Clean up the package json from the integration version of injectStyles
Oct 8, 2021
bcbae34
More cleanup
Oct 8, 2021
83dadee
Remove a word
Oct 10, 2021
29594b9
Separate out the vite/browser thing
Oct 10, 2021
68219f8
Add a changeset about the deps
Oct 11, 2021
dd9d095
Small cleanups in vite plugin
Oct 11, 2021
c35d5ad
Merge branch 'master' into inject
Oct 11, 2021
ccb8e11
JSBench has spoken
Oct 12, 2021
8477c38
Address PR comments
Oct 12, 2021
0003de4
Switch to dedent
Oct 12, 2021
98bbdf5
Add changeset for integration
Oct 12, 2021
e3108b2
Explicitly throw if the filescope is missing
Oct 12, 2021
4acd159
Strip the `?used` everywhere
Oct 12, 2021
0f4f14e
Add an explanatory comment
Oct 12, 2021
8b18442
Migrate everything to outdent
Oct 12, 2021
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
9 changes: 9 additions & 0 deletions .changeset/chilled-goats-fold.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@vanilla-extract/vite-plugin': patch
---

Fix plugin for watch mode.

The vite plugin previously relied on a one to one matching of resolve to load calls, and would clean up the CSS stored in memory after it was loaded.

This isn't true in `--watch` mode, as the same file can be loaded on the rebuild without having to be resolved, which the plugin now handles.
10 changes: 10 additions & 0 deletions .changeset/khaki-taxis-tell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@vanilla-extract/css': patch
---

Change the way vanilla runtime works.
benjervis marked this conversation as resolved.
Show resolved Hide resolved

The vanilla browser runtime now creates style tags containing the CSS itself, rather than injecting it directly into the CSSOM.

This helps with debugability, as the generated CSS can actually be seen in the devtools.
There are also some new attributes set on the style tags, making it easier to identify the source of each style.
9 changes: 9 additions & 0 deletions .changeset/polite-rings-nail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@vanilla-extract/vite-plugin': patch
---

Update the vanilla runtime integration.
benjervis marked this conversation as resolved.
Show resolved Hide resolved

When using the vanilla browser runtime in vite, it now operates on a new model where a .css.js file is generated, that uses @vanilla-extract/css/injectStyles to add the css to the browser.

This allows for hot reloading of styles, and makes styles a bit easier to debug at dev time (because they're actually visible).
10 changes: 10 additions & 0 deletions .changeset/pretty-carrots-drive.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@vanilla-extract/babel-plugin': patch
'@vanilla-extract/vite-plugin': patch
---

Handle vite 2.6.

As of vite 2.6 and greater, `?used` gets appended to css imports, which causes the file imports to be not what we expected.

This caused mismatching classnames in the vite plugin, and it caused the babel plugin to not add filescopes when it should have.
10 changes: 10 additions & 0 deletions .changeset/strong-zebras-prove.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@vanilla-extract/vite-plugin': patch
---

Automatically optimize deps.

When using the new vanilla browser runtime, the new `injectStyles` dependency gets injected at runtime, so vite can't discover it ahead of time and pre-bundle it.

The plugin will now add the dependency to optimizeDeps if the vanilla runtime is being used so that it's optimized up front.
It also ensures that some relevant vanilla packages are externalised in SSR mode.
4 changes: 2 additions & 2 deletions packages/babel-plugin/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { relative, posix, sep } from 'path';
import { types as t, PluginObj, PluginPass, NodePath } from '@babel/core';
import template from '@babel/template';
import { getPackageInfo } from '@vanilla-extract/integration';
import { cssFileFilter, getPackageInfo } from '@vanilla-extract/integration';

const packageIdentifiers = new Set([
'@vanilla-extract/css',
Expand Down Expand Up @@ -183,7 +183,7 @@ export default function (): PluginObj<Context> {
}

this.isESM = false;
this.isCssFile = /\.css\.(js|ts|jsx|tsx)$/.test(opts.filename);
this.isCssFile = cssFileFilter.test(opts.filename);
this.alreadyCompiled = false;

this.importIdentifiers = new Map();
Expand Down
8 changes: 8 additions & 0 deletions packages/css/injectStyles/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"main": "dist/vanilla-extract-css-injectStyles.cjs.js",
"module": "dist/vanilla-extract-css-injectStyles.esm.js",
"browser": {
"./dist/vanilla-extract-css-injectStyles.cjs.js": "./dist/vanilla-extract-css-injectStyles.browser.cjs.js",
"./dist/vanilla-extract-css-injectStyles.esm.js": "./dist/vanilla-extract-css-injectStyles.browser.esm.js"
}
}
2 changes: 2 additions & 0 deletions packages/css/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"adapter.ts",
"transformCss.ts",
"fileScope.ts",
"injectStyles.ts",
"disableRuntimeStyles.ts"
]
},
Expand All @@ -27,6 +28,7 @@
"/adapter",
"/transformCss",
"/fileScope",
"/injectStyles",
"/disableRuntimeStyles"
],
"repository": {
Expand Down
30 changes: 30 additions & 0 deletions packages/css/src/injectStyles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { FileScope } from './types';

const stylesheets: Record<string, HTMLElement> = {};

interface InjectStylesOptions {
fileScope: FileScope;
css: string;
}
export const injectStyles = ({ fileScope, css }: InjectStylesOptions) => {
const fileScopeId = fileScope.packageName
? [fileScope.packageName, fileScope.filePath].join('/')
: fileScope.filePath;

let stylesheet = stylesheets[fileScopeId];

if (!stylesheet) {
const styleEl = document.createElement('style');

if (fileScope.packageName) {
styleEl.setAttribute('data-package', fileScope.packageName);
}

styleEl.setAttribute('data-file', fileScope.filePath);
styleEl.setAttribute('type', 'text/css');
stylesheet = stylesheets[fileScopeId] = styleEl;
document.head.appendChild(styleEl);
}

stylesheet.innerHTML = css;
};
46 changes: 4 additions & 42 deletions packages/css/src/runtimeAdapter.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,12 @@
import type { Adapter, Composition, CSS, FileScope } from './types';
import type { Adapter, Composition, CSS } from './types';
import { injectStyles } from './injectStyles';
import { transformCss } from './transformCss';
import { setAdapterIfNotSet } from './adapter';

const stylesheets: Record<string, CSSStyleSheet> = {};

const localClassNames = new Set<string>();
const composedClassLists: Array<Composition> = [];
let bufferedCSSObjs: Array<CSS> = [];

function getStylesheet({ packageName, filePath }: FileScope) {
const fileScopeId = packageName ? `${packageName}${filePath}` : filePath;
if (stylesheets[fileScopeId]) {
return stylesheets[fileScopeId];
}
const styleEl = document.createElement('style');
document.head.appendChild(styleEl);

if (!styleEl.sheet) {
throw new Error(`Couldn't create stylesheet`);
}
stylesheets[fileScopeId] = styleEl.sheet;

return styleEl.sheet;
}

const browserRuntimeAdapter: Adapter = {
appendCss: (cssObj: CSS) => {
bufferedCSSObjs.push(cssObj);
Expand All @@ -40,30 +23,9 @@ const browserRuntimeAdapter: Adapter = {
localClassNames: Array.from(localClassNames),
composedClassLists,
cssObjs: bufferedCSSObjs,
});
const stylesheet = getStylesheet(fileScope);
const existingRuleCount = stylesheet.cssRules.length;

let ruleIndex = 0;

for (const rule of css) {
try {
if (ruleIndex < existingRuleCount) {
stylesheet.deleteRule(ruleIndex);
}
stylesheet.insertRule(rule, ruleIndex++);
} catch (e) {
console.warn(`Failed to insert rule\n${rule}`);

// insert placeholder rule to keep index count correct
stylesheet.insertRule('.--placeholder-rule--{}', ruleIndex - 1);
}
}
}).join('\n');

// Delete remaining rules
while (ruleIndex < existingRuleCount) {
stylesheet.deleteRule(ruleIndex++);
}
injectStyles({ fileScope, css });

bufferedCSSObjs = [];
},
Expand Down
1 change: 1 addition & 0 deletions packages/integration/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": "1.4.2",
"description": "Zero-runtime Stylesheets-in-TypeScript",
"main": "dist/vanilla-extract-integration.cjs.js",
"module": "dist/vanilla-extract-integration.esm.js",
Copy link
Contributor

Choose a reason for hiding this comment

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

This isn't required anymore.

"files": [
"/dist"
],
Expand Down
6 changes: 5 additions & 1 deletion packages/integration/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
export { processVanillaFile } from './processVanillaFile';
export {
processVanillaFile,
parseFileScope,
stringifyFileScope,
} from './processVanillaFile';
Copy link
Contributor

Choose a reason for hiding this comment

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

We need to add a changeset for the integration package

export { getSourceFromVirtualCssFile } from './virtualFile';
export { getPackageInfo } from './packageInfo';
export { compile, vanillaExtractFilescopePlugin } from './compile';
Expand Down
15 changes: 12 additions & 3 deletions packages/integration/src/processVanillaFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@ import { hash } from './hash';

const originalNodeEnv = process.env.NODE_ENV;

function stringifyFileScope({ packageName, filePath }: FileScope): string {
export function stringifyFileScope({
packageName,
filePath,
}: FileScope): string {
return packageName ? `${filePath}$$$${packageName}` : filePath;
}

function parseFileScope(serialisedFileScope: string): FileScope {
export function parseFileScope(serialisedFileScope: string): FileScope {
const [filePath, packageName] = serialisedFileScope.split('$$$');

return {
Expand All @@ -33,6 +36,7 @@ interface ProcessVanillaFileOptions {
fileName: string;
base64Source: string;
fileScope: FileScope;
source: string;
}) => string;
}
export function processVanillaFile({
Expand Down Expand Up @@ -113,7 +117,12 @@ export function processVanillaFile({
}.vanilla.css`;

const virtualCssFilePath = serializeVirtualCssPath
? serializeVirtualCssPath({ fileName, base64Source, fileScope })
? serializeVirtualCssPath({
fileName,
base64Source,
fileScope,
source: css,
})
: `import '${fileName}?source=${base64Source}';`;

cssImports.push(virtualCssFilePath);
Expand Down
3 changes: 2 additions & 1 deletion packages/vite-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
"author": "SEEK",
"license": "MIT",
"dependencies": {
"@vanilla-extract/integration": "^1.4.2"
"@vanilla-extract/integration": "^1.4.2",
"outdent": "^0.8.0"
Copy link
Contributor

Choose a reason for hiding this comment

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

Realised we're already using dedent in the css package so we should probably be consistent.

},
"devDependencies": {
"vite": "^2.6.0"
Expand Down
Loading