feat: 设置界面内置设置项及其控制组件

This commit is contained in:
AncTe committed 2026-11-09 21:33:31 +08:00
1 parent 0071bb741c
commit 53f4bcdee5
9 files changed
+1309 -6

No files matched your search

@@ -0,0 +1,212 @@
import { CanvasStyle, Font, IActionEvent, IRenderItem } from '@motajs/render';
import { DefaultProps } from '@motajs/render-vue';
import { SetupComponentOptions } from '@motajs/system';
import { isNil } from 'lodash-es';
import {
computed,
defineComponent,
onMounted,
onUnmounted,
ref,
watch
} from 'vue';
export interface ISliderProps extends DefaultProps {
/** 滑动条的当前值 */
value?: number;
/** 滑动条的最小值,默认为 100 */
min?: number;
/** 滑动条的最大值,默认为 0 */
max?: number;
/** 滑动条的步长,即两个值之间最小差多少,默认为 1 */
step?: number;
/** 是否在滑动条右侧显示当前值,默认显示 */
showValue?: boolean;
/** 滑动条右侧显示当前值的宽度,默认为 40 */
valueWidth?: number;
/** 文字的显示字体 */
font?: Font;
/** 滑动条的线宽 */
lineWidth?: number;
/** 线左右两侧距容器边缘的距离 */
padding?: number;
/** 控制点左侧的滑动条样式 */
filledStyle?: CanvasStyle;
/** 控制点右侧的滑动条样式 */
emptyStyle?: CanvasStyle;
/** 控制点的半径 */
radius?: number;
}
export type SliderEmits = {
/**
* 当滑动条的设置值变化时触发
* @param value 当前滑动条的设置值
*/
update: (value: number) => void;
'update:value': (value: number) => void;
};
const sliderProps = {
props: [
'loc',
'width',
'height',
'value',
'min',
'max',
'step',
'showValue',
'valueWidth',
'font',
'lineWidth',
'padding',
'filledStyle',
'emptyStyle',
'radius'
],
emits: ['update', 'update:value']
} satisfies SetupComponentOptions<ISliderProps, SliderEmits, keyof SliderEmits>;
/**
* 滑动条组件,提供一个可控制的滑动条,玩家滑动的时候会调整其值,类似于音量调节的那种滑动条。
* 注意,一定要专门提供两个按钮可以点击增减滑动条的值,因为移动端操作滑动条会比较困难。
*/
export const Slider = defineComponent<
ISliderProps,
SliderEmits,
keyof SliderEmits
>((props, { emit }) => {
const min = computed(() => props.min ?? 0);
const max = computed(() => props.max ?? 0);
const showValue = computed(() => props.showValue ?? true);
const font = computed(() => props.font ?? Font.defaults({ size: 12 }));
/** 当前值 */
const value = ref(props.value ?? min.value);
const container = ref<IRenderItem>();
const width = computed(() => props.loc?.[2] ?? props.width ?? 200);
const height = computed(() => props.loc?.[3] ?? props.width ?? 200);
const cy = computed(() => height.value / 2);
const sx = computed(() => props.padding ?? 4);
const ex = computed(() => {
if (showValue.value) {
return width.value - sx.value - (props.valueWidth ?? 40);
} else {
return width.value - sx.value;
}
});
watch(
() => props.value,
newValue => {
if (!isNil(newValue)) {
value.value = newValue;
}
}
);
/** 端点横坐标 */
const fx = computed(() => {
const ratio = (value.value - min.value) / (max.value - min.value);
const len = ratio * (ex.value - sx.value);
return sx.value + len;
});
/** 数值显示值 */
const valueStr = computed(() => {
const v = Number(value.value.toFixed(8));
if (v < 1000 && v > 0.01) return value.value.toString();
else return v.toExponential(2);
});
let dragging = false;
let startX = -1;
const down = (ev: IActionEvent) => {
dragging = true;
startX = ev.absoluteX;
};
const up = () => {
dragging = false;
startX = -1;
};
const move = (ev: IActionEvent) => {
if (!dragging || startX < 0) return;
const dx = ev.absoluteX - startX;
const ratio = (value.value - min.value) / (max.value - min.value);
const now = ratio * (ex.value - sx.value);
if (dx < -now) {
value.value = min.value;
} else if (dx > ex.value - now) {
value.value = max.value;
} else {
const target = now + dx;
const ratio = target / (ex.value - sx.value);
const targetValue = ratio * (max.value - min.value) + min.value;
const step = props.step ?? 1;
const steps = Math.round((targetValue - min.value) / step);
const aligned = steps * step + min.value;
value.value = aligned;
emit('update:value', aligned);
}
};
onMounted(() => {
if (!container.value) return;
const root = container.value.root;
if (!root) return;
root.on('moveCapture', move);
});
onUnmounted(() => {
if (!container.value) return;
const root = container.value.root;
if (!root) return;
root.off('moveCapture', move);
});
return () => (
<container ref={container}>
<g-line
line={[sx.value, cy.value, ex.value, cy.value]}
lineCap="round"
lineWidth={props.lineWidth}
strokeStyle={props.emptyStyle ?? '#888'}
zIndex={0}
/>
<g-line
line={[sx.value, cy.value, fx.value, cy.value]}
lineCap="round"
lineWidth={props.lineWidth}
strokeStyle={props.filledStyle ?? '#0ff'}
zIndex={1}
/>
<g-circle
circle={[fx.value, cy.value, props.radius ?? 4]}
fill
stroke
lineWidth={1}
fillStyle={props.filledStyle ?? '#0ff'}
strokeStyle={props.emptyStyle ?? '#888'}
cursor="pointer"
zIndex={2}
onDown={down}
onUp={up}
/>
<text
text={valueStr.value}
hidden={!showValue.value}
font={font.value}
loc={[width.value - sx.value, cy.value]}
anc={[1, 0.5]}
fillStyle="#fff"
/>
</container>
);
}, sliderProps);
@@ -0,0 +1,216 @@
import { DefineSetupFnComponent, defineComponent } from 'vue';
import { describe, expect, it } from 'vitest';
import { SaveCompression } from '@user/data-common';
import { SettingSystem } from '../system';
import { ISettingComponentProps, ISettingItem } from '../types';
interface IFakeItemState {
value: number;
saveCount: number;
loadCount: number;
lastCompression: SaveCompression | null;
}
interface IFakeItem {
readonly item: ISettingItem<number>;
readonly state: IFakeItemState;
}
/**
* 创建一个用于测试的假设置项,记录存取次数与最近一次使用的压缩级别
* @param id 设置项的 id
* @param initial 设置项的初始值
*/
function createFakeItem(id: string, initial: number): IFakeItem {
const state: IFakeItemState = {
value: initial,
saveCount: 0,
loadCount: 0,
lastCompression: null
};
const item: ISettingItem<number> = {
id,
name: id,
description: id,
getValue(): number {
return state.value;
},
setValue(value: number): void {
state.value = value;
},
getPreviewString(): string {
return String(state.value);
},
getSettingComponent(): DefineSetupFnComponent<ISettingComponentProps> {
return defineComponent<ISettingComponentProps>(() => () => []);
},
saveState(compression: SaveCompression): number {
state.saveCount++;
state.lastCompression = compression;
return state.value;
},
loadState(value: number, compression: SaveCompression): void {
state.loadCount++;
state.lastCompression = compression;
state.value = value;
}
};
return { item, state };
}
describe('设置系统', () => {
// 登记到分组后可按 id 取到该设置项
it('returns a registered setting item by id', () => {
const system = new SettingSystem();
const a = createFakeItem('a', 1);
system.setGroup('group', '分组', [a.item]);
expect(system.getSetting('a')).toBe(a.item);
});
// setGroup 整体替换分组内容,并登记分组内的设置项
it('replaces the group items and registers them', () => {
const system = new SettingSystem();
const a = createFakeItem('a', 1);
const b = createFakeItem('b', 2);
system.setGroup('group', '分组', [a.item]);
system.setGroup('group', '新分组', [b.item]);
const group = system.getGroup('group');
expect(group?.name).toBe('新分组');
expect(Array.from(group?.items ?? []).map(item => item.id)).toEqual([
'b'
]);
expect(system.getSetting('b')).toBe(b.item);
});
// 空数组会删除分组,但此前登记的设置项仍可取到并成为未分组项
it('deletes an empty group while keeping its items registered', () => {
const system = new SettingSystem();
const a = createFakeItem('a', 1);
system.setGroup('group', '分组', [a.item]);
system.setGroup('group', '分组', []);
expect(system.getGroup('group')).toBeNull();
expect(system.getSetting('a')).toBe(a.item);
expect(Array.from(system.getUngrouped())).toEqual([a.item]);
});
// 向不存在的分组添加设置项是空操作,既不报错也不登记
it('ignores addSettingToGroup for a missing group', () => {
const system = new SettingSystem();
const a = createFakeItem('a', 1);
system.addSettingToGroup('missing', a.item);
expect(system.getGroup('missing')).toBeNull();
expect(system.getSetting('a')).toBeNull();
});
// 同一设置项重复加入分组不会产生重复项
it('appends to an existing group without duplicating items', () => {
const system = new SettingSystem();
const a = createFakeItem('a', 1);
const b = createFakeItem('b', 2);
system.setGroup('group', '分组', [a.item]);
system.addSettingToGroup('group', b.item);
system.addSettingToGroup('group', b.item);
const group = system.getGroup('group');
expect(Array.from(group?.items ?? []).map(item => item.id)).toEqual([
'a',
'b'
]);
});
// 缺失的分组与设置项都返回 null
it('returns null for missing groups and settings', () => {
const system = new SettingSystem();
expect(system.getGroup('missing')).toBeNull();
expect(system.getSetting('missing')).toBeNull();
});
// iterateGroups 返回全部已登记的分组条目
it('iterates every registered group', () => {
const system = new SettingSystem();
const a = createFakeItem('a', 1);
const b = createFakeItem('b', 2);
system.setGroup('first', '第一组', [a.item]);
system.setGroup('second', '第二组', [b.item]);
const entries = Array.from(system.iterateGroups());
expect(entries.map(([id]) => id)).toEqual(['first', 'second']);
expect(entries.map(([, group]) => group.name)).toEqual([
'第一组',
'第二组'
]);
});
// getUngrouped 不包含已归入分组的设置项
it('excludes grouped items from the ungrouped list', () => {
const system = new SettingSystem();
const a = createFakeItem('a', 1);
const b = createFakeItem('b', 2);
system.setGroup('group', '分组', [a.item]);
system.setGroup('other', '另一组', [b.item]);
expect(Array.from(system.getUngrouped())).toEqual([]);
});
// getValue 与 setValue 都转发给对应的设置项
it('forwards value reads and writes to the setting item', () => {
const system = new SettingSystem();
const a = createFakeItem('a', 1);
system.setGroup('group', '分组', [a.item]);
expect(system.getValue<number>('a')).toBe(1);
system.setValue('a', 7);
expect(a.state.value).toBe(7);
expect(system.getValue<number>('a')).toBe(7);
});
// 未登记 id 取值返回 undefined,写值不产生任何效果
it('ignores value access for an unregistered id', () => {
const system = new SettingSystem();
expect(system.getValue<number>('missing')).toBeUndefined();
expect(() => system.setValue('missing', 1)).not.toThrow();
});
// saveState 聚合全部已登记设置项,并把压缩级别透传给每个设置项
it('aggregates every setting item and passes the compression level', () => {
const system = new SettingSystem();
const a = createFakeItem('a', 1);
const b = createFakeItem('b', 2);
system.setGroup('group', '分组', [a.item, b.item]);
const save = system.saveState(SaveCompression.LowCompression);
expect(save.values.get('a')).toBe(1);
expect(save.values.get('b')).toBe(2);
expect(a.state.saveCount).toBe(1);
expect(b.state.saveCount).toBe(1);
expect(a.state.lastCompression).toBe(SaveCompression.LowCompression);
expect(b.state.lastCompression).toBe(SaveCompression.LowCompression);
});
// loadState 把每个值逐项写回对应的设置项
it('loads every value back into its setting item', () => {
const system = new SettingSystem();
const a = createFakeItem('a', 1);
const b = createFakeItem('b', 2);
system.setGroup('group', '分组', [a.item, b.item]);
const values = new Map<string, unknown>([
['a', 10],
['b', 20]
]);
system.loadState({ values }, SaveCompression.HighCompression);
expect(a.state.value).toBe(10);
expect(b.state.value).toBe(20);
expect(a.state.lastCompression).toBe(SaveCompression.HighCompression);
});
// loadState 遇到未登记的 id 会跳过,且不影响其它设置项
it('skips unregistered ids while loading state', () => {
const system = new SettingSystem();
const a = createFakeItem('a', 1);
system.setGroup('group', '分组', [a.item]);
const values = new Map<string, unknown>([
['missing', 99],
['a', 5]
]);
expect(() =>
system.loadState({ values }, SaveCompression.NoCompression)
).not.toThrow();
expect(a.state.value).toBe(5);
expect(a.state.loadCount).toBe(1);
});
});
@@ -0,0 +1,341 @@
import {
computed,
defineComponent,
onMounted,
onUnmounted,
ref,
watch
} from 'vue';
import { ElementLocator, Font } from '@motajs/render';
import {
IGameUI,
SetupComponentOptions,
UIComponent,
UIRawProps
} from '@motajs/system';
import { ISettingComponentProps, ISettingItemHooks } from './types';
import { Input } from '../components';
import { Slider } from '../components/slider';
import { clamp } from 'lodash-es';
import { IGameUIPropsBase } from '../types';
/** 内边距,控制组件内容与容器边缘的距离 */
const PADDING = 4;
/** 组件常规内容的高度 */
const HEIGHT = 24;
/** 滑条组件右侧距离容器边缘的距离 */
const SLIDER_RIGHT = 32;
/** 控件内文字使用的字体 */
const defaultFont = Font.defaults({ size: 13 });
//#region 数值设置
export interface INumberSettingProps extends ISettingComponentProps<number> {
/** 最小数值 */
readonly min: number;
/** 最大数值 */
readonly max: number;
}
const numberSettingProps = {
props: ['setting', 'controller', 'width', 'loc', 'min', 'max']
} satisfies SetupComponentOptions<INumberSettingProps>;
export const NumberSettingComponent = defineComponent<INumberSettingProps>(
props => {
const current = ref(props.setting.getValue().toString());
/** 当前的提示文字 */
const hint = ref('');
const width = computed(() => props.loc?.[2] ?? props.width ?? 200);
watch(current, value => {
const num = Number(value);
if (num === props.setting.getValue()) return;
if (isNaN(num) || !isFinite(num)) {
hint.value = '请输入合法数字!';
} else {
hint.value = '';
props.setting.setValue(num);
}
});
const hook: ISettingItemHooks<number> = {
onUpdateValue(value) {
current.value = value.toString();
}
};
onMounted(() => {
props.setting.addHook(hook);
});
onUnmounted(() => {
props.setting.removeHook(hook);
});
return () => (
<container loc={props.loc} width={props.width} nocache>
<Input
loc={[PADDING, PADDING, width.value - PADDING, HEIGHT]}
v-model={current.value}
placeholder="请输入数值"
/>
<text
loc={[PADDING, PADDING * 2 + HEIGHT]}
text={hint.value}
fillStyle="#eb8252"
/>
</container>
);
},
numberSettingProps
);
//#endregion
//#region 布尔值设置
export interface IBooleanSettingProps extends ISettingComponentProps<boolean> {}
const booleanSettingProps = {
props: ['setting', 'controller', 'width', 'loc']
} satisfies SetupComponentOptions<IBooleanSettingProps>;
export const BooleanSettingComponent = defineComponent<IBooleanSettingProps>(
props => {
const current = ref(props.setting.getValue());
const width = computed(() => props.loc?.[2] ?? props.width ?? 200);
const currentText = computed(() =>
current.value ? '当前开启' : '当前关闭'
);
const buttonText = computed(() => (current.value ? '关闭' : '开启'));
const toggle = (): void => {
current.value = !current.value;
if (current.value !== props.setting.getValue()) {
props.setting.setValue(current.value);
}
};
const hook: ISettingItemHooks<boolean> = {
onUpdateValue(value) {
current.value = value;
}
};
onMounted(() => {
props.setting.addHook(hook);
});
onUnmounted(() => {
props.setting.removeHook(hook);
});
return () => (
<container loc={props.loc} width={props.width} nocache>
<g-rectr
loc={[width.value / 2, PADDING, width.value / 2, HEIGHT]}
circle={[4]}
fillStyle="#17a4cb"
cursor="pointer"
onClick={toggle}
zIndex={0}
/>
<text
text={buttonText.value}
loc={[(width.value * 3) / 4, PADDING + HEIGHT / 2]}
anc={[0.5, 0.5]}
fillStyle="#fff"
strokeStyle="#000"
font={defaultFont}
noevent
zIndex={1}
/>
<text
text={currentText.value}
loc={[PADDING, PADDING + HEIGHT / 2]}
anc={[0, 0.5]}
fillStyle="#fff"
strokeStyle="#000"
font={defaultFont}
/>
</container>
);
},
booleanSettingProps
);
//#endregion
//#region 范围值设置
export interface IRangeSettingProps extends ISettingComponentProps<number> {
/** 最小数值 */
readonly min: number;
/** 最大数值 */
readonly max: number;
/** 数值步长 */
readonly step: number;
}
const rangeSettingProps = {
props: ['setting', 'controller', 'width', 'loc', 'min', 'max', 'step']
} satisfies SetupComponentOptions<IRangeSettingProps>;
export const RangeSettingComponent = defineComponent<IRangeSettingProps>(
props => {
const current = ref(props.setting.getValue());
const w = computed(() => props.loc?.[2] ?? props.width ?? 200);
/** Button Y */
const by = computed(() => PADDING * 2 + (HEIGHT * 3) / 2);
const decrease = () => {
if (current.value > props.min) {
current.value = clamp(
current.value - props.step,
props.min,
props.max
);
}
};
const increase = () => {
if (current.value < props.max) {
current.value = clamp(
current.value + props.step,
props.min,
props.max
);
}
};
const hook: ISettingItemHooks<number> = {
onUpdateValue(value) {
current.value = value;
}
};
onMounted(() => {
props.setting.addHook(hook);
});
onUnmounted(() => {
props.setting.removeHook(hook);
});
return () => (
<container loc={props.loc} width={props.width} nocache>
<Slider
v-model={current.value}
loc={[0, 0, w.value, HEIGHT]}
min={props.min}
max={props.max}
step={props.step}
valueWidth={SLIDER_RIGHT}
padding={PADDING}
font={defaultFont}
showValue
/>
<g-rectr
loc={[w.value / 2, by.value, w.value / 4, HEIGHT]}
anc={[0.5, 0.5]}
circle={[4]}
fillStyle="#17a4cb"
cursor="pointer"
onClick={decrease}
zIndex={0}
/>
<text
loc={[w.value / 2, by.value, w.value / 4, HEIGHT]}
anc={[0.5, 0.5]}
text="减少"
fillStyle="#fff"
strokeStyle="#000"
zIndex={1}
/>
<g-rectr
loc={[(w.value * 3) / 2, by.value, w.value / 4, HEIGHT]}
anc={[0.5, 0.5]}
circle={[4]}
fillStyle="#17a4cb"
cursor="pointer"
onClick={increase}
zIndex={0}
/>
<text
loc={[(w.value * 3) / 2, by.value, w.value / 4, HEIGHT]}
anc={[0.5, 0.5]}
text="增加"
fillStyle="#fff"
strokeStyle="#000"
zIndex={1}
/>
</container>
);
},
rangeSettingProps
);
//#endregion
//#region 子页面设置
export interface ISubPageSettingProps<
T extends UIComponent
> extends ISettingComponentProps<void> {
/** 子页面 UI 对象 */
readonly page: IGameUI<T>;
/** 传递给子页面的参数 */
readonly vBind: UIRawProps<T, IGameUIPropsBase>;
}
const subPageSettingProps = {
props: ['setting', 'controller', 'width', 'loc']
} satisfies SetupComponentOptions<ISubPageSettingProps<UIComponent>>;
export const SubPageSettingComponent = defineComponent<
ISubPageSettingProps<UIComponent>
>(<T extends UIComponent>(props: ISubPageSettingProps<T>) => {
const width = computed(() => props.loc?.[2] ?? props.width ?? 200);
const buttonLoc = computed(
(): ElementLocator => [
width.value / 2,
PADDING + HEIGHT / 2,
width.value / 2,
HEIGHT
]
);
// 打开闭包中携带的目标界面
const openPage = () => {
props.controller.open(props.page, props.vBind);
};
return () => (
<container loc={props.loc} width={props.width}>
<g-rectr
loc={buttonLoc.value}
anc={[0.5, 0.5]}
circle={[4]}
fillStyle="#17a4cb"
cursor="pointer"
onClick={openPage}
/>
<text
text="编辑设置"
loc={[width.value / 2, PADDING + HEIGHT / 2]}
anc={[0.5, 0.5]}
font={defaultFont}
noevent
/>
</container>
);
}, subPageSettingProps);
//#endregion
@@ -0,0 +1,352 @@
import { DefineSetupFnComponent } from 'vue';
import { IGameUI, UIComponent, UIRawProps } from '@motajs/system';
import {
ISettingItem,
ISettingBooleanOptions,
ISettingComponentProps,
ISettingNumberOptions,
ISettingRangeOptions,
ISettingSubPageOptions,
ISettingComponentEntry,
ISettingItemHooks
} from './types';
import { clamp } from 'lodash-es';
import {
BooleanSettingComponent,
INumberSettingProps,
IRangeSettingProps,
ISubPageSettingProps,
NumberSettingComponent,
RangeSettingComponent,
SubPageSettingComponent
} from './controls';
import {
Hookable,
HookController,
IHookBase,
IHookController,
logger
} from '@motajs/common';
import { IGameUIPropsBase } from '../types';
/**
* 将数值按步长对齐并收敛到允许的区间内,同时消除浮点计算产生的尾差
* @param value 原始数值
* @param min 允许的最小值
* @param max 允许的最大值
* @param step 对齐使用的步长
*/
function clampSettingValue(
value: number,
min: number,
max: number,
step: number
): number {
const aligned = Math.round((value - min) / step) * step + min;
const clamped = Math.min(max, Math.max(min, aligned));
return Number(clamped.toFixed(6));
}
export class NumberSetting
extends Hookable<ISettingItemHooks<number>>
implements ISettingItem<number>
{
readonly id: string;
readonly name: string;
readonly description: string;
/** 数值最小值 */
private readonly min: number;
/** 数值最大值 */
private readonly max: number;
/** 当前值 */
private value: number;
constructor(options: ISettingNumberOptions) {
super();
this.id = options.id;
this.name = options.name;
this.description = options.description;
this.min = options.min;
this.max = options.max;
this.value = options.defaultValue;
}
protected createController(
hook: Partial<IHookBase>
): IHookController<IHookBase> {
return new HookController(this, hook);
}
getValue(): number {
return this.value;
}
setValue(value: number): void {
const before = this.value;
this.value = clamp(value, this.min, this.max);
this.forEachHook(hook => hook.onUpdateValue?.(value, before));
}
getPreviewString(): string {
return this.value.toString();
}
getSettingComponent(
base: ISettingComponentProps<number>
): ISettingComponentEntry<number, INumberSettingProps> {
return {
component: NumberSettingComponent,
props: {
...base,
min: this.min,
max: this.max
}
};
}
saveState(): number {
return this.value;
}
loadState(state: number): void {
this.setValue(state);
}
}
export class BooleanSetting
extends Hookable<ISettingItemHooks<boolean>>
implements ISettingItem<boolean>
{
readonly id: string;
readonly name: string;
readonly description: string;
/** 当前值 */
private value: boolean;
constructor(options: ISettingBooleanOptions) {
super();
this.id = options.id;
this.name = options.name;
this.description = options.description;
this.value = options.defaultValue;
}
protected createController(
hook: Partial<ISettingItemHooks<boolean>>
): IHookController<ISettingItemHooks<boolean>> {
return new HookController(this, hook);
}
getValue(): boolean {
return this.value;
}
setValue(value: boolean): void {
this.value = value;
}
getPreviewString(): string {
return this.value ? '开' : '关';
}
getSettingComponent(
base: ISettingComponentProps<boolean>
): ISettingComponentEntry<boolean> {
return {
component: BooleanSettingComponent,
props: {
...base
}
};
}
saveState(): boolean {
return this.value;
}
loadState(state: boolean): void {
this.value = state;
}
}
export class RangeSetting
extends Hookable<ISettingItemHooks<number>>
implements ISettingItem<number>
{
readonly id: string;
readonly name: string;
readonly description: string;
/** 数值的最小值 */
private readonly min: number;
/** 数值的最大值 */
private readonly max: number;
/** 数值的步长 */
private readonly step: number;
/** 当前值 */
private value: number;
constructor(options: ISettingRangeOptions) {
super();
this.id = options.id;
this.name = options.name;
this.description = options.description;
this.min = options.min;
this.max = options.max;
this.step = options.step;
this.value = options.defaultValue;
const steps = (this.max - this.min) / this.step;
if (Math.abs(steps - Math.round(steps)) > 1e-8) {
logger.warn(
214,
this.min.toString(),
this.max.toString(),
this.step.toString()
);
}
}
protected createController(
hook: Partial<ISettingItemHooks<number>>
): IHookController<ISettingItemHooks<number>> {
return new HookController(this, hook);
}
getValue(): number {
return this.value;
}
setValue(value: number): void {
this.value = clampSettingValue(value, this.min, this.max, this.step);
}
getPreviewString(): string {
return this.value.toString();
}
getSettingComponent(
base: ISettingComponentProps<number>
): ISettingComponentEntry<number, IRangeSettingProps> {
return {
component: RangeSettingComponent,
props: {
...base,
min: this.min,
max: this.max,
step: this.step
}
};
}
saveState(): number {
return this.value;
}
loadState(state: number): void {
this.setValue(state);
}
}
export class SubPageSetting<T extends UIComponent>
extends Hookable<ISettingItemHooks<void>>
implements ISettingItem<void>
{
readonly id: string;
readonly name: string;
readonly description: string;
/** 打开的子页面 */
private readonly page: IGameUI<T>;
/** 传递给子页面的参数 */
private readonly vBind: UIRawProps<T, IGameUIPropsBase>;
constructor(options: ISettingSubPageOptions<T>) {
super();
this.id = options.id;
this.name = options.name;
this.description = options.description;
this.page = options.page;
this.vBind = options.props;
}
protected createController(
hook: Partial<ISettingItemHooks<void>>
): IHookController<ISettingItemHooks<void>> {
return new HookController(this, hook);
}
getValue(): void {
return void 0;
}
setValue(): void {}
getPreviewString(): string {
return '';
}
getSettingComponent(
base: ISettingComponentProps<void>
): ISettingComponentEntry<void, ISubPageSettingProps<T>> {
return {
// @ts-expect-error 类型一定正确,但是由于常量没办法加泛型,所以无法推导
component: SubPageSettingComponent as DefineSetupFnComponent<
ISubPageSettingProps<T>
>,
props: {
...base,
page: this.page,
vBind: this.vBind
}
};
}
saveState(): void {}
loadState(): void {}
}
/**
* 创建一个数值类型的设置项
* @param options 设置项的配置
*/
export function defineNumberSetting(
options: ISettingNumberOptions
): ISettingItem<number> {
return new NumberSetting(options);
}
/**
* 创建一个布尔类型的设置项
* @param options 设置项的配置
*/
export function defineBooleanSetting(
options: ISettingBooleanOptions
): ISettingItem<boolean> {
return new BooleanSetting(options);
}
/**
* 创建一个区间类型的设置项
* @param options 设置项的配置
*/
export function defineRangeSetting(
options: ISettingRangeOptions
): ISettingItem<number> {
return new RangeSetting(options);
}
/**
* 创建一个点击后打开子页面的设置项
* @param options 设置项的配置
*/
export function defineSubPageSetting(
options: ISettingSubPageOptions<UIComponent>
): ISettingItem<void> {
return new SubPageSetting(options);
}
@@ -1 +1,4 @@
export * from './controls';
export * from './factories';
export * from './system';
export * from './types';
@@ -0,0 +1,100 @@
import { SaveCompression } from '@user/data-common';
import {
ISettingItem,
ISettingItemGroup,
ISettingSystem,
ISettingSystemSave
} from './types';
import { isNil } from 'lodash-es';
import { logger } from '@motajs/common';
export class SettingSystem implements ISettingSystem {
/** 所有设置分组,键为分组 id */
readonly groups: Map<string, ISettingItemGroup> = new Map();
/** 所有已登记的设置项,键为设置项 id */
private readonly settings: Map<string, ISettingItem> = new Map();
/** 设置 id 到其分组的映射 */
private readonly groupMap: Map<string, string> = new Map();
setGroup(group: string, name: string, items: ISettingItem[]): void {
if (items.length > 0) {
for (const item of items) {
this.settings.set(item.id, item);
this.groupMap.set(item.id, group);
}
this.groups.set(group, { name, items });
} else {
this.groups.delete(group);
}
}
addSettingToGroup(group: string, item: ISettingItem): void {
const exist = this.groupMap.get(item.id);
if (exist === group) return;
if (!isNil(exist) && exist !== group) {
logger.warn(213, item.id, exist, group);
}
const obj = this.groups.getOrInsertComputed(group, () => ({
name: group,
items: []
}));
this.settings.set(item.id, item);
this.groups.set(group, { name: obj.name, items: [...obj.items, item] });
}
getGroup(group: string): ISettingItemGroup | null {
return this.groups.get(group) ?? null;
}
getSetting(id: string): ISettingItem | null {
return this.settings.get(id) ?? null;
}
iterateGroups(): Iterable<[id: string, group: ISettingItemGroup]> {
return this.groups.entries();
}
getUngrouped(): Iterable<ISettingItem> {
const grouped = new Set<ISettingItem>();
for (const group of this.groups.values()) {
for (const item of group.items) {
grouped.add(item);
}
}
const ungrouped: ISettingItem[] = [];
for (const item of this.settings.values()) {
if (!grouped.has(item)) ungrouped.push(item);
}
return ungrouped;
}
getValue<T>(id: string): T | undefined {
const item = this.settings.get(id);
return item?.getValue() as T;
}
setValue<T>(id: string, value: T): void {
const item = this.settings.get(id);
if (item) {
item.setValue(value);
}
}
saveState(compression: SaveCompression): ISettingSystemSave {
const values: Map<string, unknown> = new Map();
for (const [id, item] of this.settings) {
values.set(id, item.saveState(compression));
}
return { values };
}
loadState(state: ISettingSystemSave, compression: SaveCompression): void {
for (const [id, value] of state.values) {
const item = this.settings.get(id);
// 未登记设置项直接跳过,不写入日志
if (!item) continue;
item.loadState(value, compression);
}
}
}
+74 -5
View File
@@ -1,12 +1,43 @@
import { ISaveableContent } from '@user/data-common';
import {
IGameUI,
IUIController,
UIComponent,
UIRawProps
} from '@motajs/system';
import { DefineComponent, DefineSetupFnComponent } from 'vue';
import { IGameUIPropsBase } from '../types';
import { DefaultProps } from '@motajs/render-vue';
import { IHookable, IHookBase } from '@motajs/common';
export interface ISettingComponentProps<T = unknown> {
export interface ISettingComponentProps<T> extends DefaultProps {
/** 当前设置组件对应的设置项 */
readonly setting: ISettingItem<T>;
/** 当前设置组件所属的 UI 控制器 */
readonly controller: IUIController<IGameUIPropsBase>;
}
export interface ISettingItem<T = unknown> extends ISaveableContent<T> {
export interface ISettingComponentEntry<
T,
P extends ISettingComponentProps<T> = ISettingComponentProps<T>
> {
/** 组件对象 */
readonly component: DefineSetupFnComponent<P> | DefineComponent<P>;
/** 传递给组件的参数 */
readonly props: P;
}
export interface ISettingItemHooks<T> extends IHookBase {
/**
* 当更新设置的值时触发
* @param value 更新后的值
* @param oldValue 更新前的值
*/
onUpdateValue(value: T, oldValue: T): void;
}
export interface ISettingItem<T = unknown>
extends IHookable<ISettingItemHooks<T>>, ISaveableContent<T> {
/** 设置项的唯一标识 */
readonly id: string;
/** 设置项的名称,用于显示 */
@@ -33,9 +64,9 @@ export interface ISettingItem<T = unknown> extends ISaveableContent<T> {
/**
* 获取用于修改此设置项的组件
*/
getSettingComponent():
| DefineSetupFnComponent<ISettingComponentProps>
| DefineComponent<ISettingComponentProps>;
getSettingComponent(
base: ISettingComponentProps<T>
): ISettingComponentEntry<T, any>;
}
export interface ISettingItemGroup {
@@ -104,3 +135,41 @@ export interface ISettingSystem extends ISaveableContent<ISettingSystemSave> {
*/
setValue<T>(id: string, value: T): void;
}
export interface ISettingOptionsBase<T> {
/** 设置项的唯一标识 */
readonly id: string;
/** 设置项的名称,用于显示 */
readonly name: string;
/** 设置项的说明文本 */
readonly description: string;
/** 设置项的默认值 */
readonly defaultValue: T;
}
export interface ISettingNumberOptions extends ISettingOptionsBase<number> {
/** 数值的最小值 */
readonly min: number;
/** 数值的最大值 */
readonly max: number;
}
export interface ISettingBooleanOptions extends ISettingOptionsBase<boolean> {}
export interface ISettingRangeOptions extends ISettingOptionsBase<number> {
/** 设置项允许的最小值 */
readonly min: number;
/** 设置项允许的最大值 */
readonly max: number;
/** 每次调整设置项时的步长 */
readonly step: number;
}
export interface ISettingSubPageOptions<
T extends UIComponent
> extends ISettingOptionsBase<void> {
/** 点击后打开的目标界面 */
readonly page: IGameUI<T>;
/** 打开子页面时传递给它的参数 */
readonly props: UIRawProps<T, IGameUIPropsBase>;
}