Skip to content

Commit

Permalink
[gem] Add useStore
Browse files Browse the repository at this point in the history
  • Loading branch information
mantou132 committed Dec 27, 2023
1 parent 6c34b9d commit d67c621
Show file tree
Hide file tree
Showing 32 changed files with 163 additions and 168 deletions.
4 changes: 2 additions & 2 deletions packages/duoyun-ui/docs/en/01-guide/03-customize.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ Extend theme:
```ts
import { extendTheme } from 'duoyun-ui/lib/theme';

export const theme = extendTheme({ myColor: '#f00' });
export const [theme, updateTheme] = extendTheme({ myColor: '#f00' });
```

## Customize icon
Expand All @@ -60,7 +60,7 @@ Currently DuoyunUI uses [Material Icon](https://fonts.google.com/icons?selected=
```ts
import { extendIcons } from 'duoyun-ui/lib/icons';

const icons = extendIcons({
const [icons, updateIcons] = 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>
Expand Down
4 changes: 2 additions & 2 deletions packages/duoyun-ui/docs/zh/01-guide/03-customize.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ updateTheme({ primaryColor: 'blue' });
```ts
import { extendTheme } from 'duoyun-ui/lib/theme';

export const theme = extendTheme({ myColor: '#f00' });
export const [theme, updateTheme] = extendTheme({ myColor: '#f00' });
```

## 自定义图标
Expand All @@ -61,7 +61,7 @@ export const theme = extendTheme({ myColor: '#f00' });
```ts
import { extendIcons } from 'duoyun-ui/lib/icons';

const icons = extendIcons({
const [icons, updateIcons] = 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>
Expand Down
12 changes: 12 additions & 0 deletions packages/duoyun-ui/src/elements/badge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,18 @@ const style = createCSSSheet(css`
anchor-name: --anchor;
}
}
@supports not (anchor-name: --foo) {
:host(:not([hidden])) {
display: inline;
position: relative;
}
:host(:not(:empty)) .badge {
position: absolute;
transform: translate(50%, -50%);
top: 0;
right: 0;
}
}
`);

/**
Expand Down
6 changes: 3 additions & 3 deletions packages/duoyun-ui/src/elements/chart-tooltip.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { connectStore, adoptedStyle, customElement } from '@mantou/gem/lib/decorators';
import { GemElement, html, TemplateResult } from '@mantou/gem/lib/element';
import { createCSSSheet, css, styleMap, classMap } from '@mantou/gem/lib/utils';
import { createStore, updateStore } from '@mantou/gem/lib/store';
import { useStore } from '@mantou/gem/lib/store';

import { theme } from '../lib/theme';

Expand Down Expand Up @@ -81,7 +81,7 @@ type Store = {
debug: boolean;
};

const store = createStore<Store>({
const [store, update] = useStore<Store>({
data: {},
x: 0,
y: 0,
Expand All @@ -98,7 +98,7 @@ export class DuoyunChartTooltipElement extends GemElement {
static instance: DuoyunChartTooltipElement | null = null;

static open = (x: number, y: number, data: Data) => {
updateStore(store, { x, y, data });
update({ x, y, data });
if (!ChartTooltip.instance) {
ChartTooltip.instance = new ChartTooltip();
document.body.append(ChartTooltip.instance);
Expand Down
14 changes: 7 additions & 7 deletions packages/duoyun-ui/src/elements/coach-mark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { connectStore, adoptedStyle, customElement, attribute, numattribute } from '@mantou/gem/lib/decorators';
import { html } from '@mantou/gem/lib/element';
import { createCSSSheet, css } from '@mantou/gem/lib/utils';
import { createStore, updateStore } from '@mantou/gem/lib/store';
import { useStore } from '@mantou/gem/lib/store';
import { splice } from '@mantou/gem/helper/i18n';

import { theme, getSemanticColor } from '../lib/theme';
Expand Down Expand Up @@ -33,15 +33,15 @@ type Store = {
opened: boolean;
};

const store = createStore<Store>({
const [store, update] = useStore<Store>({
currentIndex: 0,
opened: false,
});

export async function openTour(currentIndex = store.currentIndex) {
if (!tourList[currentIndex]) throw new Error('missing tours');
await tourList[currentIndex].before?.();
updateStore(store, { opened: true, currentIndex });
update({ opened: true, currentIndex });
}

export async function setTours(tours: Tour[] | Record<number, Tour>, options: Partial<Store> = {}) {
Expand All @@ -50,22 +50,22 @@ export async function setTours(tours: Tour[] | Record<number, Tour>, options: Pa
if (opened) {
await openTour(currentIndex);
} else {
updateStore(store, { opened });
update({ opened });
}
}

async function closeTour() {
updateStore(store, { opened: false });
update({ opened: false });
tourList[store.currentIndex].skip?.();
}

async function nextTour() {
updateStore(store, { opened: false });
update({ opened: false });
ContextMenu.close();
const { currentIndex } = store;
const isFinish = currentIndex === tourList.length - 1;
if (isFinish) {
updateStore(store, { currentIndex: tourList.findIndex((e) => !!e) || 0 });
update({ currentIndex: tourList.findIndex((e) => !!e) || 0 });
}
await tourList[currentIndex].finish?.();
if (!isFinish) {
Expand Down
16 changes: 8 additions & 8 deletions packages/duoyun-ui/src/elements/contextmenu.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { connectStore, adoptedStyle, customElement, refobject, RefObject } from '@mantou/gem/lib/decorators';
import { html, GemElement, TemplateResult } from '@mantou/gem/lib/element';
import { createCSSSheet, css, styleMap, classMap } from '@mantou/gem/lib/utils';
import { createStore, updateStore } from '@mantou/gem/lib/store';
import { useStore } from '@mantou/gem/lib/store';

import { icons } from '../lib/icons';
import { locale } from '../lib/locale';
Expand Down Expand Up @@ -67,7 +67,7 @@ type ContextMenuOptions = {
header?: TemplateResult;
};

const contextmenuStore = createStore<ContextMenuStore>({
const [contextmenuStore, update] = useStore<ContextMenuStore>({
menuStack: [],
});

Expand Down Expand Up @@ -132,7 +132,7 @@ export class DuoyunContextMenuElement extends GemElement {
} = options;
if (Array.isArray(contextmenu) && contextmenu.length === 0) throw new Error('menu length is 0');
toggleActiveState(activeElement, true);
updateStore(contextmenuStore, {
update({
width,
maxHeight,
activeElement,
Expand Down Expand Up @@ -213,7 +213,7 @@ export class DuoyunContextMenuElement extends GemElement {
openLeft ||
(menuStackIndex > 0 && menuStack[menuStackIndex].x < menuStack[menuStackIndex - 1].x)) &&
left > 300;
updateStore(contextmenuStore, {
update({
menuStack: [
...menuStack.slice(0, menuStackIndex + 1),
{
Expand All @@ -225,7 +225,7 @@ export class DuoyunContextMenuElement extends GemElement {
],
});
} else {
updateStore(contextmenuStore, {
update({
menuStack: menuStack.slice(0, menuStackIndex + 1),
});
}
Expand All @@ -241,7 +241,7 @@ export class DuoyunContextMenuElement extends GemElement {
#onKeydown = (evt: KeyboardEvent, menuStackIndex: number) => {
evt.stopPropagation();
const focusPrevMenu = () => {
updateStore(contextmenuStore, {
update({
menuStack: contextmenuStore.menuStack.slice(0, menuStackIndex),
});
this.#menuElements[menuStackIndex - 1]?.focus();
Expand Down Expand Up @@ -270,13 +270,13 @@ export class DuoyunContextMenuElement extends GemElement {
const showToTop = innerHeight - bottom < height + 2 * this.#offset && top > innerHeight - bottom;
const x = showToLeft ? right - width : left;
const y = showToTop ? Math.max(top - height - 2 * this.#offset, 0) : bottom;
updateStore(contextmenuStore, {
update({
maxHeight: maxHeight || `${showToTop ? top - 2 * this.#offset : innerHeight - bottom - 2 * this.#offset}px`,
menuStack: [{ ...menu, x, y }],
});
} else {
const y = innerHeight - menu.y > width ? menu.y : Math.max(0, menu.y - (scrollHeight - clientHeight));
updateStore(contextmenuStore, { menuStack: [{ ...menu, y }] });
update({ menuStack: [{ ...menu, y }] });
}
};

Expand Down
11 changes: 7 additions & 4 deletions packages/duoyun-ui/src/lib/icons.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createStore, updateStore } from '@mantou/gem/lib/store';
import { useStore } from '@mantou/gem/lib/store';
import { raw } from '@mantou/gem/lib/utils';

// 24x24, single path
Expand Down Expand Up @@ -108,9 +108,12 @@ const defaultIcons = {
),
};

export const icons = createStore(defaultIcons);
export const [icons, updateIcons] = useStore(defaultIcons);

export function extendIcons<T extends Record<string, string>>(customIcons: Partial<typeof defaultIcons> & T) {
updateStore(icons, customIcons);
return icons as unknown as typeof defaultIcons & T;
updateIcons(customIcons);
return [
icons as unknown as typeof defaultIcons & T,
updateIcons as (customIcons: Partial<typeof defaultIcons> & T) => void,
] as const;
}
12 changes: 4 additions & 8 deletions packages/duoyun-ui/src/lib/theme.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createTheme, getThemeStore, updateTheme as changeTheme } from '@mantou/gem/helper/theme';
import { getThemeStore, useTheme } from '@mantou/gem/helper/theme';

export function getSemanticColor(semantic?: string) {
switch (semantic) {
Expand Down Expand Up @@ -64,14 +64,10 @@ export const darkTheme: Partial<typeof lightTheme> = {
maskAlpha: '0.4',
};

export const theme = createTheme({ ...lightTheme });
export const [theme, updateTheme] = useTheme({ ...lightTheme });
export const themeStore = getThemeStore(theme);

export const updateTheme = (tm: Partial<typeof lightTheme>) => {
changeTheme(theme, tm);
};

export function extendTheme<T extends Record<string, string>>(tm: Partial<typeof lightTheme> & T) {
changeTheme(theme, tm);
return theme as unknown as typeof lightTheme & T;
updateTheme(tm);
return [theme as typeof lightTheme & T, updateTheme as (tm: Partial<typeof lightTheme> & T) => void] as const;
}
15 changes: 11 additions & 4 deletions packages/duoyun-ui/src/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createStore, Store, connect, updateStore } from '@mantou/gem/lib/store';
import { Store, connect, updateStore, useStore } from '@mantou/gem/lib/store';
import { render, TemplateResult } from '@mantou/gem/lib/element';
import { NonPrimitive, cleanObject } from '@mantou/gem/lib/utils';

Expand Down Expand Up @@ -324,12 +324,13 @@ export function setBodyInert(modal: HTMLElement) {
}

/**Create auto cache(localStorage) Store */
export function createCacheStore<T extends Record<string, any>>(
export function useCacheStore<T extends Record<string, any>>(
storageKey: string,
initStore: T,
options?: {
cacheExcludeKeys?: (keyof T)[];
prefix?: string | (() => string | undefined);
// 重新初始化 store,例如切换用户
depStore?: Store<NonPrimitive>;
},
) {
Expand All @@ -351,7 +352,7 @@ export function createCacheStore<T extends Record<string, any>>(
const cacheExcludeKeys = new Set(options?.cacheExcludeKeys || []);
let key = getKey();

const store = createStore<T>(getStoreStore(key));
const [store, updater] = useStore<T>(getStoreStore(key));

if (options?.depStore) {
connect(options.depStore, () => {
Expand All @@ -372,5 +373,11 @@ export function createCacheStore<T extends Record<string, any>>(

window.addEventListener('pagehide', saveStore);

return [store, saveStore] as const;
return [store, updater, saveStore] as const;
}

/**@deprecated use `useCacheStore` */
export const createCacheStore = (...args: Parameters<typeof useCacheStore>) => {
const [store, , save] = useCacheStore(...args);
return [store, save] as const;
};
8 changes: 4 additions & 4 deletions packages/gem-book/src/element/elements/main.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { html, GemElement, customElement, css, property, createCSSSheet, adoptedStyle, updateStore } from '@mantou/gem';
import { html, GemElement, customElement, css, property, createCSSSheet, adoptedStyle } from '@mantou/gem';
import { Renderer, parse } from 'marked';
import { mediaQuery } from '@mantou/gem/helper/mediaquery';

import { theme } from '../helper/theme';
import { checkBuiltInPlugin } from '../lib/utils';

import { tocStore } from './toc';
import { updateTocStore } from './toc';

import '@mantou/gem/elements/unsafe';
import '@mantou/gem/elements/link';
Expand Down Expand Up @@ -89,7 +89,7 @@ export class Main extends GemElement {
};

#updateToc = () =>
updateStore(tocStore, {
updateTocStore({
elements: [...this.shadowRoot!.querySelectorAll<HTMLHeadingElement>('.markdown-header')].slice(1),
});

Expand Down Expand Up @@ -303,7 +303,7 @@ export class Main extends GemElement {
opacity: 1;
}
h1 {
font-size: 2.5rem;
font-size: 2.3rem;
}
}
</style>
Expand Down
8 changes: 6 additions & 2 deletions packages/gem-book/src/element/elements/nav.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { capitalize, isSameOrigin } from '../lib/utils';
import { bookStore } from '../store';

import { icons } from './icons';
import { sidebarStore, toggleSidebar } from './sidebar';
import { sidebarStore, updateSidebarStore } from './sidebar';

import '@mantou/gem/elements/link';
import '@mantou/gem/elements/use';
Expand Down Expand Up @@ -171,7 +171,11 @@ export class Nav extends GemElement {
}
}
</style>
<gem-use class="menu" @click=${toggleSidebar} .element=${sidebarStore.open ? icons.close : icons.menu}></gem-use>
<gem-use
class="menu"
@click=${() => updateSidebarStore({ open: !sidebarStore.open })}
.element=${sidebarStore.open ? icons.close : icons.menu}
></gem-use>
${this.logo ? html`<gem-book-nav-logo></gem-book-nav-logo>` : ''}
<div class="left">
${internals.map((item) => this.renderInternalItem(item))}
Expand Down
14 changes: 4 additions & 10 deletions packages/gem-book/src/element/elements/sidebar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,9 @@ import {
connectStore,
classMap,
state,
createStore,
connect,
updateStore,
history,
disconnect,
useStore,
} from '@mantou/gem';
import { mediaQuery } from '@mantou/gem/helper/mediaquery';

Expand All @@ -26,10 +24,7 @@ import '@mantou/gem/elements/use';
import './side-link';
import './nav-logo';

export const sidebarStore = createStore({ open: false });

const closeSidebar = () => updateStore(sidebarStore, { open: false });
export const toggleSidebar = () => updateStore(sidebarStore, { open: !sidebarStore.open });
export const [sidebarStore, updateSidebarStore] = useStore({ open: false });

@customElement('gem-book-sidebar')
@connectStore(bookStore)
Expand Down Expand Up @@ -219,7 +214,7 @@ export class SideBar extends GemElement {
position: fixed;
background: ${theme.backgroundColor};
width: 100%;
height: calc(100vh - ${theme.headerHeight});
height: calc(100dvh - ${theme.headerHeight});
top: ${theme.headerHeight};
z-index: 3;
}
Expand Down Expand Up @@ -267,7 +262,6 @@ export class SideBar extends GemElement {
}

mounted() {
connect(history.store, closeSidebar);
return () => disconnect(history.store, closeSidebar);
return connect(history.store, () => updateSidebarStore({ open: false }));
}
}
Loading

0 comments on commit d67c621

Please sign in to comment.