Skip to content

Commit

Permalink
feat: update demo of tt platform
Browse files Browse the repository at this point in the history
  • Loading branch information
zamhown committed Feb 23, 2024
1 parent 0cffa4d commit aea7985
Show file tree
Hide file tree
Showing 9 changed files with 852 additions and 28 deletions.
671 changes: 653 additions & 18 deletions common/config/rush/pnpm-lock.yaml

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
/**
* Clone From: https://github.com/boenfu/vite-plugin-semi-theme/blob/main/index.js
*
* PNPM 定制Semi DSM 替换 Plugin
*/
import FS from 'fs';
import Path from 'path';

import { pathToFileURL } from 'url';

import pkg from 'sass';
import { platform } from 'os';
const { compileString, Logger } = pkg;

function getSubdirectories(directory) {
const subDirectories = [];
// 读取当前文件夹内容
const filesAndFolders = FS.readdirSync(directory);
for (let i = 0; i < filesAndFolders.length; i++) {
const fileOrFolderPath = directory + '/' + filesAndFolders[i];
// 判断是否为文件夹
if (FS.statSync(fileOrFolderPath).isDirectory()) {
subDirectories.push(fileOrFolderPath);
}
}
return subDirectories;
}

/**
* @type {(options:{
* theme: string;
* options?: {
* prefixCls?: string;
* variables?: {[key: string]: string | number};
* include?: string;
* };
* })=>any}
*
* @note 阅读 webpack 版本代码的理解
* 1. 解析 css 到对应 scss
* 2. 替换 scss 内容
* 3. 再构建成对应的 css
*/
export default function SemiPlugin({ theme, options = {} }) {
const PROJECT_ROOT = process.cwd();
const NODE_MODULES_ROOT =
PROJECT_ROOT.substring(0, PROJECT_ROOT.indexOf('/packages/')) + '/common/temp/node_modules/.pnpm';
const modulePathList = getSubdirectories(NODE_MODULES_ROOT);

return {
name: 'semi-theme',
enforce: 'post',
load(id) {
const filePath = normalizePath(id);
if (options.include) {
options.include = normalizePath(options.include);
}
// https://github.com/DouyinFE/semi-design/blob/main/packages/semi-webpack/src/semi-webpack-plugin.ts#L83
if (/@douyinfe\/semi-(ui|icons|foundation)\/lib\/.+\.css$/.test(filePath)) {
const scssFilePath = filePath.replace(/\.css$/, '.scss');

// 目前只有 name
// https://github.com/DouyinFE/semi-design/blob/04d17a72846dfb5452801a556b6e01f9b0e8eb9d/packages/semi-webpack/src/semi-webpack-plugin.ts#L23
const semiSemiLoaderOptions = { name: theme };

return compileString(
// TODO (boen): 未解析 file query
loader(FS.readFileSync(scssFilePath), {
...semiSemiLoaderOptions,
...options,
variables: convertMapToString(options.variables || {})
}),
{
importers: [
{
findFileUrl(url) {
if (url.startsWith('~')) {
url = url.substring(1);
const urlPath = url.split('/');
let module =
modulePathList.find(path => path.includes(urlPath.slice(0, 2).join('+') + '@')) ??
modulePathList.find(path => path.includes(urlPath[0] + '@'));
if (module) {
return pathToFileURL(module + '/node_modules/' + url);
}
}

const filePath = Path.resolve(Path.dirname(scssFilePath), url);

if (FS.existsSync(filePath)) {
return pathToFileURL(filePath);
}

return null;
}
}
],
logger: Logger.silent
}
).css;
}
}
};
}

// copy from https://github.com/DouyinFE/semi-design/blob/main/packages/semi-webpack/src/semi-theme-loader.ts
function loader(source, options) {
let fileStr = source.toString('utf8');

const theme = options.name || '@douyinfe/semi-theme-default';
// always inject
const scssVarStr = `@import "~${theme}/scss/index.scss";\n`;
// inject once
const cssVarStr = `@import "~${theme}/scss/global.scss";\n`;
// [vite-plugin]: sync from https://github.com/DouyinFE/semi-design/commit/a6064489a683495a737cbe7abd72c0b49a3bcd06
let animationStr = `@import "~${theme}/scss/animation.scss";\n`;

try {
require.resolve(`${theme}/scss/animation.scss`);
} catch (e) {
animationStr = ''; // fallback to empty string
}

const shouldInject = fileStr.includes('semi-base');

let componentVariables;

try {
componentVariables = resolve.sync(this.context, `${theme}/scss/local.scss`);
} catch (e) {}

if (options.include || options.variables || componentVariables) {
let localImport = '';
if (componentVariables) {
localImport += `\n@import "~${theme}/scss/local.scss";`;
}
if (options.include) {
localImport += `\n@import "${options.include}";`;
}
if (options.variables) {
localImport += `\n${options.variables}`;
}
try {
const regex = /(@import '.\/variables.scss';?|@import ".\/variables.scss";?)/g;
const fileSplit = fileStr.split(regex).filter(item => Boolean(item));
if (fileSplit.length > 1) {
fileSplit.splice(fileSplit.length - 1, 0, localImport);
fileStr = fileSplit.join('');
}
} catch (error) {}
}

// inject prefix
const prefixCls = options.prefixCls || 'semi';

const prefixClsStr = `$prefix: '${prefixCls}';\n`;

if (shouldInject) {
return `${animationStr}${cssVarStr}${scssVarStr}${prefixClsStr}${fileStr}`;
} else {
return `${scssVarStr}${prefixClsStr}${fileStr}`;
}
}

