Skip to content

Commit

Permalink
style: change prettier print width settings, add prettierignore & ref…
Browse files Browse the repository at this point in the history
…ormat files
  • Loading branch information
lingbopro committed Dec 22, 2024
1 parent 6da5502 commit e238d2a
Show file tree
Hide file tree
Showing 14 changed files with 138 additions and 40 deletions.
4 changes: 4 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package-lock.json
yarn.lock
pnpm-lock.yaml
.husky/
2 changes: 1 addition & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"arrowParens": "always",
"endOfLine": "lf",
"printWidth": 140,
"printWidth": 80,
"semi": true,
"singleQuote": true,
"tabWidth": 2
Expand Down
18 changes: 17 additions & 1 deletion commitlint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,23 @@ export default {
rules: {
// types declared in Conventional Commits specification & @commitlint/config-conventional
// see: https://www.conventionalcommits.org/en/v1.0.0/#summary
'type-enum': [2, 'always', ['build', 'chore', 'ci', 'docs', 'feat', 'fix', 'perf', 'refactor', 'revert', 'style', 'test']],
'type-enum': [
2,
'always',
[
'build',
'chore',
'ci',
'docs',
'feat',
'fix',
'perf',
'refactor',
'revert',
'style',
'test',
],
],
'scope-enum': [
2,
'always',
Expand Down
2 changes: 1 addition & 1 deletion demos/components/ripple.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
Expand Down
2 changes: 1 addition & 1 deletion demos/esm.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8" />
Expand Down
2 changes: 1 addition & 1 deletion demos/index.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8" />
Expand Down
42 changes: 31 additions & 11 deletions dev/scripts/lib/build.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,25 @@ const minifiedBundlePlugins = [
export async function main(options) {
log('starting bundle...');
log('copying files...');
await fs.promises.cp(path.join(root, 'src'), path.join(root, '.__compile_cache__'), { recursive: true });
await fs.promises.cp(
path.join(root, 'src'),
path.join(root, '.__compile_cache__'),
{
recursive: true,
},
);
log('compiling TypeScript...');
// This may not seem like standard usage, but it can at least reduce the waiting time by 3s
child_process.spawnSync('node', [path.join(root, 'node_modules', 'typescript', 'lib', 'tsc.js')], { cwd: root });
child_process.spawnSync(
'node',
[path.join(root, 'node_modules', 'typescript', 'lib', 'tsc.js')],
{ cwd: root },
);
logSuccess('success compiled TypeScript');
log('generating bundles...');
const globedFiles = fs.globSync(path.resolve(root, '.__compile_cache__', '**', '*.js'));
const globedFiles = fs.globSync(
path.resolve(root, '.__compile_cache__', '**', '*.js'),
);
debug({ globedFiles });
const generateBundlesResult = await rollup({
// input: path.resolve(__dirname, 'exports__compile_cache.js'),
Expand All @@ -56,18 +68,21 @@ export async function main(options) {
debug({ generateBundlesResult, generateBundlesOutput });
logSuccess('success generated bundles');
log('cleaning up temp dir...');
await fs.promises.rm(path.join(root, '.__compile_cache__'), { recursive: true });
await fs.promises.rm(path.join(root, '.__compile_cache__'), {
recursive: true,
});
if (!options.includes('--no-min-bundle')) {
log('generating minified bundle...');
const generateMinifiedBundleResult = await rollup({
input: path.resolve(root, 'exports.js'),
plugins: [...basicPlugins, ...minifiedBundlePlugins],
});
const generateMinifiedBundleOutput = await generateMinifiedBundleResult.write({
file: path.resolve(root, 'dist', 'material-me.min.js'),
format: 'umd',
...basicOutputConfig,
});
const generateMinifiedBundleOutput =
await generateMinifiedBundleResult.write({
file: path.resolve(root, 'dist', 'material-me.min.js'),
format: 'umd',
...basicOutputConfig,
});
debug({ generateMinifiedBundleResult, generateMinifiedBundleOutput });
}
logSuccess('success generated minified bundle');
Expand All @@ -86,9 +101,14 @@ export async function execute(options) {
}

export async function cleanup(options) {
if (fs.existsSync(path.join(root, '.__compile_cache__')) && !options.includes('--no-finally-clean')) {
if (
fs.existsSync(path.join(root, '.__compile_cache__')) &&
!options.includes('--no-finally-clean')
) {
log('cleaning up temp dir...');
await fs.promises.rm(path.join(root, '.__compile_cache__'), { recursive: true });
await fs.promises.rm(path.join(root, '.__compile_cache__'), {
recursive: true,
});
}
}

Expand Down
3 changes: 2 additions & 1 deletion dev/scripts/lib/utils.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export function debug(message, ...optionalParams) {
}
export function isSubDir(parent, dir) {
const relative = path.relative(parent, dir);
const isSubdir = relative && !relative.startsWith('..') && !path.isAbsolute(relative);
const isSubdir =
relative && !relative.startsWith('..') && !path.isAbsolute(relative);
return !!isSubdir;
}
2 changes: 1 addition & 1 deletion dev/scripts/lib/watch.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export async function main(options) {
}
debug(`File changes detected: ${filename} (type: ${eventType})`);
taskStack.push({ eventType, filename });
}
},
);
intervalId = setInterval(async () => {
if (taskStack.length > 0 && !taskProcessing) {
Expand Down
8 changes: 6 additions & 2 deletions dev/scripts/script.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@ const scripts = {
const argv = process.argv.slice(2);
const scriptNameIndex = argv.findIndex((arg) => !arg.startsWith('-'));
const scriptName = argv[scriptNameIndex];
const runOptions = argv.filter((arg, index) => arg.startsWith('-') && index < scriptNameIndex);
const scriptOptions = argv.filter((arg, index) => arg.startsWith('-') && index > scriptNameIndex);
const runOptions = argv.filter(
(arg, index) => arg.startsWith('-') && index < scriptNameIndex,
);
const scriptOptions = argv.filter(
(arg, index) => arg.startsWith('-') && index > scriptNameIndex,
);

const docsStr = `
Usage: pnpm script [run-options] [script-name] [script-options]
Expand Down
6 changes: 5 additions & 1 deletion src/components/page/page.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { useElement } from '../../core/element';
import { defaultTheme, generateCSSKeys, overrideColorKeys } from '../../utils/theme';
import {
defaultTheme,
generateCSSKeys,
overrideColorKeys,
} from '../../utils/theme';
import template from './page.html';
import style from './page.css';

Expand Down
19 changes: 13 additions & 6 deletions src/components/ripple/ripple.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,12 @@ export class Ripple extends useElement({
props,
syncProps: ['attached'],
setup(shadowRoot) {
const containerEl = shadowRoot.querySelector('.container') as HTMLDivElement;
const rippleTemplateEl = shadowRoot.querySelector('.ripple-template') as HTMLDivElement;
const containerEl = shadowRoot.querySelector(
'.container',
) as HTMLDivElement;
const rippleTemplateEl = shadowRoot.querySelector(
'.ripple-template',
) as HTMLDivElement;

/** 父元素(用于吸附模式) */
const parent = this.parentElement;
Expand Down Expand Up @@ -68,10 +72,13 @@ export class Ripple extends useElement({
// 点击结束处理方法
const touchEnd = () => {
// 淡出动画
const fadeOutAnimation = rippleEl.animate([{ opacity: 0.24 }, { opacity: 0 }], {
duration: 400,
fill: 'forwards',
});
const fadeOutAnimation = rippleEl.animate(
[{ opacity: 0.24 }, { opacity: 0 }],
{
duration: 400,
fill: 'forwards',
},
);
// 移除元素
fadeOutAnimation.addEventListener('finish', () => {
rippleEl.remove();
Expand Down
45 changes: 36 additions & 9 deletions src/core/element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ interface ComponentConfig<Props extends ElementProps> {
/** 属性监听列表 */
syncProps?: string[];
/** 初始化函数 */
setup?: (this: HTMLElement & Props, shadowRoot: ShadowRoot) => SetupOptions<Props>;
setup?: (
this: HTMLElement & Props,
shadowRoot: ShadowRoot,
) => SetupOptions<Props>;
}

/**
Expand All @@ -35,7 +38,11 @@ interface SetupOptions<Props extends ElementProps> {
/** 移动到新文档回调 */
onAdopt?: () => void;
/** 属性更改、添加、删除、替换回调 */
onAttributeChanged?: (name: string, oldValue: PropType, newValue: PropType) => void;
onAttributeChanged?: (
name: string,
oldValue: PropType,
newValue: PropType,
) => void;
/** 暴露的方法 */
expose?: { [key: string]: (...args: any[]) => any };
/** 属性 setters */
Expand Down Expand Up @@ -82,7 +89,7 @@ export function parseType(value: unknown, old: PropType) {
* @returns 应继承的自定义元素类
*/
export function useElement<Props extends ElementProps>(
config: ComponentConfig<Props>
config: ComponentConfig<Props>,
): {
new (): HTMLElement & Props;
/**
Expand All @@ -98,7 +105,10 @@ export function useElement<Props extends ElementProps>(
* 为此组件增加一个属性
* @param name 属性名
*/
const createProperty = (component: MaterialMeGeneratedComponent, name: string) => {
const createProperty = (
component: MaterialMeGeneratedComponent,
name: string,
) => {
Object.defineProperty(component, name, {
get: () => {
return props[name];
Expand All @@ -107,7 +117,12 @@ export function useElement<Props extends ElementProps>(
const oldValue = props[name];
const parsedValue = parseType(value, oldValue);
if (parsedValue !== props[name]) {
setupOptions.onAttributeChanged?.call(component, name, oldValue, parsedValue);
setupOptions.onAttributeChanged?.call(
component,
name,
oldValue,
parsedValue,
);
props[name] = parsedValue;
syncProperty(component, name);
setupOptions.propsSetter?.[name]?.call(component, parsedValue as any);
Expand All @@ -121,7 +136,10 @@ export function useElement<Props extends ElementProps>(
* 处理一个属性的更改同步
* @param name 属性名
*/
const syncProperty = (component: MaterialMeGeneratedComponent, name: string) => {
const syncProperty = (
component: MaterialMeGeneratedComponent,
name: string,
) => {
if (config.syncProps?.includes(name)) {
const lowerKey = name.toLowerCase();
const attrValue = component.getAttribute(lowerKey);
Expand All @@ -139,7 +157,9 @@ export function useElement<Props extends ElementProps>(
* 暴露属性
*/
const exposeProperties = (component: MaterialMeGeneratedComponent) => {
const exposeDescriptors = Object.getOwnPropertyDescriptors(setupOptions.expose ?? {});
const exposeDescriptors = Object.getOwnPropertyDescriptors(
setupOptions.expose ?? {},
);
for (const key in exposeDescriptors) {
const item = exposeDescriptors[key];
const existing = Object.getOwnPropertyDescriptor(component, key);
Expand Down Expand Up @@ -173,7 +193,11 @@ export function useElement<Props extends ElementProps>(
attachStylesheet(shadowRoot, config.style);
}
props = { ...config.props };
setupOptions = config.setup?.call(this as unknown as HTMLElement & Props, shadowRoot) ?? {};
setupOptions =
config.setup?.call(
this as unknown as HTMLElement & Props,
shadowRoot,
) ?? {};
const nonDefaultProps: string[] = [];
exposeProperties(this);
for (const name in props) {
Expand Down Expand Up @@ -214,5 +238,8 @@ export function useElement<Props extends ElementProps>(
window.customElements.define(name, this);
}
}
return MaterialMeGeneratedComponent as unknown as { new (): HTMLElement & Props; readonly define: (name: string) => void };
return MaterialMeGeneratedComponent as unknown as {
new (): HTMLElement & Props;
readonly define: (name: string) => void;
};
}
23 changes: 19 additions & 4 deletions src/utils/theme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,11 @@ export function generateCSSKeys(theme: Theme): string {
const toRgbValue = (color: RgbColor) => {
return `${color.r}, ${color.g}, ${color.b}`;
};
const generateKeys = (obj: any, prefix: string, valueProcessor?: (value: any) => string) => {
const generateKeys = (
obj: any,
prefix: string,
valueProcessor?: (value: any) => string,
) => {
return Object.keys(obj)
.map((key) => {
const value = obj[key];
Expand All @@ -197,8 +201,16 @@ export function generateCSSKeys(theme: Theme): string {
.join('\n');
};

const keysColorLight = generateKeys(theme.colors.light, 'color-light', (value: RgbColor) => toRgbValue(value));
const keysColorDark = generateKeys(theme.colors.dark, 'color-dark', (value: RgbColor) => toRgbValue(value));
const keysColorLight = generateKeys(
theme.colors.light,
'color-light',
(value: RgbColor) => toRgbValue(value),
);
const keysColorDark = generateKeys(
theme.colors.dark,
'color-dark',
(value: RgbColor) => toRgbValue(value),
);
const keysElevations = generateKeys(theme.elevations, 'elevation');
const keys = keysColorLight + keysColorDark + keysElevations;
return keys;
Expand All @@ -210,7 +222,10 @@ export function generateCSSKeys(theme: Theme): string {
* @param theme 主题对象(仅用于提取键名)
* @returns
*/
export function generateOverrideColorKeys(scheme: 'light' | 'dark', theme: Theme = defaultTheme): string {
export function generateOverrideColorKeys(
scheme: 'light' | 'dark',
theme: Theme = defaultTheme,
): string {
const keys = Object.keys(theme.colors[scheme]).map((key) => {
const casedKey = toKebabCase(key);
return `--mm-color-${casedKey}: var(--mm-color-${scheme}-${casedKey});`;
Expand Down

0 comments on commit e238d2a

Please sign in to comment.