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

prototype: classNamePrefix option #540

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
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
1 change: 1 addition & 0 deletions e2e/nextjs/src/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ async function performTest() {
packLocalPackage(rootDir, tempDir, '@griffel/style-types'),
packLocalPackage(rootDir, tempDir, '@griffel/core'),
packLocalPackage(rootDir, tempDir, '@griffel/react'),
packLocalPackage(rootDir, tempDir, '@griffel/babel-preset'),
packLocalPackage(rootDir, tempDir, '@griffel/webpack-extraction-plugin'),
packLocalPackage(rootDir, tempDir, '@griffel/webpack-loader'),
packLocalPackage(rootDir, tempDir, '@griffel/next-extraction-plugin'),
Expand Down
1 change: 1 addition & 0 deletions e2e/rspack/src/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ async function performTest() {
packLocalPackage(rootDir, tempDir, '@griffel/style-types'),
packLocalPackage(rootDir, tempDir, '@griffel/core'),
packLocalPackage(rootDir, tempDir, '@griffel/react'),
packLocalPackage(rootDir, tempDir, '@griffel/babel-preset'),
packLocalPackage(rootDir, tempDir, '@griffel/webpack-extraction-plugin'),
packLocalPackage(rootDir, tempDir, '@griffel/webpack-loader'),
]);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { makeStyles } from '@griffel/react';

