Skip to content

Commit

Permalink
fix(formula): fix formula facade import (#4438)
Browse files Browse the repository at this point in the history
  • Loading branch information
hexf00 authored Jan 10, 2025
1 parent a1b7a16 commit b1e4ae8
Show file tree
Hide file tree
Showing 10 changed files with 193 additions and 20 deletions.
9 changes: 9 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,15 @@ and then run the following command to run E2E tests:
pnpm test:e2e
```

### Build Preview

After building, the output may differ from the source code. To test for any differences, you can link to the built artifacts using:

```shell
pnpm build
pnpm dev:libs
```

### Update Snapshots

Univer uses Playwright to perform visual comparison tests. If you have made changes to the UI, the CI may fail due to visual differences. You can update the snapshots by running this GitHub Action [📸 Manually Update Snapshots · Workflow runs · dream-num/univer (github.com)](https://github.com/dream-num/univer/actions/workflows/update-snapshots-manually.yml) on your branch.
Expand Down
106 changes: 106 additions & 0 deletions examples/esbuild.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,12 @@ import cleanPlugin from 'esbuild-plugin-clean';
import copyPlugin from 'esbuild-plugin-copy';
import vue from 'esbuild-plugin-vue3';
import stylePlugin from 'esbuild-style-plugin';
import glob from 'fast-glob';
import fs from 'fs-extra';
import minimist from 'minimist';
import tailwindcss from 'tailwindcss';

const LINK_TO_LIB = process.env.LINK_TO_LIB === 'true';
const nodeModules = path.resolve(process.cwd(), './node_modules');

const args = minimist(process.argv.slice(2));
Expand All @@ -41,6 +44,104 @@ const monacoEditorEntryPoints = [
'vs/editor/editor.worker.js',
];

/**
* fix `import '@univerjs/xxx/lib/index.css'` not work on source code dev mode
*
* The `stylePlugin` must be loaded after the `skipLibCssEsbuildPlugin`.
*/
const skipLibCssEsbuildPlugin = {
name: 'skip-lib-css-esbuild-plugin',
setup(build) {
console.log('[skip-lib-css-esbuild-plugin] enabled, resolve will skip `import \'@univerjs/xxx/lib/**/*.css\'`');

build.onResolve({ filter: /\/lib\/.*\.css$/ }, async (args) => {
if (args.path.includes('@univerjs/')) {
return {
path: args.path,
namespace: 'univer-lib-css',
};
}
});

build.onLoad({ filter: /.*/, namespace: 'univer-lib-css' }, async () => {
// return virtual css content
return {
contents: '',
loader: 'css',
};
});
},
};

/**
* Add this function to generate aliases
*/
function generateAliases() {
const aliases = {};
const packagesRoots = ['packages', 'packages-experimental'].map((dir) =>
path.resolve(__dirname, '..', dir)
);

for (const packagesRoot of packagesRoots) {
if (!fs.existsSync(packagesRoot)) continue;

// Find all package.json files in subdirectories
const packageJsonPaths = glob.sync('*/package.json', { cwd: packagesRoot });

for (const packageJsonPath of packageJsonPaths) {
const pkgDir = path.join(packagesRoot, path.dirname(packageJsonPath));
const pkgJson = fs.readJSONSync(path.join(packagesRoot, packageJsonPath));
const exportsConfig = pkgJson.publishConfig?.exports;

if (!exportsConfig) continue;

// Add main package alias
if (exportsConfig['.']) {
aliases[pkgJson.name] = path.resolve(pkgDir, exportsConfig['.'].import);
}

const getValue = (val: { import: string } | string) => {
if (typeof val === 'string') {
return val;
}
return val.import;
};
// Add subpath aliases
Object.entries(exportsConfig as Record<string, { import: string } | string>).forEach(([key, value]) => {
try {
if (key === '.') {
aliases[pkgJson.name] = path.resolve(pkgDir, exportsConfig['.'].import);
} else if (key === './lib/*') {
const cssFile = path.resolve(pkgDir, getValue(value).replace('*', 'index.css'));
if (fs.existsSync(cssFile)) {
aliases[`${pkgJson.name}/lib/index.css`] = cssFile;
}
} else if (key === './*') {
// do nothing
} else if (key === './locale/*') {
const locales = ['en-US', 'fr-FR', 'ru-RU', 'zh-CN', 'zh-TW', 'vi-VN', 'fa-IR'];
locales.forEach((lang) => {
aliases[`${pkgJson.name}/locale/${lang}`] = path.resolve(pkgDir, getValue(value).replace('*', lang));
});
} else {
const aliasKey = `${pkgJson.name}/${key.replace('./', '')}`;
const aliasPath = path.resolve(pkgDir, getValue(value));
aliases[aliasKey] = aliasPath;
}
} catch (e) {
console.error(`Error generating aliases for ${pkgJson.name}: ${e.message}`);
process.exit(1);
}
});
}
}

return aliases;
}