// copy from https://github.com/DouyinFE/semi-design/blob/main/packages/semi-webpack/src/semi-webpack-plugin.ts#L136
function convertMapToString(map) {
return Object.keys(map).reduce(function (prev, curr) {
return prev + `${curr}: ${map[curr]};\n`;
}, '');
}

function normalizePath(id) {
return Path.posix.normalize(platform() === 'win32' ? id.replace(/\\/g, '/') : id);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from 'react';

import Layout from './pages/Layout';

import './global.css';
import './global.scss';

const App = () => {
return <Layout />;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
@import '@douyinfe/semi-ui/dist/css/semi.min.css';
@import '@semi-bot/semi-theme-ttpd-internal/semi.min.css';

body {
margin: 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Nav, Layout } from '@douyinfe/semi-ui';
import { IconStar } from '@douyinfe/semi-icons';
import Chart from '../Chart';
import Logo from '../logo';
import './index.css';
import './index.scss';

function App() {
// Set up Layout's elements
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
@import '@douyinfe/semi-ui/dist/css/semi.min.css';
@import '@semi-bot/semi-theme-ttpd-internal/semi.min.css';

.App {
text-align: center;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
import svgr from 'vite-plugin-svgr';
import SemiPlugin from './script/semi-plugin';
import sass from 'sass';

export default defineConfig({
server: {
Expand All @@ -12,5 +14,16 @@ export default defineConfig({
__DEV__: true,
__VERSION__: JSON.stringify(require('../../../package.json').version)
},
plugins: [react(), svgr()]
buildOptions: {
scss: {
implementation: sass
}
},
plugins: [
react(),
svgr(),
SemiPlugin({
theme: '@semi-bot/semi-theme-ttpd-internal'
})
]
});
4 changes: 3 additions & 1 deletion packages/vchart-tt-platform-theme/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,14 @@
"@vitejs/plugin-react-swc": "^3.4.1",
"vite": "^4.5.0",
"vite-plugin-svgr": "^4.1.0",
"node-sass": "^9.0.0",
"@babel/runtime": "latest",
"@visactor/vchart": "~1.9.0",
"@visactor/react-vchart": "~1.9.0",
"@douyinfe/semi-ui": "^2.51.3",
"@douyinfe/semi-icons": "latest",
"@douyinfe/semi-icons-lab": "latest"
"@douyinfe/semi-icons-lab": "latest",
"@semi-bot/semi-theme-ttpd-internal": "latest"
},
"publishConfig": {
"access": "public"
Expand Down
8 changes: 4 additions & 4 deletions packages/vchart-tt-platform-theme/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ export const initVChartTTPlatformTheme = (options?: IInitVChartSemiThemeOption)
themeManager = ThemeManager
} = options ?? {};

switchVChartSemiTheme(themeManager, false, defaultMode);
switchVChartTTPlatformTheme(themeManager, false, defaultMode);

if (isWatchingMode) {
observeAttribute(document.body, THEME_MODE_ATTRIBUTE, () => switchVChartSemiTheme(themeManager));
observeAttribute(document.body, THEME_MODE_ATTRIBUTE, () => switchVChartTTPlatformTheme(themeManager));
}
if (isWatchingThemeSwitch) {
observeThemeSwitch(() => {
Expand All @@ -33,7 +33,7 @@ export const initVChartTTPlatformTheme = (options?: IInitVChartSemiThemeOption)
const timer = setInterval(() => {
const theme = generateVChartTTPlatformTheme(mode);
if (times > 50 || cacheColorScheme !== JSON.stringify(theme.colorScheme)) {
switchVChartSemiTheme(themeManager, true, mode, theme);
switchVChartTTPlatformTheme(themeManager, true, mode, theme);
clearInterval(timer);
}
times++;
Expand All @@ -42,7 +42,7 @@ export const initVChartTTPlatformTheme = (options?: IInitVChartSemiThemeOption)
}
};

export const switchVChartSemiTheme = (
export const switchVChartTTPlatformTheme = (
themeManager: typeof ThemeManager,
force?: boolean,
mode?: 'light' | 'dark',
Expand Down

0 comments on commit aea7985

Please sign in to comment.