Skip to content

Commit

Permalink
Use standard identifier generation logic for variable names (#810)
Browse files Browse the repository at this point in the history
  • Loading branch information
markdalgleish authored Sep 6, 2022
1 parent bfde2e5 commit c38b152
Show file tree
Hide file tree
Showing 6 changed files with 102 additions and 30 deletions.
5 changes: 5 additions & 0 deletions .changeset/gold-trainers-sing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@vanilla-extract/css': patch
---

Fix spaces in debug IDs for variable names.
16 changes: 16 additions & 0 deletions .changeset/hungry-ties-judge.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@vanilla-extract/css': minor
---

Support excluding file names from `generateIdentifier` output. This is available by passing a newly-added options object rather than a string.

**Example usage**

```ts
import { generateIdentifier } from '@vanilla-extract/css';

const identifier = generateIdentifier({
debugId,
debugFileName: false,
});
```
5 changes: 5 additions & 0 deletions .changeset/popular-seas-relate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@vanilla-extract/css': patch
---

Fix file name prefix in debug names when file extension is `.cjs` or `.mjs`.
40 changes: 36 additions & 4 deletions packages/css/src/identifier.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,58 @@ import { generateIdentifier } from './identifier';

describe('identifier', () => {
beforeAll(() => {
setFileScope('test');
setFileScope('path/to/file.css.ts');
});

afterAll(() => {
endFileScope();
});

it(`should create a valid identifier`, () => {
it(`should ignore file scopes without a file extension when creating a path prefix`, () => {
setFileScope('test');
expect(generateIdentifier(undefined)).toMatchInlineSnapshot(`"skkcyc0"`);
endFileScope();
});

it(`should create a valid identifier`, () => {
expect(generateIdentifier(undefined)).toMatchInlineSnapshot(
`"file__18bazsm0"`,
);
});

it('should create a valid identifier with a debug id', () => {
expect(generateIdentifier('debug')).toMatchInlineSnapshot(
`"debug__skkcyc1"`,
`"file_debug__18bazsm1"`,
);
});

it('should create a valid identifier with a debug id with whitespace', () => {
expect(generateIdentifier('debug and more')).toMatchInlineSnapshot(
`"debug_and_more__skkcyc2"`,
`"file_debug_and_more__18bazsm2"`,
);
});

describe('options object', () => {
it(`should create a valid identifier`, () => {
expect(generateIdentifier({})).toMatchInlineSnapshot(`"file__18bazsm3"`);
});

it('should create a valid identifier with a debug id and with file name debugging explicitly enabled', () => {
expect(
generateIdentifier({ debugId: 'debug', debugFileName: true }),
).toMatchInlineSnapshot(`"file_debug__18bazsm4"`);
});

it('should create a valid identifier with a debug id and without file name debugging', () => {
expect(
generateIdentifier({ debugId: 'debug', debugFileName: false }),
).toMatchInlineSnapshot(`"debug__18bazsm5"`);
});

it('should create a valid identifier without a debug ID or file name', () => {
expect(
generateIdentifier({ debugFileName: false }),
).toMatchInlineSnapshot(`"_18bazsm6"`);
});
});
});
43 changes: 33 additions & 10 deletions packages/css/src/identifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,46 @@ import hash from '@emotion/hash';
import { getIdentOption } from './adapter';
import { getAndIncrementRefCounter, getFileScope } from './fileScope';

function getDevPrefix(debugId: string | undefined) {
function getDevPrefix({
debugId,
debugFileName,
}: {
debugId?: string;
debugFileName: boolean;
}) {
const parts = debugId ? [debugId.replace(/\s/g, '_')] : [];
const { filePath } = getFileScope();

const matches = filePath.match(
/(?<dir>[^\/\\]*)?[\/\\]?(?<file>[^\/\\]*)\.css\.(ts|js|tsx|jsx)$/,
);
if (debugFileName) {
const { filePath } = getFileScope();

const matches = filePath.match(
/(?<dir>[^\/\\]*)?[\/\\]?(?<file>[^\/\\]*)\.css\.(ts|js|tsx|jsx|cjs|mjs)$/,
);

if (matches && matches.groups) {
const { dir, file } = matches.groups;
parts.unshift(file && file !== 'index' ? file : dir);
if (matches && matches.groups) {
const { dir, file } = matches.groups;
parts.unshift(file && file !== 'index' ? file : dir);
}
}

return parts.join('_');
}

export function generateIdentifier(debugId: string | undefined) {
interface GenerateIdentifierOptions {
debugId?: string;
debugFileName?: boolean;
}

export function generateIdentifier(debugId?: string): string;
export function generateIdentifier(options?: GenerateIdentifierOptions): string;
export function generateIdentifier(
arg?: string | GenerateIdentifierOptions,
): string {
const { debugId, debugFileName = true } = {
...(typeof arg === 'string' ? { debugId: arg } : null),
...(typeof arg === 'object' ? arg : null),
};

// Convert ref count to base 36 for optimal hash lengths
const refCount = getAndIncrementRefCounter().toString(36);
const { filePath, packageName } = getFileScope();
Expand All @@ -31,7 +54,7 @@ export function generateIdentifier(debugId: string | undefined) {
let identifier = `${fileScopeHash}${refCount}`;

if (getIdentOption() === 'debug') {
const devPrefix = getDevPrefix(debugId);
const devPrefix = getDevPrefix({ debugId, debugFileName });

if (devPrefix) {
identifier = `${devPrefix}__${identifier}`;
Expand Down
23 changes: 7 additions & 16 deletions packages/css/src/vars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,20 @@ import {
MapLeafNodes,
CSSVarFunction,
} from '@vanilla-extract/private';
import hash from '@emotion/hash';
import cssesc from 'cssesc';

import { Tokens, NullableTokens, ThemeVars } from './types';
import { getAndIncrementRefCounter, getFileScope } from './fileScope';
import { validateContract } from './validateContract';
import { getIdentOption } from './adapter';
import { generateIdentifier } from './identifier';

export function createVar(debugId?: string): CSSVarFunction {
// Convert ref count to base 36 for optimal hash lengths
const refCount = getAndIncrementRefCounter().toString(36);
const { filePath, packageName } = getFileScope();
const fileScopeHash = hash(
packageName ? `${packageName}${filePath}` : filePath,
const cssVarName = cssesc(
generateIdentifier({
debugId,
debugFileName: false,
}),
{ isIdentifier: true },
);
const varName =
getIdentOption() === 'debug' && debugId
? `${debugId}__${fileScopeHash}${refCount}`
: `${fileScopeHash}${refCount}`;

const cssVarName = cssesc(varName.match(/^[0-9]/) ? `_${varName}` : varName, {
isIdentifier: true,
});

return `var(--${cssVarName})` as const;
}
Expand Down

0 comments on commit c38b152

Please sign in to comment.