/**
* Build monaco editor's resources for web worker
*/
function monacoBuildTask() {
return esbuild.build({
entryPoints: monacoEditorEntryPoints.map((entry) => `./node_modules/monaco-editor/esm/${entry}`),
Expand Down Expand Up @@ -141,6 +242,7 @@ const config: SameShape<BuildOptions, BuildOptions> = {
to: ['./'],
},
}),
...(LINK_TO_LIB ? [] : [skipLibCssEsbuildPlugin]),
stylePlugin({
postcss: {
plugins: [tailwindcss],
Expand All @@ -160,8 +262,12 @@ const config: SameShape<BuildOptions, BuildOptions> = {
entryPoints,
outdir: './local',
define,
alias: LINK_TO_LIB ? generateAliases() : {},
};

/**
* Build the project
*/
async function main() {
if (args.watch) {
const ctx = await esbuild.context(config);
Expand Down
3 changes: 3 additions & 0 deletions examples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"prepare": "tsx ./scripts/generate-locales.ts && tsx ./scripts/generate-html.ts",
"build:demo": "tsx ./esbuild.config.ts",
"dev:demo": "tsx ./esbuild.config.ts --watch",
"dev:demo-libs": "cross-env LINK_TO_LIB=true tsx ./esbuild.config.ts --watch",
"dev:e2e": "tsx ./esbuild.config.ts --watch --e2e",
"build:e2e": "tsx ./esbuild.config.ts --e2e",
"lint:types": "tsc --noEmit"
Expand Down Expand Up @@ -78,12 +79,14 @@
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@univerjs-infra/shared": "workspace:*",
"cross-env": "^7.0.3",
"detect-port": "^1.6.1",
"esbuild": "^0.24.2",
"esbuild-plugin-clean": "^1.0.1",
"esbuild-plugin-copy": "^2.1.1",
"esbuild-plugin-vue3": "^0.4.2",
"esbuild-style-plugin": "^1.6.3",
"fast-glob": "^3.3.3",
"fs-extra": "^11.2.0",
"less": "^4.2.1",
"minimist": "^1.2.8",
Expand Down
1 change: 1 addition & 0 deletions examples/src/sheets/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import '@univerjs/sheets-find-replace/facade';
import '@univerjs/sheets-drawing-ui/facade';
import '@univerjs/sheets-zen-editor/facade';
import '../global.css';
import './styles';

/* eslint-disable-next-line node/prefer-global/process */
const IS_E2E: boolean = !!process.env.IS_E2E;
Expand Down
32 changes: 32 additions & 0 deletions examples/src/sheets/styles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Copyright 2023-present DreamNum Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import '@univerjs/sheets-ui/lib/index.css';
import '@univerjs/ui/lib/index.css';
import '@univerjs/design/lib/index.css';
import '@univerjs/docs-ui/lib/index.css';
import '@univerjs/sheets-formula-ui/lib/index.css';
import '@univerjs/sheets-numfmt-ui/lib/index.css';
import '@univerjs/drawing-ui/lib/index.css';
import '@univerjs/docs-drawing-ui/lib/index.css';
import '@univerjs/sheets-data-validation-ui/lib/index.css';
import '@univerjs/sheets-filter-ui/lib/index.css';
import '@univerjs/find-replace/lib/index.css';
import '@univerjs/sheets-hyper-link-ui/lib/index.css';
import '@univerjs/sheets-sort-ui/lib/index.css';
import '@univerjs/thread-comment-ui/lib/index.css';
import '@univerjs/sheets-zen-editor/lib/index.css';
import '@univerjs/uniscript/lib/index.css';
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"prepare": "husky install",
"pre-commit": "lint-staged",
"dev": "turbo dev:demo",
"dev:libs": "pnpm --filter univer-examples dev:demo-libs",
"dev:e2e": "pnpm --filter univer-examples dev:e2e",
"lint:types": "turbo lint:types",
"test": "turbo test -- --passWithNoTests",
Expand Down
1 change: 0 additions & 1 deletion packages/engine-formula/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,6 @@ export { FormulaExecutedStateType, FormulaExecuteStageType, FormulaRuntimeServic
export { ISuperTableService } from './services/super-table.service';
export { SuperTableService } from './services/super-table.service';
export { deserializeRangeWithSheetWithCache } from './engine/utils/reference-cache';
export { FFormula } from './facade/f-formula';
export { FormulaDependencyTree, type IFormulaDependencyTree } from './engine/dependency/dependency-tree';
export { type IOtherFormulaData } from './basics/common';
export { FormulaDependencyTreeType } from './engine/dependency/dependency-tree';
Expand Down
6 changes: 3 additions & 3 deletions packages/facade/src/apis/__tests__/facade.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,11 +380,11 @@ describe('Test FUniver', () => {
expect(range.getComment()).toBeNull();
});

it('Function registerFunction should handle async function', () => {
const functionName = 'ASYNCFUNC';
it('Function registerFunction should handle function', () => {
const functionName = 'CUSTOMFUNC';
const functionsDisposable = univerAPI.getFormula().registerFunction(functionName, () => {
return 42;
}, 'Async custom function');
}, 'Custom function');

const descriptionService = get(IDescriptionService);
const functionInfo = descriptionService.getFunctionInfo(functionName);
Expand Down
11 changes: 8 additions & 3 deletions packages/sheets-formula/src/facade/f-formula.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ import type { IDisposable, ILocales } from '@univerjs/core';
import type { IFunctionInfo } from '@univerjs/engine-formula';
import type { CalculationMode, IRegisterAsyncFunction, IRegisterFunction, ISingleFunctionRegisterParams, IUniverSheetsFormulaBaseConfig } from '@univerjs/sheets-formula';
import { debounce, IConfigService, ILogService, LifecycleService, LifecycleStages } from '@univerjs/core';
import { FFormula, SetFormulaCalculationStartMutation } from '@univerjs/engine-formula';
import { SetFormulaCalculationStartMutation } from '@univerjs/engine-formula';
import { FFormula } from '@univerjs/engine-formula/facade';
import { IRegisterFunctionService, PLUGIN_CONFIG_KEY_BASE, RegisterFunctionService } from '@univerjs/sheets-formula';

export interface IFFormulaSheetsMixin {
Expand Down Expand Up @@ -88,6 +89,8 @@ export interface IFFormulaSheetsMixin {
* @param name - The name of the function to register. This will be used in formulas (e.g., =MYFUNC())
* @param func - The implementation of the function
* @param options - Object containing locales and description
* @param options.locales - Object containing locales
* @param options.description - Object containing description
* @returns A disposable object that will unregister the function when disposed
* @example
* ```js
Expand Down Expand Up @@ -148,7 +151,9 @@ export interface IFFormulaSheetsMixin {
* Register a custom asynchronous formula function with description.
* @param name - The name of the function to register. This will be used in formulas (e.g., =ASYNCFUNC())
* @param func - The async implementation of the function
* @param description - A string describing the function's purpose and usage
* @param options - Object containing locales and description
* @param options.locales - Object containing locales
* @param options.description - Object containing description
* @returns A disposable object that will unregister the function when disposed
* @example
* ```js
Expand Down Expand Up @@ -287,7 +292,7 @@ export class FFormulaSheetsMixin extends FFormula implements IFFormulaSheetsMixi
}

FFormula.extend(FFormulaSheetsMixin);
declare module '@univerjs/engine-formula' {
declare module '@univerjs/engine-formula/facade' {
// eslint-disable-next-line ts/naming-convention
interface FFormula extends IFFormulaSheetsMixin {}
}
Loading

0 comments on commit b1e4ae8

Please sign in to comment.