Skip to content

Commit

Permalink
Closed #94
Browse files Browse the repository at this point in the history
  • Loading branch information
mantou132 committed Dec 15, 2023
1 parent dfcd9bd commit 3daba6a
Show file tree
Hide file tree
Showing 18 changed files with 254 additions and 80 deletions.
14 changes: 8 additions & 6 deletions packages/duoyun-ui/docs/en/01-guide/03-customize.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Customize

DuoyunUI comes with the theme (including a dark theme), icon(such as [`<dy-loading>`](../02-elements/loading.md)), text (eg, [`<dy-pagination>`](../02-elements/pagination.md)) can be easily used and modified,
in your application, you can use them like this:
DuoyunUI comes with themes, icons, texts, and can be used in the application:

```ts
import { createCSSSheet, css, adoptedStyle, customElement, GemElement, html } from '@mantou/gem';
Expand All @@ -26,6 +25,8 @@ export class MyEleElement extends GemElement {
}
```

Can be easily modified or extended.

## Customize theme

Use build-in dark theme:
Expand Down Expand Up @@ -57,19 +58,20 @@ export const theme = extendTheme({ myColor: '#f00' });
Currently DuoyunUI uses [Material Icon](https://fonts.google.com/icons?selected=Material+Icons), modify icon:

```ts
import { setIcons } from 'duoyun-ui/lib/icons';
import { extendIcons } from 'duoyun-ui/lib/icons';

setIcons({
const icons = extendIcons({
more: `
<svg part="icon" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="currentColor">
<path d="M0 0h24v24H0z" fill="none" stroke="none"></path>
<path d="M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"></path>
</svg>
`,
myIcon: ``,
});
```

## Customize language
## Customize text

DuoyunUI defaults English, specifying Chinese and modifying a text:

Expand All @@ -95,7 +97,7 @@ export const i18n = new I18n<typeof zhCN>({
'zh-CN': zhCN,
en: enURI,
},
onChange: async (code: keyof typeof langNames) => {
onChange: (code: keyof typeof langNames) => {
switch (code) {
case 'en':
return updateLocale(import('duoyun-ui/locales/en'));
Expand Down
57 changes: 47 additions & 10 deletions packages/duoyun-ui/docs/en/01-guide/05-lib.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,54 @@
In addition to providing many custom elements, DuoyunUI has some basic class with certain features,
also includes some common modules that are somewhat being used in custom elements of DuoyunUI, some of which are independent.

## Color

Color space conversion; brightness, contrast calculation.

<gbp-api src="/src/lib/color.ts"></gbp-api>

## Encode/Decode

hash, base64 etc encode.

<gbp-api src="/src/lib/encode.ts"></gbp-api>

## HotKeys

Lightweight version of [hotkeys](https://github.com/greena13/react-hotkeys).

<gbp-api src="/src/lib/hotkeys.ts"></gbp-api>

## Image

Compressed image; generate SVG.

<gbp-api src="/src/lib/image.ts"></gbp-api>

## Number

Format numbers, range adjustments.

<gbp-api src="/src/lib/number.ts"></gbp-api>

## Date/Time

Lightweight version of the date time process library.

<gbp-api src="/src/lib/time.ts"></gbp-api>

## Utils

Some common functions.

<gbp-api src="/src/lib/utils.ts"></gbp-api>

## 其他

- `animations`: Use [Web Animations API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API) implement simple animation
- `cache`: Provide a simple [LRU](<https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)>) cache
- `color`: Color space conversion; brightness, contrast calculation
- `encode`: hash, base64 etc encode
- `hotkeys`: Lightweight version of [hotkeys](https://github.com/greena13/react-hotkeys)
- `icons`: Build-in icons
- `image`: Compressed image; generate SVG
- `locale`: Switch, modify the language
- `number`: Format numbers, range adjustments
- `icons`: Build-in icons, [see](./03-customize.md#customize-icon)
- `locale`: Switch, modify the language, [see](./03-customize.md#customize-text)
- `styles`: Some styles that can be shared globally
- `theme`: Build-in theme
- `time`: Lightweight version of the date time process library
- `theme`: Build-in theme, [see](./03-customize.md#customize-theme)
- `types`: Convenient TypeScript type infer help function
- `utils`: Some common functions
12 changes: 7 additions & 5 deletions packages/duoyun-ui/docs/zh/01-guide/03-customize.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,22 +55,24 @@ export const theme = extendTheme({ myColor: '#f00' });

## 自定义图标

目前 DuoyunUI 使用 [Material Icon](https://fonts.google.com/icons?selected=Material+Icons),修改 Icon:
目前 DuoyunUI 使用 [Material Icon](https://fonts.google.com/icons?selected=Material+Icons)
修改和扩展 Icon:

```ts
import { setIcons } from 'duoyun-ui/lib/icons';
import { extendIcons } from 'duoyun-ui/lib/icons';

setIcons({
const icons = extendIcons({
more: `
<svg part="icon" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="currentColor">
<path d="M0 0h24v24H0z" fill="none" stroke="none"></path>
<path d="M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"></path>
</svg>
`,
myIcon: ``,
});
```

## 自定义语言
## 自定义文本

DuoyunUI 默认使用英语,指定成中文并修改某个文本:

Expand All @@ -96,7 +98,7 @@ export const i18n = new I18n<typeof zhCN>({
'zh-CN': zhCN,
en: enURI,
},
onChange: async (code: keyof typeof langNames) => {
onChange: (code: keyof typeof langNames) => {
switch (code) {
case 'en':
return updateLocale(import('duoyun-ui/locales/en'));
Expand Down
59 changes: 48 additions & 11 deletions packages/duoyun-ui/docs/zh/01-guide/05-lib.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,54 @@
DuoyunUI 除了提供许多自定义元素、具有某些特定功能的基类之外,
还包含一些常用模块,它们有些被用在 DuoyunUI 的自定义元素中,有些则是独立提供的。

## Color

色彩空间转换;亮度、对比度计算。

<gbp-api src="/src/lib/color.ts"></gbp-api>

## Encode/Decode

hash, base64 等编码。

<gbp-api src="/src/lib/encode.ts"></gbp-api>

## HotKeys

轻量版的 [hotkeys](https://github.com/greena13/react-hotkeys)

<gbp-api src="/src/lib/hotkeys.ts"></gbp-api>

## Image

压缩图片;生成 SVG 图片。

<gbp-api src="/src/lib/image.ts"></gbp-api>

## Number

格式化数字、范围调整。

<gbp-api src="/src/lib/number.ts"></gbp-api>

## Date/Time

轻量版的日期时间处理库。

<gbp-api src="/src/lib/time.ts"></gbp-api>

## Utils

一些常用的函数。

<gbp-api src="/src/lib/utils.ts"></gbp-api>

## 其他

- `animations`:使用 [Web Animations API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API) 运行简单动画
- `cache`:提供一个简单的 [LRU](<https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)>) 缓存
- `color`:色彩空间转换;亮度、对比度计算
- `encode`: hash, base64 等编码
- `hotkeys`:轻量版的 [hotkeys](https://github.com/greena13/react-hotkeys)
- `icons`:内置图标
- `image`:压缩图片;生成 SVG 图片
- `locale`:切换、修改语言
- `number`:格式化数字、范围调整
- `cache`:提供简单的缓存方案,比如 [LRU](<https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)>) 缓存
- `icons`:内置图标,[另见](./03-customize.md#自定义图标)
- `locale`:切换、修改语言,[另见](./03-customize.md#自定义文本)
- `styles`:一些可全局共享的样式
- `theme`:内置主题
- `time`:轻量版的日期时间处理库
- `theme`:内置主题,[另见](./03-customize.md#自定义主题)
- `types`:方便 Typescript 类型推导的帮助函数
- `utils`:一些常用的函数
10 changes: 6 additions & 4 deletions packages/duoyun-ui/src/lib/color.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export function parseHexColor(str: HexColor): RGBA {
}

/**
* note: ignore alpha
* Note: ignore alpha
*/
export function luminance([r, g, b]: RGB | RGBA) {
const a = [r, g, b].map((v) => {
Expand All @@ -84,7 +84,7 @@ export function luminance([r, g, b]: RGB | RGBA) {
}

/**
* note: ignore alpha
* Note: ignore alpha
*/
export function contrast(rgb1: RGB | RGBA, rgb2: RGB | RGBA) {
const l1 = luminance([rgb1[0], rgb1[1], rgb1[2]]) + 0.05;
Expand All @@ -93,8 +93,10 @@ export function contrast(rgb1: RGB | RGBA, rgb2: RGB | RGBA) {
}

/**
* note: ignore alpha
* edit for https://stackoverflow.com/questions/8022885/rgb-to-hsv-color-in-javascript
* Note: ignore alpha
*
* @see
* https://stackoverflow.com/questions/8022885/rgb-to-hsv-color-in-javascript
*/
export function rgbToHsl(rgb: RGB | RGBA): HSL {
const [r, g, b] = rgb.map((e) => e / 255);
Expand Down
2 changes: 2 additions & 0 deletions packages/duoyun-ui/src/lib/encode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ function base64ToSafeUrl(str: string) {
return str.replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
}

/**Converted string to Base64, `isSafe` indicates URL safe */
export function utf8ToB64(str: string, isSafe?: boolean) {
const base64 = window.btoa(
encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (_, p1) => String.fromCharCode(Number(`0x${p1}`))),
Expand All @@ -34,6 +35,7 @@ export function arrayBufferToBase64(arrayBuffer: ArrayBuffer, isSafe?: boolean)
return isSafe ? base64ToSafeUrl(base64) : base64;
}

/**Must be async */
export async function hash(strOrAb: string | ArrayBuffer, options?: 'string'): Promise<string>;
export async function hash(strOrAb: string | ArrayBuffer, output: 'arrayBuffer'): Promise<ArrayBuffer>;
export async function hash(strOrAb: string | ArrayBuffer, output: 'string' | 'arrayBuffer' = 'string') {
Expand Down
14 changes: 9 additions & 5 deletions packages/duoyun-ui/src/lib/hotkeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export type Key = {
type NormalizeKey = string;

/**
* @see
* https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code/code_values
*/
export function normalizeKey(code: string): NormalizeKey {
Expand Down Expand Up @@ -121,6 +122,7 @@ appendToMap(keys);

export const isMac = navigator.platform.includes('Mac');

/**Get the platform button */
export function getDisplayKey(code: string, type?: keyof Key) {
const key = normalizeKey(code);
const keyObj = keys[key];
Expand All @@ -136,7 +138,7 @@ export function getDisplayKey(code: string, type?: keyof Key) {
return result.replace(/^(.)/, (_substr, $1: string) => $1.toUpperCase());
}

// custom key map
/**Custom key map */
export function setKeys(keysRecord: Record<NormalizeKey, Key>) {
Object.assign(keys, keysRecord);
appendToMap(keysRecord);
Expand All @@ -147,6 +149,7 @@ const hotkeySplitter = /,(?!,)/;
// const keySplitter = /(?<!\+)\+/;
const keySplitter = /\+/;

/**Detect whether the current keyboard event matches the specified button */
export function matchHotKey(evt: KeyboardEvent, hotkey: string) {
const keys = hotkey.split(keySplitter).map((k) => map[k]);

Expand Down Expand Up @@ -198,16 +201,17 @@ export type HotKeyHandles = {
let locked = false;
const unlockCallback = new Set<() => void>();

/**Release the lock state of the continuous button, see `hotkeys` */
export function unlock() {
locked = false;
unlockCallback.forEach((callback) => callback());
unlockCallback.clear();
}

/**
* must have non-control character;
* not case sensitive;
* support `a-b`, press `a`, hotkeys be locked, wait next `keydown` event, allow call `unlock`
* Must have non-control character;
* Not case sensitive;
* Support `a-b`, press `a`, hotkeys be locked, wait next `keydown` event, allow call `unlock`
*/
export function hotkeys(handles: HotKeyHandles) {
return function (evt: KeyboardEvent) {
Expand Down Expand Up @@ -267,7 +271,7 @@ export function hotkeys(handles: HotKeyHandles) {
}

/**
* support space,enter
* Support space,enter
*/
export const commonHandle = hotkeys({
'space,enter': (evt) => {
Expand Down
7 changes: 5 additions & 2 deletions packages/duoyun-ui/src/lib/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export function createDataURLFromSVG(raw: string) {
}

// if `bg` is't `HexColor`, text fill color error
/**Create SVG according to the text, the text will rotate some angles randomly */
export function createSVGFromText(text: string, backgroundColor?: string) {
const hslRange = [
[0, 1],
Expand All @@ -35,7 +36,7 @@ export function createSVGFromText(text: string, backgroundColor?: string) {
const getTranslate = () => Math.random() / 5;
const getRotate = () => (Math.random() - 0.5) * 45;

const strs = [...text].map(
const strings = [...text].map(
(char) => `<text
x="50%"
y="50%"
Expand All @@ -51,7 +52,7 @@ export function createSVGFromText(text: string, backgroundColor?: string) {
height="300"
viewBox="0 0 1 1"
style="background: ${bg}; fill: ${color}; font: 1px sans-serif">
${strs.join('')}
${strings.join('')}
</svg>
`;
}
Expand Down Expand Up @@ -113,6 +114,8 @@ interface OutputOptions {
type?: 'url';
}
type Origin = (HTMLImageElement & { type?: string }) | File;

/**Compression `HTMLImageElement`/`File` to DataURL/`File` */
export function compressionImage(origin: Origin, limit: LimitOptions, output: OutputOptions): Promise<string>;
export function compressionImage(origin: Origin, limit: LimitOptions): Promise<File>;
export async function compressionImage(origin: Origin, limit: LimitOptions, { aspectRatio, type }: OutputOptions = {}) {
Expand Down
8 changes: 4 additions & 4 deletions packages/duoyun-ui/src/lib/number.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,10 @@ it('`formatNumber` 默认选项', () => {
it('`formatNumber` 小数点', () => {
expect(formatNumber(1, { dotAfterCount: 0 })).include({ number: '1', unit: '' });
expect(formatNumber(10, { dotAfterCount: 1 })).include({ number: '10', unit: '' });
expect(formatNumber(10, { dotAfterCount: 1, autoOmitFract: false })).include({ number: '10.0', unit: '' });
expect(formatNumber(10.02, { dotAfterCount: 1, autoOmitFract: false })).include({ number: '10.0', unit: '' });
expect(formatNumber(10.09, { dotAfterCount: 1, autoOmitFract: false })).include({ number: '10.1', unit: '' });
expect(formatNumber(10000, { dotAfterCount: 3, autoOmitFract: false })).include({
expect(formatNumber(10, { dotAfterCount: 1, autoOmitFraction: false })).include({ number: '10.0', unit: '' });
expect(formatNumber(10.02, { dotAfterCount: 1, autoOmitFraction: false })).include({ number: '10.0', unit: '' });
expect(formatNumber(10.09, { dotAfterCount: 1, autoOmitFraction: false })).include({ number: '10.1', unit: '' });
expect(formatNumber(10000, { dotAfterCount: 3, autoOmitFraction: false })).include({
number: '10,000.000',
unit: '',
});
Expand Down
Loading

0 comments on commit 3daba6a

Please sign in to comment.