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

chore: bump to angualr18 #15

Merged
merged 2 commits into from
Jul 1, 2024
Merged
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
11 changes: 11 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,14 @@ yarn.lock
dist
src/*.css
src/color.less

# Yarn
# yarn.lock
yarn-error.log
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
.pnp.*
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
18.19.1
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"request": "launch",
"name": "test",
"program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
"args": ["-r", "ts-node/register", "test/color-less.spec.ts"],
"args": ["-r", "ts-node/register", "test/theme-css.spec.ts"],
"env": {
"TS_NODE_PROJECT": "test/tsconfig.json"
},
Expand Down
3 changes: 1 addition & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
// Place your settings in this file to overwrite default and user settings.
{
"editor.codeActionsOnSave": {
// For ESLint
"source.fixAll.eslint": true
"source.fixAll.eslint": "explicit"
},
"[html]": {
"editor.formatOnSave": true
Expand Down
893 changes: 893 additions & 0 deletions .yarn/releases/yarn-4.0.2.cjs

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions .yarnrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
enableImmutableInstalls: false

nodeLinker: node-modules

yarnPath: .yarn/releases/yarn-4.0.2.cjs
2 changes: 1 addition & 1 deletion build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,5 @@ cp package.json dist/package.json
cp README.md dist/README.md

if [[ ${TEST} == true ]]; then
cp -fr dist/* ../ng-alain/node_modules/ng-alain-plugin-theme
cp -fr dist/* ../delon/node_modules/ng-alain-plugin-theme
fi
20 changes: 13 additions & 7 deletions lib/color-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,19 @@ let nodeModulesPath = '';

async function buildLess(content: string, config: ColorLessConfig): Promise<string> {
const options = {
javascriptEnabled: true,
paths: ['node_modules/'],
paths: [
join(root, 'node_modules/ng-zorro-antd/style/color'),
join(root, 'node_modules/@delon/theme/system/mixins'),
join(root, 'node_modules'),
],
...config.buildLessOptions,
};
if (config.debug) console.log(options);
const res = await less.render(content, options);
return res.css;
try {
const res = await less.render(content, options);
return res.css;
} catch (ex) {
throw new Error(`Less build error: ${ex}`);
}
}

/**
Expand Down Expand Up @@ -70,7 +76,7 @@ function randomColor() {
This function take primary color palette name and returns @primary-color dependent value
.e.g
Input: @primary-1
Output: color(~`colorPalette("@{primary-color}", ' 1 ')`)
Output: color(colorPalette("@primary-color", ' 1 '))
*/
function getShade(varName: string) {
const match = varName.match(/(.*)-(\d)/);
Expand All @@ -80,7 +86,7 @@ function getShade(varName: string) {
if (/primary-\d/.test(varName)) {
className = '@primary-color';
}
return 'color(~`colorPalette("@{' + className.replace('@', '') + '}", ' + match[2] + ')`)';
return 'color(colorPalette("@' + className.replace('@', '') + '", ' + match[2] + '))';
}

function generateColorMap(themeFilePath: string, config: ColorLessConfig): ColorLessKV {
Expand Down
148 changes: 60 additions & 88 deletions lib/theme-css.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { join } from 'path';
import { readFileSync, writeFileSync, existsSync, unlinkSync } from 'fs';
import { writeFileSync, existsSync, unlinkSync } from 'fs';
import less from 'less';
const lessToJs = require('less-vars-to-js');
const LessPluginCleanCSS = require('less-plugin-clean-css');

import { ThemeCssItem, BuildThemeCSSOptions, ThemeCssConfig } from './theme-css.types';
import { d, deepMergeKey, getJSON, mergePath } from './utils';
import { deepMergeKey, getJSON, mergePath } from './utils';

const root = process.cwd();
let node_modulesPath = '';
Expand Down Expand Up @@ -54,132 +53,105 @@ function fixConfig(config: ThemeCssConfig): ThemeCssConfig {
return config;
}

function genThemeVars(type: 'default' | 'dark' | 'compact', extraThemeVars: string[]): { [key: string]: string } {
const contents: string[] = [];
function genStripVar(item: ThemeCssItem): { [key: string]: string } {
const modifyVars = item.modifyVars || {};
const stripPrefixOfModifyVars: { [key: string]: string } = {};
Object.keys(modifyVars).forEach(key => {
const newKey = key.startsWith('@') ? key.substring(1) : key;
stripPrefixOfModifyVars[newKey] = modifyVars[key];
});
return stripPrefixOfModifyVars;
}

async function buildCss(options: BuildThemeCSSOptions, config: ThemeCssConfig): Promise<string> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const plugins: any[] = [];
if (options.min === true) {
plugins.push(new LessPluginCleanCSS({ advanced: true }));
}
return less
.render(options.content, {
plugins,
paths: [
join(root, 'node_modules/ng-zorro-antd/style/color'),
join(root, 'node_modules/@delon/theme/system/mixins'),
join(root, 'node_modules'),
],
...config.buildLessOptions,
modifyVars: {
...options.modifyVars,
},
})
.then(res => res.css);
}

function genThemeLess(type: 'default' | 'dark' | 'compact', extraThemeVars: string[]): string[] {
const list = [] as string[];
// ng-zorro-antd
const ngZorroAntdStylePath = join(root, node_modulesPath, 'ng-zorro-antd', 'style');
if (existsSync(ngZorroAntdStylePath)) {
contents.push(readFileSync(join(ngZorroAntdStylePath, 'color', 'colors.less'), 'utf-8'));
contents.push(readFileSync(join(ngZorroAntdStylePath, 'themes', `${type}.less`), 'utf-8'));
if (existsSync(join(root, node_modulesPath, 'ng-zorro-antd/style'))) {
list.push(`@import 'ng-zorro-antd/style/themes/${type}.less';`);
}
// @delon
const delonPath = join(root, node_modulesPath, '@delon');
// @delon/theme/system
const delonSystem = join(delonPath, 'theme');
if (existsSync(delonSystem)) {
[
join(delonSystem, 'system', `theme-${type}.less`),
join(delonSystem, 'layout-default', 'style', `theme-${type}.less`),
join(delonSystem, 'layout-blank', 'style', `theme-${type}.less`),
].forEach(filePath => {
if (!existsSync(filePath)) {
console.warn(`主题路径 ${filePath} 不存在`);
return;
}
contents.push(readFileSync(filePath, 'utf-8'));
});
if (existsSync(join(delonPath, 'theme'))) {
list.push(`@import '@delon/theme/system/theme-${type}.less';`);
list.push(`@import '@delon/theme/layout-default/style/theme-${type}.less';`);
list.push(`@import '@delon/theme/layout-blank/style/theme-${type}.less';`);
}
// abc & chart
['abc', 'chart'].forEach(libName => {
const libThemePath = join(delonPath, libName, `theme-${type}.less`);
if (existsSync(libThemePath)) {
contents.push(readFileSync(libThemePath, 'utf-8'));
list.push(`@import '@delon/${libName}/theme-${type}.less';`);
}
});

// 外部样式 extraThemeVars
if (Array.isArray(extraThemeVars) && extraThemeVars.length > 0) {
contents.push(
list.push(
...extraThemeVars.map(path => {
// 自动处理 src/app/layout/name/styles/theme-#NAME#.less之类的
const lessFilePath = join(root, path.replace(`#NAME#`, type));
if (!existsSync(lessFilePath)) {
return '';
}
return readFileSync(lessFilePath, 'utf-8');
return `@import '${lessFilePath}';`;
}),
);
}

return lessToJs(contents.join(''), {
stripPrefix: true,
resolveVariables: false,
});
}

function genVar(config: ThemeCssConfig, item: ThemeCssItem): { [key: string]: string } {
// eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
const fileContent = item.projectThemeVar?.map(path => readFileSync(join(root, path), 'utf-8'))!;
// add project theme
fileContent.push(readFileSync(join(root, config.projectStylePath!), 'utf-8'));
let projectTheme: { [key: string]: string } = {};
if (fileContent) {
projectTheme = lessToJs(fileContent.join(''), {
stripPrefix: true,
resolveVariables: false,
});
}
const modifyVars = item.modifyVars || {};
const stripPrefixOfModifyVars: { [key: string]: string } = {};
Object.keys(modifyVars).forEach(key => {
const newKey = key.startsWith('@') ? key.substr(1) : key;
stripPrefixOfModifyVars[newKey] = modifyVars[key];
});
const additionalThemeVars = config.additionalThemeVars!;
return {
...genThemeVars('default', additionalThemeVars),
...(item.theme === 'dark' ? genThemeVars('dark', additionalThemeVars) : null),
...(item.theme === 'compact' ? genThemeVars('compact', additionalThemeVars) : null),
...projectTheme,
...stripPrefixOfModifyVars,
};
}

async function buildCss(options: BuildThemeCSSOptions, config: ThemeCssConfig): Promise<string> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const plugins: any[] = [];
if (options.min === true) {
plugins.push(new LessPluginCleanCSS({ advanced: true }));
}
return less
.render(options.content, {
javascriptEnabled: true,
plugins,
paths: ['node_modules/'],
...config.buildLessOptions,
modifyVars: {
...options.modifyVars,
},
})
.then(res => res.css);
return list;
}

export async function buildThemeCSS(config: ThemeCssConfig): Promise<void> {
node_modulesPath = config.nodeModulesPath || 'node_modules';
config = fixConfig(config);

const promises = config.list?.map(item => {
const modifyVars = genVar(config, item);
d(config, 'All Modify Vars', modifyVars);
// const modifyVars = genVar(config, item);
// d(config, 'All Modify Vars', modifyVars);
const content = [
// 如果项目入口样子已经包含 【@import '~@delon/theme/system/index';】 所以则无须增加
// 否则部分 javascript less 变量会无法找到,例如:
// message:'error evaluating function `color`: JavaScript evaluation error: 'ReferenceError: colorPalette is not defined''
// `@import '${join(node_modulesPath + 'ng-zorro-antd/style/color/colors.less')}'`,
`@import '${config.projectStylePath}';`,
...config.additionalLibraries!.map(v => `@import '${v}';`),
// 强制主题变量优先级最高
...genThemeLess(item.theme || 'default', config.additionalThemeVars ?? []),
].join('');
const options: BuildThemeCSSOptions = {
min: config.min,
content,
modifyVars,
modifyVars: genStripVar(item),
};
if (existsSync(item.filePath!)) {
unlinkSync(item.filePath!);
}
return buildCss(options, config).then(css => {
writeFileSync(item.filePath!, css);
console.log(`✅ Style '${item.key}' generated successfully. Output: ${item.filePath!}`);
});
return buildCss(options, config)
.then(css => {
writeFileSync(item.filePath!, css);
console.log(`✅ Style '${item.key}' generated successfully. Output: ${item.filePath!}`);
})
.catch(ex => {
console.error(`❌ Style '${item.key}' generation failed. ${ex.message}`);
});
});

await Promise.all(promises!);
Expand Down
14 changes: 7 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ng-alain-plugin-theme",
"version": "16.0.1",
"version": "18.0.0",
"description": "NG-ALAIN theme plugin",
"keywords": [
"delon",
Expand Down Expand Up @@ -33,17 +33,16 @@
"release:next": "npm run build && cd dist && npm publish --access public --tag next"
},
"dependencies": {
"meow": "^9.0.0",
"jsonc-parser": "^3.2.0",
"less": "^4.1.3",
"less-plugin-clean-css": "^1.5.1",
"less-vars-to-js": "^1.3.0",
"postcss-less": "^6.0.0",
"postcss": "^8.4.18"
"meow": "^9.0.0",
"postcss": "^8.4.18",
"postcss-less": "^6.0.0"
},
"devDependencies": {
"ng-zorro-antd": "^16.2.2",
"@delon/theme": "^16.4.2",
"@delon/theme": "^17.0.0",
"@types/chai": "^4.3.3",
"@types/less": "^3.0.3",
"@types/meow": "^6.0.0",
Expand All @@ -54,9 +53,10 @@
"chai": "^4.3.6",
"eslint": "^8.26.0",
"mocha": "^10.1.0",
"ng-zorro-antd": "^18.0.0",
"postcss": "^8.4.18",
"postcss-less": "^6.0.0",
"ts-node": "^10.9.1",
"typescript": "*"
"typescript": "~5.4.2"
}
}
Loading