Skip to content

Commit

Permalink
Add displayName, fix formats
Browse files Browse the repository at this point in the history
  • Loading branch information
lxsmnsyc committed Jan 15, 2024
1 parent c2e6b78 commit b39c83f
Show file tree
Hide file tree
Showing 26 changed files with 297 additions and 593 deletions.
51 changes: 27 additions & 24 deletions biome.json
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
{
"$schema": "https://unpkg.com/@biomejs/biome/configuration_schema.json",
"files": {
"ignore": [
"node_modules/**/*"
]
"ignore": ["node_modules/**/*"]
},
"vcs": {
"useIgnoreFile": true
},
"linter": {
"enabled": true,
"ignore": [
"node_modules/**/*"
],
"ignore": ["node_modules/**/*"],
"rules": {
"a11y": {
"noAccessKey": "error",
"noAriaHiddenOnFocusable": "off",
"noAriaUnsupportedElements": "error",
"noAutofocus": "error",
"noBlankTarget": "error",
Expand All @@ -41,17 +38,13 @@
"useMediaCaption": "error",
"useValidAnchor": "error",
"useValidAriaProps": "error",
"useValidAriaRole": "error",
"useValidAriaValues": "error",
"useValidLang": "error"
},
"complexity": {
"noBannedTypes": "error",
"noExcessiveCognitiveComplexity": {
"level": "error",
"options": {
"maxAllowedComplexity": 15
}
},
"noExcessiveCognitiveComplexity": "error",
"noExtraBooleanCast": "error",
"noForEach": "error",
"noMultipleSpacesInRegularExpressionLiterals": "warn",
Expand All @@ -72,6 +65,7 @@
"useFlatMap": "error",
"useLiteralKeys": "error",
"useOptionalChain": "warn",
"useRegexLiterals": "error",
"useSimpleNumberKeys": "error",
"useSimplifiedLogicExpression": "error"
},
Expand Down Expand Up @@ -121,6 +115,7 @@
"style": {
"noArguments": "error",
"noCommaOperator": "off",
"noDefaultExport": "off",
"noImplicitBoolean": "error",
"noInferrableTypes": "error",
"noNamespace": "error",
Expand Down Expand Up @@ -180,6 +175,7 @@
"noFunctionAssign": "error",
"noGlobalIsFinite": "error",
"noGlobalIsNan": "error",
"noImplicitAnyLet": "off",
"noImportAssign": "error",
"noLabelVar": "error",
"noMisleadingInstantiator": "error",
Expand All @@ -199,27 +195,36 @@
"useValidTypeof": "error"
},
"nursery": {
"noAriaHiddenOnFocusable": "off",
"noDefaultExport": "off",
"noDuplicateJsonKeys": "off",
"noEmptyBlockStatements": "error",
"noImplicitAnyLet": "off",
"noEmptyTypeParameters": "error",
"noGlobalEval": "off",
"noGlobalAssign": "error",
"noInvalidUseBeforeDeclaration": "error",
"noMisleadingCharacterClass": "error",
"noNodejsModules": "off",
"noThenProperty": "warn",
"noUnusedImports": "error",
"noUnusedPrivateClassMembers": "error",
"noUselessLoneBlockStatements": "error",
"noUselessTernary": "error",
"useAwait": "error",
"useConsistentArrayType": "error",
"useExportType": "error",
"useFilenamingConvention": "off",
"useForOf": "warn",
"useGroupedTypeImport": "error",
"useImportRestrictions": "off",
"useRegexLiterals": "error",
"useValidAriaRole": "error"
"useImportType": "error",
"useNodejsImportProtocol": "warn",
"useNumberNamespace": "error",
"useShorthandFunctionType": "warn"
}
}
},
"formatter": {
"enabled": true,
"ignore": [
"node_modules/**/*"
],
"ignore": ["node_modules/**/*"],
"formatWithErrors": false,
"indentWidth": 2,
"indentStyle": "space",
Expand All @@ -228,9 +233,7 @@
},
"organizeImports": {
"enabled": true,
"ignore": [
"node_modules/**/*"
]
"ignore": ["node_modules/**/*"]
},
"javascript": {
"formatter": {
Expand Down Expand Up @@ -266,4 +269,4 @@
"allowTrailingCommas": false
}
}
}
}
6 changes: 3 additions & 3 deletions examples/react/vite.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import forgettiPlugin from 'vite-plugin-forgetti';