export const useStyles = makeStyles({
root: { color: 'red', paddingLeft: '4px' },
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { __styles } from '@griffel/react';
export const useStyles = __styles(
{
root: {
sj55zd: 'pe3e8s9',
uwmqm3: ['pycuoez', 'p8wuabp'],
},
},
{
d: ['.pe3e8s9{color:red;}', '.pycuoez{padding-left:4px;}', '.p8wuabp{padding-right:4px;}'],
},
);
3 changes: 3 additions & 0 deletions packages/babel-preset/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ export const configSchema: JSONSchema7 = {

type: 'object',
properties: {
classNamePrefix: {
type: 'string',
},
generateMetadata: {
type: 'boolean',
},
Expand Down
8 changes: 8 additions & 0 deletions packages/babel-preset/src/transformPlugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,14 @@ pluginTester({
// Configs
//
//
{
title: 'config: classNamePrefix',
fixture: path.resolve(fixturesDir, 'config-classname-prefix', 'code.ts'),
outputFixture: path.resolve(fixturesDir, 'config-classname-prefix', 'output.ts'),
pluginOptions: {
classNamePrefix: 'p',
},
},
{
title: 'config: babelOptions',
fixture: path.resolve(fixturesDir, 'config-babel-options', 'code.ts'),
Expand Down
6 changes: 5 additions & 1 deletion packages/babel-preset/src/transformPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { declare } from '@babel/helper-plugin-utils';
import { Module } from '@linaria/babel-preset';
import shakerEvaluator from '@linaria/shaker';
import type { GriffelStyle, CSSRulesByBucket, CSSClassesMapBySlot } from '@griffel/core';
import { resolveStyleRulesForSlots, resolveResetStyleRules, normalizeCSSBucketEntry } from '@griffel/core';
import { HASH_PREFIX, resolveStyleRulesForSlots, resolveResetStyleRules, normalizeCSSBucketEntry } from '@griffel/core';
import * as path from 'path';

import { normalizeStyleRules } from './assets/normalizeStyleRules';
Expand Down Expand Up @@ -97,6 +97,7 @@ function buildCSSResetEntriesMetadata(
declaratorId: string,
) {
const cssRulesByBucket: CSSRulesByBucket = Array.isArray(cssRules) ? { d: cssRules } : cssRules;

state.cssResetEntries[declaratorId] ??= [];
state.cssResetEntries[declaratorId] = Object.values(cssRulesByBucket).flatMap(bucketEntries => {
return bucketEntries.map(bucketEntry => {
Expand Down Expand Up @@ -202,6 +203,7 @@ export const transformPlugin = declare<Partial<BabelPluginOptions>, PluginObj<Ba
api.assertVersion(7);

const pluginOptions: Required<BabelPluginOptions> = {
classNamePrefix: HASH_PREFIX,
babelOptions: {},
generateMetadata: false,
modules: [
Expand Down Expand Up @@ -289,6 +291,7 @@ export const transformPlugin = declare<Partial<BabelPluginOptions>, PluginObj<Ba
if (definitionPath.functionKind === 'makeStyles') {
const stylesBySlots: Record<string /* slot */, GriffelStyle> = evaluationResult.value;
const [classnamesMapping, cssRulesByBucket] = resolveStyleRulesForSlots(
pluginOptions.classNamePrefix,
// Heads up!
// Style rules should be normalized *before* they will be resolved to CSS rules to have deterministic
// results across different build targets.
Expand Down Expand Up @@ -321,6 +324,7 @@ export const transformPlugin = declare<Partial<BabelPluginOptions>, PluginObj<Ba
if (definitionPath.functionKind === 'makeResetStyles') {
const styles: GriffelStyle = evaluationResult.value;
const [ltrClassName, rtlClassName, cssRules] = resolveResetStyleRules(
pluginOptions.classNamePrefix === HASH_PREFIX ? '' : pluginOptions.classNamePrefix,
// Heads up!
// Style rules should be normalized *before* they will be resolved to CSS rules to have deterministic
// results across different build targets.
Expand Down
3 changes: 3 additions & 0 deletions packages/babel-preset/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ import type { TransformOptions } from '@babel/core';
import type { EvalRule } from '@linaria/babel-preset';

export type BabelPluginOptions = {
classNamePrefix?: string;

/**
* Returns the evaluated CSS rules in the file result metadata
* @default false
*/
generateMetadata?: boolean;

/** Defines set of modules and imports handled by a transformPlugin. */
modules?: {
moduleSource: string;
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ export const DEFINITION_LOOKUP_TABLE = getGlobalVar<Record<SequenceHash, LookupI
/** @internal */
export const DATA_BUCKET_ATTR = 'data-make-styles-bucket';

/** @internal */
export const DATA_CLASSNAME_PREFIX_ATTR = 'data-prefix';

/** @internal */
export const HASH_PREFIX = 'f';

Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/makeResetStyles.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { GriffelResetStyle } from '@griffel/style-types';

import { DEBUG_RESET_CLASSES } from './constants';
import { DEBUG_RESET_CLASSES, HASH_PREFIX } from './constants';

Check failure on line 3 in packages/core/src/makeResetStyles.ts

View workflow job for this annotation

GitHub Actions / main

'HASH_PREFIX' is defined but never used
import { insertionFactory } from './insertionFactory';
import { resolveResetStyleRules } from './runtime/resolveResetStyleRules';
import type { CSSRulesByBucket, GriffelRenderer, GriffelInsertionFactory } from './types';
Expand All @@ -22,7 +22,7 @@
const { dir, renderer } = options;

if (ltrClassName === null) {
[ltrClassName, rtlClassName, cssRules] = resolveResetStyleRules(styles);
[ltrClassName, rtlClassName, cssRules] = resolveResetStyleRules(renderer.classNamePrefix || '', styles);
}

insertStyles(renderer, Array.isArray(cssRules) ? { r: cssRules! } : cssRules!);
Expand Down
23 changes: 23 additions & 0 deletions packages/core/src/makeStyles.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,4 +258,27 @@ describe('makeStyles', () => {
expect(computeClasses({ dir: 'ltr', renderer }).root).toEqual('___afhpfp0_0000000 fe3e8s9');
},
);

describe('renderer', () => {
it('uses "classNamePrefix', () => {
const rendererWithPrefix = createDOMRenderer(document, { classNamePrefix: 'test' });
const computeClassesA = makeStyles({ root: { color: 'red', paddingLeft: '10px' } });

expect(computeClassesA({ dir: 'ltr', renderer: rendererWithPrefix }).root).toMatchInlineSnapshot(
`"___izb4q10 teste3e8s9 testrdkuqy"`,
);
expect(rendererWithPrefix).toMatchInlineSnapshot(`
/** bucket "d" **/
.teste3e8s9 {
color: red;
}
.testrdkuqy {
padding-left: 10px;
}
.test81rol6 {
padding-right: 10px;
}
`);
});
});
});
12 changes: 9 additions & 3 deletions packages/core/src/makeStyles.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import { HASH_PREFIX } from './constants';
import { debugData, isDevToolsEnabled, getSourceURLfromError } from './devtools';
import { insertionFactory } from './insertionFactory';
import { resolveStyleRulesForSlots } from './resolveStyleRulesForSlots';
import { reduceToClassNameForSlots } from './runtime/reduceToClassNameForSlots';
import type { CSSClassesMapBySlot, CSSRulesByBucket, GriffelRenderer, StylesBySlots } from './types';
import type { GriffelInsertionFactory } from './types';
import type {
CSSClassesMapBySlot,
CSSRulesByBucket,
GriffelInsertionFactory,
GriffelRenderer,
StylesBySlots,
} from './types';

export interface MakeStylesOptions {
dir: 'ltr' | 'rtl';
Expand Down Expand Up @@ -31,7 +37,7 @@ export function makeStyles<Slots extends string | number>(
const { dir, renderer } = options;

if (classesMapBySlot === null) {
[classesMapBySlot, cssRules] = resolveStyleRulesForSlots(stylesBySlots);
[classesMapBySlot, cssRules] = resolveStyleRulesForSlots(renderer.classNamePrefix || HASH_PREFIX, stylesBySlots);
}

const isLTR = dir === 'ltr';
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/renderer/createDOMRenderer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,13 @@ describe('createDOMRenderer', () => {
HTMLCollection [
<style
data-make-styles-bucket="d"
data-prefix=""
foo-bar="baz"
nonce="random"
/>,
<style
data-make-styles-bucket="h"
data-prefix=""
foo-bar="baz"
nonce="random"
/>,
Expand Down Expand Up @@ -113,9 +115,11 @@ describe('createDOMRenderer', () => {
/>,
<style
data-make-styles-bucket="d"
data-prefix=""
/>,
<style
data-make-styles-bucket="h"
data-prefix=""
/>,
<style
data-test="B"
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/renderer/createDOMRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { safeInsertRule } from './safeInsertRule';
let lastIndex = 0;

export interface CreateDOMRendererOptions {
classNamePrefix?: string;

/**
* If specified, a renderer will insert created style tags after this element.
*/
Expand Down Expand Up @@ -50,12 +52,14 @@ export function createDOMRenderer(
options: CreateDOMRendererOptions = {},
): GriffelRenderer {
const {
classNamePrefix,
unstable_filterCSSRule,
insertionPoint,
styleElementAttributes,
compareMediaQueries = defaultCompareMediaQueries,
} = options;
const renderer: GriffelRenderer = {
classNamePrefix,
insertionCache: {},
stylesheets: {},
styleElementAttributes: Object.freeze(styleElementAttributes),
Expand All @@ -72,6 +76,7 @@ export function createDOMRenderer(
for (let i = 0, l = cssRulesForBucket.length; i < l; i++) {
const [ruleCSS, metadata] = normalizeCSSBucketEntry(cssRulesForBucket[i]);
const sheet = getStyleSheetForBucket(
classNamePrefix || '',
styleBucketName as StyleBucketName,
targetDocument,
insertionPoint || null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { createIsomorphicStyleSheet } from './createIsomorphicStyleSheet';

describe('createIsomorphicStyleElement - node', () => {
it('should insert css rule', () => {
const stylesheet = createIsomorphicStyleSheet(undefined, 'd', {});
const stylesheet = createIsomorphicStyleSheet(undefined, '', 'd', {});
stylesheet.insertRule(".foo { color: 'red' }");
expect(stylesheet.cssRules()).toMatchInlineSnapshot(`
Array [
Expand All @@ -18,11 +18,12 @@ describe('createIsomorphicStyleElement - node', () => {
});

it('should set element attributes', () => {
const stylesheet = createIsomorphicStyleSheet(undefined, 'd', { 'data-foo': 'foo' });
const stylesheet = createIsomorphicStyleSheet(undefined, '', 'd', { 'data-foo': 'foo' });
expect(stylesheet.elementAttributes).toMatchInlineSnapshot(`
Object {
"data-foo": "foo",
"data-make-styles-bucket": "d",
"data-prefix": "",
}
`);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { createIsomorphicStyleSheet } from './createIsomorphicStyleSheet';

describe('createIsomorphicStyleElement', () => {
it('should insert css rule', () => {
const stylesheet = createIsomorphicStyleSheet(document.createElement('style'), 'd', {});
const stylesheet = createIsomorphicStyleSheet(document.createElement('style'), '', 'd', {});
stylesheet.insertRule(".foo { color: 'red' }");
expect(stylesheet.cssRules()).toMatchInlineSnapshot(`
Array [
Expand All @@ -12,18 +12,20 @@ describe('createIsomorphicStyleElement', () => {
});

it('should set element attributes', () => {
const stylesheet = createIsomorphicStyleSheet(document.createElement('style'), 'd', { 'data-foo': 'foo' });
const stylesheet = createIsomorphicStyleSheet(document.createElement('style'), '', 'd', { 'data-foo': 'foo' });
expect(stylesheet.elementAttributes).toMatchInlineSnapshot(`
Object {
"data-foo": "foo",
"data-make-styles-bucket": "d",
"data-prefix": "",
}
`);

expect(stylesheet.element).toMatchInlineSnapshot(`
<style
data-foo="foo"
data-make-styles-bucket="d"
data-prefix=""
/>
`);

Expand All @@ -36,11 +38,12 @@ describe('createIsomorphicStyleElement', () => {
});

it('should create HTML style element', () => {
const stylesheet = createIsomorphicStyleSheet(document.createElement('style'), 'd', {});
const stylesheet = createIsomorphicStyleSheet(document.createElement('style'), '', 'd', {});
expect(stylesheet.element).not.toBeUndefined();
expect(stylesheet.element).toMatchInlineSnapshot(`
<style
data-make-styles-bucket="d"
data-prefix=""
/>
`);
});
Expand Down
6 changes: 5 additions & 1 deletion packages/core/src/renderer/createIsomorphicStyleSheet.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import { DATA_BUCKET_ATTR } from '../constants';
import { DATA_BUCKET_ATTR, DATA_CLASSNAME_PREFIX_ATTR } from '../constants';
import type { IsomorphicStyleSheet, StyleBucketName } from '../types';

export function createIsomorphicStyleSheet(
styleElement: HTMLStyleElement | undefined,
classNamePrefix: string,
bucketName: StyleBucketName,
elementAttributes: Record<string, string>,
): IsomorphicStyleSheet {
// no CSSStyleSheet in SSR, just append rules here for server render
const __cssRulesForSSR: string[] = [];

elementAttributes[DATA_BUCKET_ATTR] = bucketName;
elementAttributes[DATA_CLASSNAME_PREFIX_ATTR] = classNamePrefix;

if (styleElement) {
for (const attrName in elementAttributes) {
styleElement.setAttribute(attrName, elementAttributes[attrName]);
Expand Down Expand Up @@ -46,6 +49,7 @@ export function createIsomorphicStyleSheetFromElement(element: HTMLStyleElement)
}, {} as Record<string, string>);
const stylesheet = createIsomorphicStyleSheet(
element,
elementAttributes[DATA_CLASSNAME_PREFIX_ATTR],
elementAttributes[DATA_BUCKET_ATTR] as StyleBucketName,
elementAttributes,
);
Expand Down
Loading
Loading