export default defineConfig({
Expand All @@ -13,6 +13,6 @@ export default defineConfig({
include: 'src/**/*.{ts,js,tsx,jsx}',
exclude: 'node_modules/**/*.{ts,js,tsx,jsx}',
},
})
}),
],
});
11 changes: 3 additions & 8 deletions lerna.json
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
{
"packages": [
"packages/*",
"examples/*"
],
"npmClient": "pnpm",
"packages": ["packages/*", "examples/*"],
"command": {
"version": {
"exact": true
},
"publish": {
"allowBranch": [
"main",
"next"
],
"allowBranch": ["main", "next"],
"registry": "https://registry.npmjs.org/"
}
},
Expand Down
9 changes: 3 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
{
"name": "root",
"private": true,
"workspaces": [
"packages/*",
"examples/*"
],
"workspaces": ["packages/*", "examples/*"],
"devDependencies": {
"@biomejs/biome": "^1.4.1",
"@biomejs/biome": "^1.5.1",
"lerna": "^7.4.1",
"typescript": "^5.2.2"
}
}
}
12 changes: 4 additions & 8 deletions packages/forgetti/example.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
import * as babel from '@babel/core';
import plugin from 'forgetti';
import { readFile } from 'fs/promises';
import { readFile } from 'node:fs/promises';

const options = {
preset: 'react',
};

async function compile(code) {
const result = await babel.transformAsync(code, {
plugins: [
[plugin, options],
],
plugins: [[plugin, options]],
parserOpts: {
plugins: [
'jsx',
],
plugins: ['jsx'],
},
});

return result?.code ?? '';
}

console.log(await compile(await readFile('./input.js', 'utf-8')));
console.log(await compile(await readFile('./input.js', 'utf-8')));
8 changes: 6 additions & 2 deletions packages/forgetti/input.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
function Example(props) {
return <styled.H1>{props.greeting}, {props.receiver}!</styled.H1>;
}
return (
<styled.H1>
{props.greeting}, {props.receiver}!
</styled.H1>
);
}
3 changes: 2 additions & 1 deletion packages/forgetti/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@
"devDependencies": {
"@babel/core": "^7.23.2",
"@types/babel__core": "^7.20.3",
"@types/babel__helper-module-imports": "^7.18.3",
"@types/babel__traverse": "^7.20.3",
"@types/node": "^20.8.7",
"pridepack": "2.5.1",
"pridepack": "2.6.0",
"tslib": "^2.6.2",
"typescript": "^5.2.2",
"vitest": "^0.34.6"
Expand Down
2 changes: 1 addition & 1 deletion packages/forgetti/pridepack.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
".": "src/index.ts",
"./runtime": "runtime/index.ts"
}
}
}
22 changes: 19 additions & 3 deletions packages/forgetti/runtime/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@ export function $$cache(hook: MemoHook, size: number): unknown[] {
return hook(() => new Array<unknown>(size), EMPTY_ARRAY);
}

export function $$branch(parent: unknown[], index: number, size: number): unknown[] {
export function $$branch(
parent: unknown[],
index: number,
size: number,
): unknown[] {
parent[index] ||= new Array(size);
return parent[index] as unknown[];
}
Expand All @@ -45,7 +49,10 @@ function arePropsEqual(prev: MemoProps, next: MemoProps): boolean {
return true;
}

type MemoComponent = (props: MemoProps) => unknown;
interface MemoComponent {
(props: MemoProps): unknown;
displayName: string;
}

export type MemoFunction = (
Component: MemoComponent,
Expand All @@ -54,7 +61,16 @@ export type MemoFunction = (

export function $$memo(
memoFunc: MemoFunction,
name: string,
render: (values: unknown[]) => unknown,
): MemoComponent {
return memoFunc((props: MemoProps) => render(props.v), arePropsEqual);
const OriginalComponent = (props: MemoProps) => render(props.v);
if (import.meta.env.DEV) {
OriginalComponent.displayName = `Forgetti(${name}.render)`;
}
const Component = memoFunc(OriginalComponent, arePropsEqual);
if (import.meta.env.DEV) {
Component.displayName = `Forgetti(${name}.template)`;
}
return Component;
}
42 changes: 42 additions & 0 deletions packages/forgetti/src/core/get-descriptive-name.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type * as babel from '@babel/core';

export function getDescriptiveName(
path: babel.NodePath,
defaultName: string,
): string {
let current: babel.NodePath | null = path;
while (current) {
switch (current.node.type) {
case 'FunctionDeclaration':
case 'FunctionExpression': {
if (current.node.id) {
return current.node.id.name;
}
break;
}
case 'VariableDeclarator': {
if (current.node.id.type === 'Identifier') {
return current.node.id.name;
}
break;
}
case 'ClassPrivateMethod':
case 'ClassMethod':
case 'ObjectMethod': {
switch (current.node.key.type) {
case 'Identifier':
return current.node.key.name;
case 'PrivateName':
return current.node.key.id.name;
default:
break;
}
break;
}
default:
break;
}
current = current.parentPath;
}
return defaultName;
}
9 changes: 7 additions & 2 deletions packages/forgetti/src/core/optimize-jsx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import getImportIdentifier from './get-import-identifier';
import { RUNTIME_MEMO } from './imports';
import { shouldSkipJSX, isPathValid } from './checks';
import type { ImportDefinition } from './presets';
import { getDescriptiveName } from './get-descriptive-name';

interface JSXReplacement {
id: t.Identifier;
Expand Down Expand Up @@ -125,7 +126,8 @@ function extractJSXExpressionsFromJSXElement(
const isJSXMember = isPathValid(openingName, t.isJSXMemberExpression);
if (isPathValid(trueOpeningName, t.isJSXIdentifier)) {
if (isJSXMember || /^[A-Z_]/.test(trueOpeningName.node.name)) {
const id = path.scope.generateUidIdentifier('Component');
const descriptiveName = getDescriptiveName(path, 'Component');
const id = path.scope.generateUidIdentifier(descriptiveName);
const index = state.expressions.length;
state.expressions.push(t.identifier(trueOpeningName.node.name));
state.jsxs.push({
Expand Down Expand Up @@ -219,7 +221,9 @@ function transformJSX(
};
extractJSXExpressions(path, state, true);

const memoComponent = path.scope.generateUidIdentifier('Memo');
const memoComponent = path.scope.generateUidIdentifier(
getDescriptiveName(path, 'Memo'),
);

let body: t.Expression | t.BlockStatement;
if (state.jsxs.length) {
Expand All @@ -241,6 +245,7 @@ function transformJSX(
id: memoComponent,
init: t.callExpression(getImportIdentifier(ctx, path, RUNTIME_MEMO), [
getImportIdentifier(ctx, path, memoDefinition),
t.stringLiteral(memoComponent.name),
t.arrowFunctionExpression([state.source], body),
]),
});
Expand Down
2 changes: 1 addition & 1 deletion packages/forgetti/src/core/optimizer-scope.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as babel from '@babel/core';
import type * as babel from '@babel/core';
import * as t from '@babel/types';
import type { OptimizedExpression, StateContext } from './types';
import getImportIdentifier from './get-import-identifier';
Expand Down
4 changes: 0 additions & 4 deletions packages/forgetti/src/core/simplify-expressions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,6 @@ export function simplifyExpressions(path: babel.NodePath<ComponentNode>): void {
);
break;
}
default:
break;
}
},
},
Expand All @@ -105,8 +103,6 @@ export function simplifyExpressions(path: babel.NodePath<ComponentNode>): void {
}
break;
}
default:
break;
}
},
},
Expand Down
2 changes: 1 addition & 1 deletion packages/forgetti/src/core/unwrap-path.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as babel from '@babel/core';
import type * as babel from '@babel/core';
import type * as t from '@babel/types';
import { isNestedExpression, isPathValid } from './checks';

Expand Down
Loading

0 comments on commit b39c83f

Please sign in to comment.