refactor: src 除入口外全部移入 monorepo

This commit is contained in:
AncTe committed 2025-03-09 16:43:59 +08:00
1 parent cca10a429c
commit 0679bbb1a5
103 files changed
+340 -252

No files matched your search

@@ -0,0 +1,637 @@
import { DefaultProps, ElementLocator, Font, useKey } from '@motajs/render';
import { computed, defineComponent, reactive, ref } from 'vue';
import { Background, Selection } from './misc';
import { TextContent, TextContentExpose, TextContentProps } from './textbox';
import { SetupComponentOptions } from './types';
import { TextAlign } from './textboxTyper';
import { Page, PageExpose } from './page';
import { GameUI, IUIMountable } from '@motajs/system-ui';
export interface ConfirmBoxProps extends DefaultProps, TextContentProps {
text: string;
width: number;
loc: ElementLocator;
selFont?: Font;
selFill?: CanvasStyle;
pad?: number;
yesText?: string;
noText?: string;
winskin?: ImageIds;
defaultYes?: boolean;
color?: CanvasStyle;
border?: CanvasStyle;
}
export type ConfirmBoxEmits = {
yes: () => void;
no: () => void;
};
const confirmBoxProps = {
props: [
'text',
'width',
'loc',
'selFont',
'selFill',
'pad',
'yesText',
'noText',
'winskin',
'defaultYes',
'color',
'border'
],
emits: ['no', 'yes']
} satisfies SetupComponentOptions<
ConfirmBoxProps,
ConfirmBoxEmits,
keyof ConfirmBoxEmits
>;
/**
* 确认框组件,与 2.x 的 drawConfirm 类似,可以键盘操作,单次调用参考 {@link getConfirm}。
* 参数参考 {@link ConfirmBoxProps},事件参考 {@link ConfirmBoxEmits},用例如下:
* ```tsx
* const onYes = () => console.log('yes');
* const onNo = () => console.log('no');
*
* <ConfirmBox
* text="是否要返回标题界面"
* width={240}
* // 确认框会自动计算宽度和高度,因此不需要手动指定,即使手动指定也无效
* loc={[240, 240, void 0, void 0, 0.5, 0.5]}
* // 使用 winskin 图片作为背景
* winskin="winskin.png"
* // 使用颜色作为背景和边框,如果设置了 winskin,那么此参数无效
* color="#333"
* border="gold"
* // 设置选项的字体
* selFont={new Font('Verdana', 16)}
* // 设置选项的文本颜色
* selFill="#d48"
* // 完全继承 TextContent 的参数,因此可以填写 font 参数指定文本字体
* font={new Font('arial')}
* onYes={onYes}
* onNo={onNo}
* />
* ```
*/
export const ConfirmBox = defineComponent<
ConfirmBoxProps,
ConfirmBoxEmits,
keyof ConfirmBoxEmits
>((props, { emit, attrs }) => {
const content = ref<TextContentExpose>();
const height = ref(200);
const selected = ref(props.defaultYes ? true : false);
const yesSize = ref<[number, number]>([0, 0]);
const noSize = ref<[number, number]>([0, 0]);
const loc = computed<ElementLocator>(() => {
const [x = 0, y = 0, , , ax = 0, ay = 0] = props.loc;
return [x, y, props.width, height.value, ax, ay];
});
const yesText = computed(() => props.yesText ?? '确认');
const noText = computed(() => props.noText ?? '取消');
const pad = computed(() => props.pad ?? 32);
const yesLoc = computed<ElementLocator>(() => {
const y = height.value - pad.value;
return [props.width / 3, y, void 0, void 0, 0.5, 1];
});
const noLoc = computed<ElementLocator>(() => {
const y = height.value - pad.value;
return [(props.width / 3) * 2, y, void 0, void 0, 0.5, 1];
});
const contentLoc = computed<ElementLocator>(() => {
const width = props.width - pad.value * 2;
return [props.width / 2, pad.value, width, 0, 0.5, 0];
});
const selectLoc = computed<ElementLocator>(() => {
if (selected.value) {
const [x = 0, y = 0] = yesLoc.value;
const [width, height] = yesSize.value;
return [x, y + 4, width + 8, height + 8, 0.5, 1];
} else {
const [x = 0, y = 0] = noLoc.value;
const [width, height] = noSize.value;
return [x, y + 4, width + 8, height + 8, 0.5, 1];
}
});
const onUpdateHeight = (textHeight: number) => {
height.value = textHeight + pad.value * 4;
};
const setYes = (_: string, width: number, height: number) => {
yesSize.value = [width, height];
};
const setNo = (_: string, width: number, height: number) => {
noSize.value = [width, height];
};
const [key] = useKey();
key.realize('confirm', () => {
if (selected.value) emit('yes');
else emit('no');
});
key.realize('moveLeft', () => void (selected.value = true));
key.realize('moveRight', () => void (selected.value = false));
return () => (
<container loc={loc.value}>
<Background
loc={[0, 0, props.width, height.value]}
winskin={props.winskin}
color={props.color}
border={props.border}
zIndex={0}
/>
<TextContent
{...attrs}
ref={content}
loc={contentLoc.value}
text={props.text}
width={props.width - pad.value * 2}
zIndex={5}
textAlign={TextAlign.Center}
autoHeight
onUpdateHeight={onUpdateHeight}
/>
<Selection
loc={selectLoc.value}
winskin={props.winskin}
border={props.border}
noevent
zIndex={10}
/>
<text
loc={yesLoc.value}
text={yesText.value}
fillStyle={props.selFill}
font={props.selFont}
cursor="pointer"
zIndex={15}
onClick={() => emit('yes')}
onEnter={() => (selected.value = true)}
onSetText={setYes}
/>
<text
loc={noLoc.value}
text={noText.value}
fillStyle={props.selFill}
font={props.selFont}
cursor="pointer"
zIndex={15}
onClick={() => emit('no')}
onEnter={() => (selected.value = false)}
onSetText={setNo}
/>
</container>
);
}, confirmBoxProps);
export type ChoiceKey = string | number | symbol;
export type ChoiceItem = [key: ChoiceKey, text: string];
export interface ChoicesProps extends DefaultProps, TextContentProps {
choices: ChoiceItem[];
loc: ElementLocator;
width: number;
maxHeight?: number;
text?: string;
title?: string;
winskin?: ImageIds;
color?: CanvasStyle;
border?: CanvasStyle;
selFont?: Font;
selFill?: CanvasStyle;
titleFont?: Font;
titleFill?: CanvasStyle;
pad?: number;
interval?: number;
}
export type ChoicesEmits = {
choose: (key: ChoiceKey) => void;
};
const choicesProps = {
props: [
'choices',
'loc',
'width',
'maxHeight',
'text',
'title',
'winskin',
'color',
'border',
'selFont',
'selFill',
'titleFont',
'titleFill',
'pad',
'interval'
],
emits: ['choose']
} satisfies SetupComponentOptions<
ChoicesProps,
ChoicesEmits,
keyof ChoicesEmits
>;
/**
* 选项框组件,用于在多个选项中选择一个,例如样板的系统设置就由它实现。单次调用参考 {@link getChoice}。
* 参数参考 {@link ChoicesProps},事件参考 {@link ChoicesEmits}。用例如下:
* ```tsx
* <Choices
* // 选项数组,每一项是一个二元素数组,第一项表示这个选项的 id,在选中时会以此作为参数传递给事件
* // 第二项表示这一项的内容,即展示给玩家看的内容
* choices={[[0, '选项1'], [100, '选项2']]}
* // 选项框会自动计算宽度和高度,因此不需要手动指定,即使手动指定也无效
* loc={[240, 240, void 0, void 0, 0.5, 0.5]}
* text="请选择一项"
* title="选项"
* // 使用 winskin 图片作为背景
* winskin="winskin.png"
* // 使用颜色作为背景和边框,如果设置了 winskin,那么此参数无效
* color="#333"
* border="gold"
* // 调整每两个选项之间的间隔
* interval={12}
* // 设置选项的字体
* selFont={new Font('Verdana', 16)}
* // 设置选项的文本颜色
* selFill="#d48"
* // 设置标题的字体
* titleFont={new Font('Verdana', 16)}
* // 设置标题的文本颜色
* selFill="gold"
* // 完全继承 TextContent 的参数,因此可以填写 font 参数指定文本字体
* font={new Font('arial')}
* // 当选择某一项时触发
* onChoice={(choice) => console.log(choice)}
* />
* ```
*/
export const Choices = defineComponent<
ChoicesProps,
ChoicesEmits,
keyof ChoicesEmits
>((props, { emit, attrs }) => {
const titleHeight = ref(0);
const contentHeight = ref(0);
const selected = ref(0);
const pageCom = ref<PageExpose>();
const choiceSize = reactive<[number, number][]>([]);
const selFont = computed(() => props.selFont ?? new Font());
const maxHeight = computed(() => props.maxHeight ?? 360);
const pad = computed(() => props.pad ?? 28);
const choiceInterval = computed(() => props.interval ?? 16);
const hasText = computed(() => !!props.text);
const hasTitle = computed(() => !!props.title);
const contentWidth = computed(() => props.width - pad.value * 2);
const choiceHeight = computed(
() => selFont.value.size + 8 + choiceInterval.value
);
const contentY = computed(() => {
if (hasTitle.value) {
return pad.value * 2 + titleHeight.value;
} else {
return pad.value;
}
});
const choicesY = computed(() => {
const padding = pad.value;
const text = hasText.value;
let y = padding;
if (hasTitle.value) {
y += titleHeight.value;
if (text) {
y += padding / 2;
} else {
y += padding;
}
}
if (text) {
y += contentHeight.value;
y += padding / 2;
}
return y;
});
const choicesMaxHeight = computed(
() =>
maxHeight.value -
choicesY.value -
pad.value * 2 -
selFont.value.size -
8
);
const choiceCountPerPage = computed(() =>
Math.max(Math.floor(choicesMaxHeight.value / choiceHeight.value), 1)
);
const pages = computed(() =>
Math.ceil(props.choices.length / choiceCountPerPage.value)
);
const choicesHeight = computed(() => {
const padBottom = pages.value > 1 ? pad.value + selFont.value.size : 0;
if (props.choices.length > choiceCountPerPage.value) {
return choiceCountPerPage.value * choiceHeight.value + padBottom;
} else {
return props.choices.length * choiceHeight.value + padBottom;
}
});
const boxHeight = computed(() => {
if (props.choices.length > choiceCountPerPage.value) {
return (
choicesHeight.value +
choicesY.value +
// 不乘2是因为 choiceY 已经算上了顶部填充
pad.value
);
} else {
return (
choicesHeight.value +
choicesY.value +
// 不乘2是因为 choiceY 已经算上了顶部填充
pad.value
);
}
});
const boxLoc = computed<ElementLocator>(() => {
const [x = 0, y = 0, , , ax = 0, ay = 0] = props.loc;
return [x, y, props.width, boxHeight.value, ax, ay];
});
const titleLoc = computed<ElementLocator>(() => {
return [props.width / 2, pad.value, void 0, void 0, 0.5, 0];
});
const contentLoc = computed<ElementLocator>(() => {
return [
props.width / 2,
contentY.value,
contentWidth.value,
void 0,
0.5,
0
];
});
const choiceLoc = computed<ElementLocator>(() => {
return [
props.width / 2,
choicesY.value,
contentWidth.value,
choicesHeight.value,
0.5,
0
];
});
const selectionLoc = computed<ElementLocator>(() => {
const [width = 200, height = 200] = choiceSize[selected.value] ?? [];
return [
props.width / 2 - pad.value,
(selected.value + 0.5) * choiceHeight.value,
width + 8,
height + 8,
0.5,
0.5
];
});
const getPageContent = (page: number) => {
const count = choiceCountPerPage.value;
return props.choices.slice(page * count, (page + 1) * count);
};
const getChoiceLoc = (index: number): ElementLocator => {
return [
props.width / 2 - pad.value,
choiceHeight.value * (index + 0.5),
void 0,
void 0,
0.5,
0.5
];
};
const updateContentHeight = (height: number) => {
contentHeight.value = height;
};
const updateTitleHeight = (_0: string, _1: number, height: number) => {
titleHeight.value = height;
};
const updateChoiceSize = (index: number, width: number, height: number) => {
choiceSize[index] = [width, height];
};
const onPageChange = () => {
selected.value = 0;
};
const [key] = useKey();
key.realize('moveUp', () => {
if (selected.value === 0) {
if (pageCom.value?.now() !== 0) {
pageCom.value?.movePage(-1);
selected.value = choiceCountPerPage.value - 1;
}
} else {
selected.value--;
}
});
key.realize('moveDown', () => {
if (selected.value === choiceCountPerPage.value - 1) {
pageCom.value?.movePage(1);
selected.value = 0;
} else {
const page = pageCom.value?.now() ?? 1;
const index = page * choiceCountPerPage.value + selected.value;
if (index < props.choices.length - 1) {
selected.value++;
}
}
});
key.realize('moveLeft', () => pageCom.value?.movePage(-1));
key.realize('moveRight', () => pageCom.value?.movePage(1));
key.realize('confirm', () => {
const page = pageCom.value?.now() ?? 1;
const index = page * choiceCountPerPage.value + selected.value;
emit('choose', props.choices[index][0]);
});
return () => (
<container loc={boxLoc.value}>
<Background
loc={[0, 0, props.width, boxHeight.value]}
winskin={props.winskin}
color={props.color}
border={props.border}
/>
{hasTitle.value && (
<text
loc={titleLoc.value}
text={props.title}
font={props.titleFont ?? new Font(void 0, 18)}
fillStyle={props.titleFill ?? 'gold'}
zIndex={5}
onSetText={updateTitleHeight}
/>
)}
{hasText.value && (
<TextContent
{...attrs}
text={props.text}
loc={contentLoc.value}
width={contentWidth.value}
zIndex={5}
autoHeight
onUpdateHeight={updateContentHeight}
/>
)}
<Page
ref={pageCom}
loc={choiceLoc.value}
pages={pages.value}
font={props.selFont}
hideIfSingle
onPageChange={onPageChange}
>
{(page: number) => [
<Selection
loc={selectionLoc.value}
winskin={props.winskin}
color={props.color}
border={props.border}
/>,
...getPageContent(page).map((v, i) => {
return (
<text
text={v[1]}
loc={getChoiceLoc(i)}
font={props.selFont}
cursor="pointer"
zIndex={5}
onClick={() => emit('choose', v[0])}
onSetText={(_, width, height) =>
updateChoiceSize(i, width, height)
}
onEnter={() => (selected.value = i)}
/>
);
})
]}
</Page>
</container>
);
}, choicesProps);
/**
* 弹出一个确认框,然后将确认结果返回,例如给玩家弹出一个确认框,并获取玩家是否确认:
* ```ts
* const confirm = await getConfirm(
* // 在哪个 UI 控制器上打开,对于一般 UI 组件来说,直接填写 props.controller 即可
* props.controller,
* // 确认内容
* '确认要 xxx 吗?',
* // 确认框的位置,宽度由下一个参数指定,高度参数由组件内部计算得出,指定无效
* [240, 240, void 0, void 0, 0.5, 0.5],
* // 宽度设为 240
* 240,
* // 可以给选择框传入其他的 props,例如指定字体,此项可选
* { font: new Font('Verdana', 20) }
* );
* // 之后,就可以直接判断 confirm 来执行不同的操作了
* if (confirm) { ... }
* ```
* @param controller UI 控制器
* @param text 确认文本内容
* @param loc 确认框的位置
* @param width 确认框的宽度
* @param props 额外的 props,参考 {@link ConfirmBoxProps}
*/
export function getConfirm(
controller: IUIMountable,
text: string,
loc: ElementLocator,
width: number,
props?: Partial<ConfirmBoxProps>
) {
return new Promise<boolean>(res => {
const instance = controller.open(
ConfirmBoxUI,
{
...(props ?? {}),
loc,
text,
width,
onYes: () => {
controller.close(instance);
res(true);
},
onNo: () => {
controller.close(instance);
res(false);
}
},
true
);
});
}
/**
* 弹出一个选择框,然后将选择结果返回,例如给玩家弹出一个选择框,并获取玩家选择了哪个:
* ```ts
* const choice = await getChoice(
* // 在哪个 UI 控制器上打开,对于一般 UI 组件来说,直接填写 props.controller 即可
* props.controller,
* // 选项内容,参考 Choices 的注释
* [[0, '选项1'], [1, '选项2'], [2, '选项3']],
* // 选择框的位置,宽度由下一个参数指定,高度参数由组件内部计算得出,指定无效
* [240, 240, void 0, void 0, 0.5, 0.5],
* // 宽度设为 240
* 240,
* // 可以给选择框传入其他的 props,例如指定标题,此项可选
* { title: '选项标题' }
* );
* // 之后,就可以直接判断 choice 来执行不同的操作了
* if (choice === 0) { ... }
* ```
* @param controller UI 控制器
* @param choices 选择框的选项
* @param loc 选择框的位置
* @param width 选择框的宽度
* @param props 额外的 props,参考 {@link ChoicesProps}
*/
export function getChoice<T extends ChoiceKey = ChoiceKey>(
controller: IUIMountable,
choices: ChoiceItem[],
loc: ElementLocator,
width: number,
props?: Partial<ChoicesProps>
) {
return new Promise<T>(res => {
const instance = controller.open(
ChoicesUI,
{
...(props ?? {}),
choices,
loc,
width,
onChoose: key => {
controller.close(instance);
res(key as T);
}
},
true
);
});
}
/** @see {@link ConfirmBox} */
export const ConfirmBoxUI = new GameUI('confirm-box', ConfirmBox);
/** @see {@link Choices} */
export const ChoicesUI = new GameUI('choices', Choices);
@@ -0,0 +1,503 @@
import { DefaultProps, ElementLocator, GraphicPropsBase } from '@motajs/render';
import { computed, defineComponent, onMounted, Ref, ref, watch } from 'vue';
import { SetupComponentOptions } from './types';
export interface IconsProps extends DefaultProps<GraphicPropsBase> {
loc: ElementLocator;
}
const iconsProps = {
props: ['loc']
} satisfies SetupComponentOptions<IconsProps>;
type PathGenerator = (width: number, height: number) => Path2D;
/**
* @param ox 横向偏移坐标
* @param oy 纵向偏移坐标
* @param width 路径宽度
* @param height 路径高度
*/
type PathFn = (ox: number, oy: number, width: number, height: number) => Path2D;
function adjustPath(
aspect: number,
ref: Ref<Path2D | undefined>,
fn: PathFn
): PathGenerator {
let beforeWidth = 200;
let beforeHeight = 200;
let path: Path2D | undefined;
return (width, height) => {
if (width === beforeWidth && height === beforeHeight && path) {
return path;
}
beforeWidth = width;
beforeHeight = height;
const eleAspect = width / height;
let ox = 0;
let oy = 0;
let dw = 0;
let dh = 0;
if (aspect >= eleAspect) {
ox = 0;
dw = width;
dh = width / aspect;
oy = (height - dh) / 2;
} else {
oy = 0;
dh = height;
dw = height * aspect;
ox = (width - dw) / 2;
}
path = fn(ox, oy, dw, dh);
ref.value = path;
return path;
};
}
export const RollbackIcon = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const arc = width / 10;
const arrow = width / 10;
const left = ox + width / 10;
const top = oy + height / 5;
const right = ox + width - width / 10;
const bottom = oy + height - height / 5;
const end = left + width / 4;
path.moveTo(left, bottom);
path.lineTo(right - arc, bottom);
path.arcTo(right, bottom, right, bottom - arc, arc);
path.lineTo(right, top + arc);
path.arcTo(right, top, right - arc, top, arc);
path.lineTo(end, top);
path.moveTo(end + arrow, top - arrow);
path.lineTo(end, top);
path.lineTo(end + arrow, top + arrow);
path.moveTo(left, top);
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const RetweetIcon = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const arc = width / 10;
const arrow = width / 10;
const left = ox + width / 10;
const top = oy + height / 5;
const right = ox + width - width / 10;
const bottom = oy + height - height / 5;
const end = left + width / 2;
path.moveTo(end, bottom);
path.lineTo(left + arc, bottom);
path.arcTo(left, bottom, left, bottom - arc, arc);
path.lineTo(left, top + arc);
path.arcTo(left, top, left + arc, top, arc);
path.lineTo(right, top);
path.moveTo(right - arrow, top - arrow);
path.lineTo(right, top);
path.lineTo(right - arrow, top + arrow);
path.moveTo(left, top);
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const ViewMapIcon = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const left = ox + width / 5;
const top = oy + height / 5;
const right = ox + width - width / 5;
const bottom = oy + height - height / 5;
const cx = ox + width / 2;
const cy = oy + height / 2;
path.rect(left, top, right - left, bottom - top);
path.moveTo(cx, top);
path.lineTo(cx, bottom);
path.moveTo(left, cy);
path.lineTo(right, cy);
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const DanmakuIcon = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const left = ox + width / 5;
const bottom = oy + height - height / 5;
const cx = ox + width / 2;
const cy = oy + height / 2;
const rx = width / 3;
const ry = height / 4;
const start = (Math.PI * 16) / 18;
const end = (Math.PI * 12) / 18;
path.ellipse(cx, cy, rx, ry, 0, start, end);
path.lineTo(left - width / 24, bottom - height / 36);
path.closePath();
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const ReplayIcon = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const arc = width / 10;
const left = ox + width / 5;
const top = oy + height / 5;
const right = ox + width - width / 5;
const bottom = oy + height - height / 5;
const cy = oy + height / 2;
path.moveTo(right, cy - height / 8);
path.lineTo(right, top + arc);
path.arcTo(right, top, right - arc, top, arc);
path.lineTo(left + arc, top);
path.arcTo(left, top, left, top + arc, arc);
path.lineTo(left, cy);
path.moveTo(left + arc, cy - arc);
path.lineTo(left, cy);
path.lineTo(left - arc, cy - arc);
path.moveTo(left, cy + height / 8);
path.lineTo(left, bottom - arc);
path.arcTo(left, bottom, left + arc, bottom, arc);
path.lineTo(right - arc, bottom);
path.arcTo(right, bottom, right, bottom - arc, arc);
path.lineTo(right, cy);
path.moveTo(right - arc, cy + arc);
path.lineTo(right, cy);
path.lineTo(right + arc, cy + arc);
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const NumpadIcon = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const left = ox + width / 5;
const top = oy + height / 5;
const right = ox + width - width / 5;
const bottom = oy + height - height / 5;
const cx = ox + width / 2;
const cy = oy + height / 2;
path.rect(left, top, right - left, bottom - top);
const path2 = new Path2D();
path2.ellipse(cx, cy, width / 9, height / 6, 0, 0, Math.PI * 2);
path.addPath(path2);
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const PlayIcon = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const left = ox + width / 5;
const top = oy + height / 5;
const right = ox + width - width / 5;
const bottom = oy + height - height / 5;
path.moveTo(left, top);
path.lineTo(right, oy + height / 2);
path.lineTo(left, bottom);
path.closePath();
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
fill
stroke
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const PauseIcon = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const cx = ox + width / 2;
const top = oy + height / 5;
const bottom = oy + height - height / 5;
path.moveTo(cx - width / 5, top);
path.lineTo(cx - width / 5, bottom);
path.moveTo(cx + width / 5, top);
path.lineTo(cx + width / 5, bottom);
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const DoubleArrow = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const path2 = new Path2D();
const left = ox + width / 5;
const top = oy + height / 5;
const right = ox + width - width / 5;
const bottom = oy + height - height / 5;
const cx = ox + width / 2;
const cy = oy + height / 2;
path.moveTo(left, top + height / 12);
path.lineTo(cx + width / 8, cy);
path.lineTo(left, bottom - height / 12);
path.closePath();
path2.moveTo(cx, top + height / 12);
path2.lineTo(right, cy);
path2.lineTo(cx, bottom - height / 12);
path2.closePath();
path.addPath(path2);
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
fill
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const StepForward = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const path2 = new Path2D();
const left = ox + width / 5;
const top = oy + height / 5;
const right = ox + width - width / 5;
const bottom = oy + height - height / 5;
path.moveTo(left, top);
path.lineTo(right, oy + height / 2);
path.lineTo(left, bottom);
path.closePath();
path2.moveTo(right, top);
path2.lineTo(right, bottom);
path.addPath(path2);
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
fill
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
@@ -0,0 +1,9 @@
export * from './choices';
export * from './icons';
export * from './misc';
export * from './page';
export * from './scroll';
export * from './textbox';
export * from './textboxTyper';
export * from './tip';
export * from './types';
@@ -0,0 +1,583 @@
import {
DefaultProps,
ElementLocator,
onTick,
PathProps,
Sprite
} from '@motajs/render';
import { computed, defineComponent, ref, SetupContext, watch } from 'vue';
import { SetupComponentOptions } from './types';
import { MotaOffscreenCanvas2D } from '@motajs/render';
import { TextboxProps, TextContent, TextContentProps } from './textbox';
import { Scroll, ScrollExpose, ScrollProps } from './scroll';
import { transitioned } from '../use';
import { hyper } from 'mutate-animate';
import { logger } from '@motajs/common';
import { GameUI, IUIMountable } from '@motajs/system-ui';
interface ProgressProps extends DefaultProps {
/** 进度条的位置 */
loc: ElementLocator;
/** 进度条的进度,1表示完成,0表示未完成 */
progress: number;
/** 已完成部分的样式,默认为绿色(green) */
success?: CanvasStyle;
/** 未完成部分的样式,默认为灰色(gray) */
background?: CanvasStyle;
/** 线宽度 */
lineWidth?: number;
}
const progressProps = {
props: ['loc', 'progress', 'success', 'background']
} satisfies SetupComponentOptions<ProgressProps>;
/**
* 进度条组件,参数参考 {@link ProgressProps},用例如下:
* ```tsx
* // 定义进度
* const progress = ref(0);
*
* // 显示进度条
* <Progress loc={[12, 12, 120, 8]} progress={progress.value} />
* ```
*/
export const Progress = defineComponent<ProgressProps>(props => {
const element = ref<Sprite>();
const render = (canvas: MotaOffscreenCanvas2D) => {
const { ctx } = canvas;
const width = props.loc[2] ?? 200;
const height = props.loc[3] ?? 200;
ctx.lineCap = 'round';
const lineWidth = props.lineWidth ?? 2;
ctx.lineWidth = lineWidth;
ctx.strokeStyle = props.background ?? 'gray';
ctx.beginPath();
ctx.moveTo(lineWidth, height / 2);
ctx.lineTo(width - lineWidth, height / 2);
ctx.stroke();
if (!isNaN(props.progress)) {
ctx.strokeStyle = props.success ?? 'green';
const p = lineWidth + (width - lineWidth * 2) * props.progress;
ctx.beginPath();
ctx.moveTo(lineWidth, height / 2);
ctx.lineTo(p, height / 2);
ctx.stroke();
}
};
watch(props, () => {
element.value?.update();
});
return () => {
return <sprite ref={element} loc={props.loc} render={render}></sprite>;
};
}, progressProps);
export interface ArrowProps extends PathProps {
/** 箭头的起始和终点坐标,前两个是起始坐标,后两个是终点坐标 */
arrow: [number, number, number, number];
/** 箭头的头部大小 */
head?: number;
/** 箭头的颜色 */
color?: CanvasStyle;
}
const arrowProps = {
props: ['arrow', 'head', 'color']
} satisfies SetupComponentOptions<ArrowProps>;
/**
* 箭头组件,显示一个箭头,参数参考 {@link ArrowProps},用例如下:
* ```tsx
* // 从 (12, 12) 到 (48, 48) 的箭头
* <Arrow arrow={[12, 12, 48, 48]} />
* ```
*/
export const Arrow = defineComponent<ArrowProps>(props => {
const loc = computed<ElementLocator>(() => {
const [x1, y1, x2, y2] = props.arrow;
const left = Math.min(x1, x2);
const right = Math.max(x1, x2);
const top = Math.min(y1, y2);
const bottom = Math.max(y1, y2);
return [left, top, right - left, bottom - top];
});
const path = computed(() => {
const path = new Path2D();
const head = props.head ?? 8;
const [x = 0, y = 0] = loc.value;
const [x1, y1, x2, y2] = props.arrow;
path.moveTo(x1 - x, y1 - y);
path.lineTo(x2 - x, y2 - y);
const angle = Math.atan2(y2 - y1, x2 - x1);
path.moveTo(
x2 - head * Math.cos(angle - Math.PI / 6),
y2 - head * Math.sin(angle - Math.PI / 6)
);
path.lineTo(x2 - x, y2 - y);
path.lineTo(
x2 - head * Math.cos(angle + Math.PI / 6),
y2 - head * Math.sin(angle + Math.PI / 6)
);
return path;
});
return () => (
<g-path
loc={loc.value}
path={path.value}
stroke
strokeStyle={props.color}
lineCap="round"
lineJoin="round"
/>
);
}, arrowProps);
export interface ScrollTextProps extends TextboxProps, ScrollProps {
/** 自动滚动的速度,每秒多少像素 */
speed: number;
/** 文字的最大宽度 */
width: number;
/** 自动滚动组件的定位 */
loc: ElementLocator;
/** 文字滚动入元素之前要先滚动多少像素,默认16像素 */
pad?: number;
}
export type ScrollTextEmits = {
/**
* 当滚动完毕时触发
*/
scrollEnd: () => void;
};
export interface ScrollTextExpose {
/**
* 暂停滚动
*/
pause(): void;
/**
* 继续滚动
*/
resume(): void;
/**
* 设置滚动速度
*/
setSpeed(speed: number): void;
/**
* 立刻重新滚动
*/
rescroll(): void;
}
const scrollProps = {
props: ['speed', 'loc', 'pad', 'width'],
emits: ['scrollEnd']
} satisfies SetupComponentOptions<
ScrollTextProps,
ScrollTextEmits,
keyof ScrollTextEmits
>;
/**
* 滚动文字,可以用于展示长剧情或者 staff 表,参数参考 {@link ScrollTextProps},
* 事件参考 {@link ScrollTextEmits},函数接口参考 {@link ScrollTextExpose},用例如下:
* ```tsx
* // 用于接受函数接口
* const scroll = ref<ScrollTextExpose>();
* // 显示的文字
* const text = '滚动文字'.repeat(100);
*
* onMounted(() => {
* // 设置为每秒滚动 100 像素
* scroll.value?.setSpeed(100);
* // 暂停滚动
* scroll.value?.pause();
* });
*
* // 显示滚动文字,每秒滚动 50 像素
* <ScrollText ref={scroll} text={text} speed={50} loc={[0, 0, 180, 100]} width={180} />
* ```
*/
export const ScrollText = defineComponent<
ScrollTextProps,
ScrollTextEmits,
keyof ScrollTextEmits
>((props, { emit, expose, attrs }) => {
const scroll = ref<ScrollExpose>();
const speed = ref(props.speed);
const eleHeight = computed(() => props.loc[3] ?? props.width);
const pad = computed(() => props.pad ?? 16);
let lastFixedTime = Date.now();
let lastFixedPos = 0;
let paused = false;
let nowScroll = 0;
onTick(() => {
if (paused || !scroll.value) return;
const now = Date.now();
const dt = now - lastFixedTime;
nowScroll = (dt / 1000) * speed.value + lastFixedPos;
scroll.value.scrollTo(nowScroll, 0);
if (nowScroll >= scroll.value.getScrollLength()) {
emit('scrollEnd');
paused = true;
}
});
const pause = () => {
paused = true;
};
const resume = () => {
paused = false;
lastFixedPos = nowScroll;
lastFixedTime = Date.now();
};
const setSpeed = (value: number) => {
lastFixedPos = nowScroll;
lastFixedTime = Date.now();
speed.value = value;
};
const rescroll = () => {
nowScroll = 0;
lastFixedTime = Date.now();
lastFixedPos = 0;
};
expose<ScrollTextExpose>({ pause, resume, setSpeed, rescroll });
return () => (
<Scroll
ref={scroll}
loc={props.loc}
padEnd={eleHeight.value + pad.value}
noscroll
>
<TextContent
{...attrs}
width={props.width - 16}
loc={[8, eleHeight.value + pad.value]}
autoHeight
/>
</Scroll>
);
}, scrollProps);
export interface SelectionProps extends DefaultProps {
loc: ElementLocator;
color?: CanvasStyle;
border?: CanvasStyle;
winskin?: ImageIds;
/** 选择图标的不透明度范围 */
alphaRange?: [number, number];
}
const selectionProps = {
props: ['loc', 'color', 'border', 'winskin', 'alphaRange']
} satisfies SetupComponentOptions<SelectionProps>;
/**
* 显示一个选择光标,与 2.x 的 drawUIEventSelector 效果一致,参数参考 {@link SelectionProps},用例如下:
* ```tsx
* // 使用 winskin.png 作为选择光标,光标动画的不透明度范围是 [0.3, 0.8]
* <Selection loc={[24, 24, 80, 16]} winskin="winskin.png" alphaRange={[0.3, 0.8]} />
* // 使用指定的填充和边框颜色作为选择光标
* <Selection loc={[24, 24, 80, 16]} color="#ddd" border="gold" />
* ```
*/
export const Selection = defineComponent<SelectionProps>(props => {
const minAlpha = computed(() => props.alphaRange?.[0] ?? 0.25);
const maxAlpha = computed(() => props.alphaRange?.[1] ?? 0.55);
const alpha = transitioned(minAlpha.value, 2000, hyper('sin', 'in-out'))!;
const isWinskin = computed(() => !!props.winskin);
const winskinImage = computed(() =>
isWinskin.value ? core.material.images.images[props.winskin!] : null
);
const fixedLoc = computed<ElementLocator>(() => {
const [x = 0, y = 0, width = 200, height = 200] = props.loc;
return [x + 1, y + 1, width - 2, height - 2];
});
const renderWinskin = (canvas: MotaOffscreenCanvas2D) => {
const ctx = canvas.ctx;
const image = winskinImage.value;
if (!image) return;
const [, , width = 200, height = 200] = props.loc;
// 背景
ctx.drawImage(image, 130, 66, 28, 28, 2, 2, width - 4, height - 4);
// 四个角
ctx.drawImage(image, 128, 64, 2, 2, 0, 0, 2, 2);
ctx.drawImage(image, 158, 64, 2, 2, width - 2, 0, 2, 2);
ctx.drawImage(image, 128, 94, 2, 2, 0, height - 2, 2, 2);
ctx.drawImage(image, 158, 94, 2, 2, width - 2, height - 2, 2, 2);
// 四条边
ctx.drawImage(image, 130, 64, 28, 2, 2, 0, width - 4, 2);
ctx.drawImage(image, 130, 94, 28, 2, 2, height - 2, width - 4, 2);
ctx.drawImage(image, 128, 66, 2, 28, 0, 2, 2, height - 4);
ctx.drawImage(image, 158, 66, 2, 28, width - 2, 2, 2, height - 4);
};
onTick(() => {
if (alpha.value === maxAlpha.value) {
alpha.set(minAlpha.value);
}
if (alpha.value === minAlpha.value) {
alpha.set(maxAlpha.value);
}
});
return () =>
isWinskin.value ? (
<sprite
loc={props.loc}
render={renderWinskin}
alpha={alpha.ref.value}
noanti
/>
) : (
<g-rectr
loc={fixedLoc.value}
circle={[4]}
alpha={alpha.ref.value}
fill
stroke
fillStyle={props.color}
strokeStyle={props.border}
lineWidth={1}
/>
);
}, selectionProps);
export interface BackgroundProps extends DefaultProps {
loc: ElementLocator;
winskin?: ImageIds;
color?: CanvasStyle;
border?: CanvasStyle;
}
const backgroundProps = {
props: ['loc', 'winskin', 'color', 'border']
} satisfies SetupComponentOptions<BackgroundProps>;
/**
* 背景组件,与 Selection 类似,不过绘制的是背景,而不是选择光标,参数参考 {@link BackgroundProps},用例如下:
* ```tsx
* // 使用 winskin2.png 作为背景
* <Background loc={[8, 8, 160, 160]} winskin="winskin2.png" />
* // 使用指定填充和边框颜色作为背景
* <Background loc={[8, 8, 160, 160]} color="#333" border="gold" />
* ```
*/
export const Background = defineComponent<BackgroundProps>(props => {
const isWinskin = computed(() => !!props.winskin);
const fixedLoc = computed<ElementLocator>(() => {
const [x = 0, y = 0, width = 200, height = 200] = props.loc;
return [x + 2, y + 2, width - 4, height - 4];
});
return () =>
isWinskin.value ? (
<winskin image={props.winskin!} loc={props.loc} noanti />
) : (
<g-rectr
loc={fixedLoc.value}
fillStyle={props.color}
strokeStyle={props.border}
fill
stroke
lineWidth={2}
circle={[4]}
/>
);
}, backgroundProps);
export interface WaitBoxProps<T>
extends Partial<BackgroundProps>,
Partial<TextContentProps> {
loc: ElementLocator;
width: number;
promise?: Promise<T>;
text?: string;
pad?: number;
}
export type WaitBoxEmits<T> = {
resolve: (data: T) => void;
};
export interface WaitBoxExpose<T> {
/**
* 手动将此组件兑现,注意调用时如果传入的 Promise 还没有兑现,
* 当 Promise 兑现后将不会再次触发 resolve 事件,即 resolve 事件只会被触发一次
* @param data 兑现值
*/
resolve(data: T): void;
}
const waitBoxProps = {
props: ['promise', 'loc', 'winskin', 'color', 'border'],
emits: ['resolve']
} satisfies SetupComponentOptions<
WaitBoxProps<unknown>,
WaitBoxEmits<unknown>,
keyof WaitBoxEmits<unknown>
>;
/**
* 等待框,可以等待某个异步操作 (Promise),操作完毕后触发兑现事件,单次调用参考 {@link waitbox}。
* 参数参考 {@link WaitBoxProps},事件参考 {@link WaitBoxEmits},函数接口参考 {@link WaitBoxExpose}。用例如下:
* ```tsx
* // 创建一个等待 1000ms 的 Promise,兑现值是等待完毕时的当前时间刻
* const promise = new Promise(res => window.setTimeout(() => res(Date.now()), 1000));
*
* <WaitBox
* // 传入要等待的 Promise
* promise={promise}
* // 等待框的位置,宽度由 width 参数指定,高度由内部计算得来,不需要手动指定,即使手动指定也无效
* loc={[240, 240, void 0, void 0, 0.5, 0.5]}
* // 等待框的宽度
* width={240}
* // 完全继承 Background 的参数,因此可以直接指定背景样式
* winskin="winskin2.png"
* // 完全继承 TextContent 的参数,因此可以直接指定字体
* font={new Font('Verdana', 28)}
* />
* ```
*/
export const WaitBox = defineComponent<
WaitBoxProps<unknown>,
WaitBoxEmits<unknown>,
keyof WaitBoxEmits<unknown>
>(
<T,>(
props: WaitBoxProps<T>,
{ emit, expose, attrs }: SetupContext<WaitBoxEmits<T>>
) => {
const contentHeight = ref(200);
const text = computed(() => props.text ?? '请等待 ...');
const pad = computed(() => props.pad ?? 24);
const containerLoc = computed<ElementLocator>(() => {
const [x = 0, y = 0, , , ax = 0, ay = 0] = props.loc;
return [x, y, props.width, contentHeight.value, ax, ay];
});
const backLoc = computed<ElementLocator>(() => {
return [1, 1, props.width - 2, contentHeight.value - 2];
});
const contentLoc = computed<ElementLocator>(() => {
return [
pad.value,
pad.value,
props.width - pad.value * 2,
contentHeight.value - pad.value * 2
];
});
let resolved: boolean = false;
props.promise?.then(
value => {
resolve(value);
},
reason => {
logger.warn(63, reason);
}
);
const resolve = (data: T) => {
if (resolved) return;
resolved = true;
emit('resolve', data);
};
const onContentHeight = (height: number) => {
contentHeight.value = height + pad.value * 2;
};
expose<WaitBoxExpose<T>>({ resolve });
return () => (
<container loc={containerLoc.value}>
<Background
loc={backLoc.value}
zIndex={0}
winskin={props.winskin}
color={props.color}
border={props.border}
/>
<TextContent
{...attrs}
autoHeight
text={text.value}
loc={contentLoc.value}
width={props.width - pad.value * 2}
zIndex={5}
onUpdateHeight={onContentHeight}
/>
</container>
);
},
waitBoxProps
);
/**
* 打开一个等待框,等待传入的 Promise 兑现后,关闭等待框,并将兑现值返回。
* 示例,等待 1000ms:
* ```ts
* // 创建一个等待 1000ms 的 Promise,兑现值是等待完毕时的当前时间刻
* const promise = new Promise(res => window.setTimeout(() => res(Date.now()), 1000));
* const value = await waitbox(
* // 在哪个 UI 控制器上打开,对于一般 UI 组件来说,直接填写 props.controller 即可
* props.controller,
* // 确认框的位置,宽度由下一个参数指定,高度参数由组件内部计算得出,指定无效
* [240, 240, void 0, void 0, 0.5, 0.5],
* // 确认框的宽度
* 240,
* // 要等待的 Promise
* promise,
* // 额外的 props,例如填写等待文本,此项可选,参考 WaitBoxProps
* { text: '请等待 1000ms' }
* );
* console.log(value); // 输出时间刻
* ```
* @param controller UI 控制器
* @param loc 等待框的位置
* @param width 等待框的宽度
* @param promise 要等待的 Promise
* @param props 额外的 props,参考 {@link WaitBoxProps}
*/
export function waitbox<T>(
controller: IUIMountable,
loc: ElementLocator,
width: number,
promise: Promise<T>,
props?: Partial<WaitBoxProps<T>>
): Promise<T> {
return new Promise<T>(res => {
const instance = controller.open(WaitBoxUI, {
...(props ?? {}),
loc,
width,
promise,
onResolve: data => {
controller.close(instance);
res(data as T);
}
});
});
}
export const WaitBoxUI = new GameUI('wait-box', WaitBox);
@@ -0,0 +1,320 @@
import {
computed,
defineComponent,
nextTick,
onMounted,
ref,
SlotsType,
VNode,
watch
} from 'vue';
import { SetupComponentOptions } from './types';
import { clamp } from 'lodash-es';
import { DefaultProps, ElementLocator, Font } from '@motajs/render';
/** 圆角矩形页码距离容器的边框大小,与 pageSize 相乘 */
const RECT_PAD = 0.1;
export interface PageProps extends DefaultProps {
/** 共有多少页 */
pages: number;
/** 页码组件的定位 */
loc: ElementLocator;
/** 页码的字体 */
font?: Font;
/** 只有一页的时候,是否隐藏页码 */
hideIfSingle?: boolean;
}
export type PageEmits = {
pageChange: (page: number) => void;
};
export interface PageExpose {
/**
* 切换页码
* @param page 要切换至的页码数,1 表示第一页
*/
changePage(page: number): void;
/**
* 切换到传入的页码数加上当前页码数的页码
* @param delta 页码数增量
*/
movePage(delta: number): void;
/**
* 获取当前在第几页
*/
now(): number;
}
type PageSlots = SlotsType<{
default: (page: number) => VNode | VNode[];
}>;
const pageProps = {
props: ['pages', 'loc', 'font', 'hideIfSingle'],
emits: ['pageChange']
} satisfies SetupComponentOptions<
PageProps,
PageEmits,
keyof PageEmits,
PageSlots
>;
/**
* 分页组件,用于多页切换,例如存档界面等。参数参考 {@link PageProps},函数接口参考 {@link PageExpose}
*
* ---
*
* 用例如下,是一个在每页显示文字的用例,其中 page 表示页码索引,第一页就是 0,第二页就是 1,以此类推:
* ```tsx
* <Page maxPage={5}>
* {
* (page: number) => {
* return items[page].map(v => <text text={v.text} />)
* }
* }
* </Page>
* ```
*/
export const Page = defineComponent<
PageProps,
PageEmits,
keyof PageEmits,
PageSlots
>((props, { slots, expose, emit }) => {
const nowPage = ref(0);
// 五个元素的位置
const leftLoc = ref<ElementLocator>([]);
const leftPageLoc = ref<ElementLocator>([]);
const nowPageLoc = ref<ElementLocator>([]);
const rightPageLoc = ref<ElementLocator>([]);
const rightLoc = ref<ElementLocator>([]);
/** 内容的位置 */
const contentLoc = ref<ElementLocator>([]);
/** 页码容器的位置 */
const pageLoc = ref<ElementLocator>([]);
/** 页码的矩形框的位置 */
const rectLoc = ref<ElementLocator>([0, 0, 0, 0]);
/** 页面文字的位置 */
const textLoc = ref<ElementLocator>([0, 0, 0, 0]);
// 两个监听的参数
const leftArrow = ref<Path2D>();
const rightArrow = ref<Path2D>();
const hide = computed(() => props.hideIfSingle && props.pages === 1);
const font = computed(() => props.font ?? new Font());
const isFirst = computed(() => nowPage.value === 0);
const isLast = computed(() => nowPage.value === props.pages - 1);
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const round = computed(() => font.value.size / 4);
const nowPageFont = computed(() => Font.clone(font.value, { weight: 700 }));
// 左右箭头的颜色
const leftColor = computed(() => (isFirst.value ? '#666' : '#ddd'));
const rightColor = computed(() => (isLast.value ? '#666' : '#ddd'));
let updating = false;
const updatePagePos = () => {
if (updating) return;
updating = true;
nextTick(() => {
updating = false;
});
const pageH = hide.value ? 0 : font.value.size + 8;
contentLoc.value = [0, 0, width.value, height.value - pageH];
pageLoc.value = [0, height.value - pageH, width.value, pageH];
const center = width.value / 2;
const size = font.value.size * 1.5;
nowPageLoc.value = [center, 0, size, size, 0.5, 0];
leftPageLoc.value = [center - size * 1.5, 0, size, size, 0.5, 0];
leftLoc.value = [center - size * 3, 0, size, size, 0.5, 0];
rightPageLoc.value = [center + size * 1.5, 0, size, size, 0.5, 0];
rightLoc.value = [center + size * 3, 0, size, size, 0.5, 0];
};
const updateArrowPath = () => {
const rectSize = font.value.size * 1.5;
const size = font.value.size;
const pad = rectSize - size;
const left = new Path2D();
left.moveTo(size, pad);
left.lineTo(pad, rectSize / 2);
left.lineTo(size, rectSize - pad);
const right = new Path2D();
right.moveTo(pad, pad);
right.lineTo(size, rectSize / 2);
right.lineTo(pad, rectSize - pad);
leftArrow.value = left;
rightArrow.value = right;
};
const updateRectAndText = () => {
const size = font.value.size * 1.5;
const pad = RECT_PAD * size;
rectLoc.value = [pad, pad, size - pad * 2, size - pad * 2];
textLoc.value = [size / 2, size / 2, void 0, void 0, 0.5, 0.5];
};
watch(font, () => {
updatePagePos();
updateArrowPath();
updateRectAndText();
});
watch(
() => props.loc,
() => {
updatePagePos();
updateRectAndText();
}
);
/**
* 切换页码
*/
const changePage = (page: number) => {
const target = clamp(page, 0, props.pages - 1);
if (nowPage.value !== target) {
nowPage.value = target;
emit('pageChange', target);
}
};
const movePage = (delta: number) => {
changePage(nowPage.value + delta);
};
const now = () => nowPage.value;
const lastPage = () => {
changePage(nowPage.value - 1);
};
const nextPage = () => {
changePage(nowPage.value + 1);
};
onMounted(() => {
updatePagePos();
updateArrowPath();
updateRectAndText();
});
expose<PageExpose>({ changePage, movePage, now });
return () => {
return (
<container loc={props.loc}>
<container loc={contentLoc.value}>
{slots.default?.(nowPage.value)}
</container>
<container loc={pageLoc.value} hidden={hide.value}>
<container
key={1}
loc={leftLoc.value}
onClick={lastPage}
cursor="pointer"
>
<g-rectr
loc={rectLoc.value}
circle={[round.value]}
strokeStyle={leftColor.value}
lineWidth={1}
stroke
></g-rectr>
<g-path
path={leftArrow.value}
stroke
strokeStyle={leftColor.value}
lineWidth={1}
></g-path>
</container>
{!isFirst.value && (
<container
key={2}
loc={leftPageLoc.value}
onClick={lastPage}
cursor="pointer"
>
<g-rectr
loc={rectLoc.value}
circle={[round.value]}
strokeStyle="#ddd"
lineWidth={1}
stroke
></g-rectr>
<text
loc={textLoc.value}
text={nowPage.value.toString()}
font={font.value}
></text>
</container>
)}
<container loc={nowPageLoc.value} key={3}>
<g-rectr
loc={rectLoc.value}
circle={[round.value]}
strokeStyle="#ddd"
fillStyle="#ddd"
lineWidth={1}
fill
stroke
></g-rectr>
<text
loc={textLoc.value}
text={(nowPage.value + 1).toString()}
fillStyle="#222"
font={nowPageFont.value}
></text>
</container>
{!isLast.value && (
<container
key={4}
loc={rightPageLoc.value}
onClick={nextPage}
cursor="pointer"
>
<g-rectr
loc={rectLoc.value}
circle={[round.value]}
strokeStyle="#ddd"
lineWidth={1}
stroke
></g-rectr>
<text
loc={textLoc.value}
text={(nowPage.value + 2).toString()}
font={font.value}
></text>
</container>
)}
<container
key={5}
loc={rightLoc.value}
onClick={nextPage}
cursor="pointer"
>
<g-rectr
loc={rectLoc.value}
circle={[round.value]}
strokeStyle={rightColor.value}
lineWidth={1}
stroke
></g-rectr>
<g-path
path={rightArrow.value}
stroke
strokeStyle={rightColor.value}
lineWidth={1}
></g-path>
</container>
</container>
</container>
);
};
}, pageProps);
@@ -0,0 +1,556 @@
import {
computed,
defineComponent,
nextTick,
onMounted,
onUnmounted,
onUpdated,
ref,
SlotsType,
VNode,
watch
} from 'vue';
import { SetupComponentOptions } from './types';
import {
Container,
DefaultProps,
ElementLocator,
RenderItem,
Sprite,
Transform,
MotaOffscreenCanvas2D,
IActionEvent,
IWheelEvent,
MouseType
} from '@motajs/render';
import { hyper, linear, Transition } from 'mutate-animate';
import { clamp } from 'lodash-es';
import { transitioned } from '../use';
export const enum ScrollDirection {
Horizontal,
Vertical
}
export interface ScrollExpose {
/**
* 控制滚动条滚动至目标位置
* @param y 滚动至的目标位置
* @param time 滚动的动画时长,默认为无动画
*/
scrollTo(y: number, time?: number): void;
/**
* 获取这个滚动条组件最多可以滚动多长
*/
getScrollLength(): number;
}
export interface ScrollProps extends DefaultProps {
loc: ElementLocator;
hor?: boolean;
noscroll?: boolean;
/**
* 滚动到最下方(最右方)时的填充大小,如果默认的高度计算方式有误,
* 那么可以调整此参数来修复错误
*/
padEnd?: number;
}
type ScrollSlots = SlotsType<{
default: () => VNode | VNode[];
}>;
const scrollProps = {
props: ['hor', 'noscroll', 'loc', 'padEnd']
} satisfies SetupComponentOptions<ScrollProps, {}, string, ScrollSlots>;
/** 滚动条图示的最短长度 */
const SCROLL_MIN_LENGTH = 20;
/** 滚动条图示的宽度 */
const SCROLL_WIDTH = 10;
/** 滚动条的颜色 */
const SCROLL_COLOR = '255,255,255';
/**
* 滚动条组件,具有虚拟滚动功能,即在画面外的不渲染。参数参考 {@link ScrollProps},暴露接口参考 {@link ScrollExpose}
*
* ---
*
* 使用时,建议使用平铺式布局,即包含很多子元素,而不要用一个 container 将所有内容包裹,
* 每个子元素的高度(宽度)不建议过大,以更好地通过虚拟滚动优化
*
* **推荐写法**:
* ```tsx
* <Scroll>
* <item />
* <item />
* ...其他元素
* <item />
* <item />
* </Scroll>
* ```
* **不推荐**使用这种写法:
* ```tsx
* <Scroll>
* <container>
* <item />
* </container>
* <Scroll>
* ```
*/
export const Scroll = defineComponent<ScrollProps, {}, string, ScrollSlots>(
(props, { slots, expose }) => {
/** 滚动条的定位 */
const sp = ref<ElementLocator>([0, 0, 1, 1]);
const listenedChild: Set<RenderItem> = new Set();
const areaMap: Map<RenderItem, [number, number]> = new Map();
const content = ref<Container>();
const scroll = ref<Sprite>();
const scrollAlpha = transitioned(0.5, 100, linear())!;
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const direction = computed(() =>
props.hor ? ScrollDirection.Horizontal : ScrollDirection.Vertical
);
const scrollColor = computed(
() => `rgba(${SCROLL_COLOR},${scrollAlpha.ref.value ?? 0.5})`
);
const padEnd = computed(() => props.padEnd ?? 0);
watch(scrollColor, () => {
scroll.value?.update();
});
/** 滚动内容的当前位置 */
let contentPos = 0;
/** 滚动条的当前位置 */
let scrollPos = 0;
/** 滚动内容的目标位置 */
let contentTarget = 0;
/** 滚动条的目标位置 */
let scrollTarget = 0;
/** 滚动内容的长度 */
let maxLength = 0;
/** 滚动条的长度 */
let scrollLength = SCROLL_MIN_LENGTH;
const transition = new Transition();
transition.value.scroll = 0;
transition.value.showScroll = 0;
transition.mode(hyper('sin', 'out')).absolute();
//#region 滚动操作
transition.ticker.add(() => {
if (scrollPos !== scrollTarget) {
scrollPos = transition.value.scroll;
content.value?.update();
}
if (contentPos !== contentTarget) {
contentPos = transition.value.showScroll;
checkAllItem();
content.value?.update();
}
});
/**
* 滚动到目标值
* @param time 动画时长
*/
const scrollTo = (y: number, time: number = 0) => {
if (maxLength < height.value) return;
const max = maxLength - height.value;
const target = clamp(y, 0, max);
contentTarget = target;
if (direction.value === ScrollDirection.Horizontal) {
scrollTarget =
(width.value - scrollLength) * (contentTarget / max);
} else {
scrollTarget =
(height.value - scrollLength) * (contentTarget / max);
}
if (isNaN(scrollTarget)) scrollTarget = 0;
transition.time(time).transition('scroll', scrollTarget);
transition.time(time).transition('showScroll', target);
};
/**
* 计算一个元素会在画面上显示的区域
*/
const getArea = (item: RenderItem, rect: DOMRectReadOnly) => {
if (direction.value === ScrollDirection.Horizontal) {
areaMap.set(item, [rect.left - width.value, rect.right]);
} else {
areaMap.set(item, [rect.top - height.value, rect.bottom]);
}
};
/**
* 检查一个元素是否需要显示,不需要则隐藏
*/
const checkItem = (item: RenderItem) => {
const area = areaMap.get(item);
if (!area) {
item.show();
return;
}
const [min, max] = area;
if (contentPos > min - 10 && contentPos < max + 10) {
item.show();
} else {
item.hide();
}
};
/**
* 对所有元素执行显示检查
*/
const checkAllItem = () => {
content.value?.children.forEach(v => checkItem(v));
};
/**
* 当一个元素的矩阵发生变换时执行,检查其显示区域
*/
const onTransform = (item: RenderItem) => {
const rect = item.getBoundingRect();
const pad = props.padEnd ?? 0;
if (item.parent === content.value) {
if (direction.value === ScrollDirection.Horizontal) {
if (rect.right > maxLength - pad) {
maxLength = rect.right + pad;
updatePosition();
}
} else {
if (rect.bottom > maxLength - pad) {
maxLength = rect.bottom + pad;
updatePosition();
}
}
} else {
item.off('transform', onTransform);
listenedChild.delete(item);
}
getArea(item, rect);
checkItem(item);
scroll.value?.update();
content.value?.update();
};
/**
* 更新滚动条位置
*/
const updatePosition = () => {
if (direction.value === ScrollDirection.Horizontal) {
scrollLength = clamp(
(height.value / maxLength) * width.value,
SCROLL_MIN_LENGTH,
width.value
);
const h = props.noscroll
? height.value
: height.value - SCROLL_WIDTH;
sp.value = [0, h, width.value, SCROLL_WIDTH];
} else {
scrollLength = clamp(
(height.value / maxLength) * height.value,
SCROLL_MIN_LENGTH,
height.value
);
const w = props.noscroll
? width.value
: width.value - SCROLL_WIDTH;
sp.value = [w, 0, SCROLL_WIDTH, height.value];
}
};
let updating = false;
const updateScroll = () => {
if (!content.value || updating) return;
updating = true;
nextTick(() => {
updating = false;
});
let max = 0;
listenedChild.forEach(v => v.off('transform', onTransform));
listenedChild.clear();
areaMap.clear();
content.value.children.forEach(v => {
if (v.isComment) return;
const rect = v.getBoundingRect();
if (direction.value === ScrollDirection.Horizontal) {
if (rect.right > max) {
max = rect.right;
}
} else {
if (rect.bottom > max) {
max = rect.bottom;
}
}
getArea(v, rect);
if (!listenedChild.has(v)) {
v.on('transform', onTransform);
listenedChild.add(v);
}
checkItem(v);
});
maxLength = Math.max(max + padEnd.value, 10);
updatePosition();
scroll.value?.update();
};
watch(() => props.loc, updateScroll);
onUpdated(updateScroll);
onMounted(updateScroll);
onUnmounted(() => {
listenedChild.forEach(v => v.off('transform', onTransform));
});
//#endregion
//#region 渲染滚动
const drawScroll = (canvas: MotaOffscreenCanvas2D) => {
if (props.noscroll) return;
const ctx = canvas.ctx;
ctx.lineCap = 'round';
ctx.lineWidth = 3;
ctx.strokeStyle = scrollColor.value;
ctx.beginPath();
const scroll = transition.value.scroll;
if (direction.value === ScrollDirection.Horizontal) {
ctx.moveTo(scroll + 5, 5);
ctx.lineTo(scroll + scrollLength - 5, 5);
} else {
ctx.moveTo(5, scroll + 5);
ctx.lineTo(5, scroll + scrollLength - 5);
}
ctx.stroke();
};
const renderContent = (
canvas: MotaOffscreenCanvas2D,
children: RenderItem[],
transform: Transform
) => {
const ctx = canvas.ctx;
ctx.save();
if (direction.value === ScrollDirection.Horizontal) {
ctx.translate(-contentPos, 0);
} else {
ctx.translate(0, -contentPos);
}
children.forEach(v => {
if (v.hidden) return;
v.renderContent(canvas, transform);
});
ctx.restore();
};
//#endregion
//#region 事件监听
const wheelScroll = (delta: number, max: number) => {
const sign = Math.sign(delta);
const dx = Math.abs(delta);
const movement = Math.min(max, dx) * sign;
scrollTo(contentTarget + movement, dx > 10 ? 300 : 0);
};
const wheel = (ev: IWheelEvent) => {
if (direction.value === ScrollDirection.Horizontal) {
if (ev.wheelX !== 0) {
wheelScroll(ev.wheelX, width.value / 5);
} else if (ev.wheelY !== 0) {
wheelScroll(ev.wheelY, width.value / 5);
}
} else {
wheelScroll(ev.wheelY, height.value / 5);
}
};
const getPos = (ev: IActionEvent, absolute: boolean = false) => {
if (absolute) {
if (direction.value === ScrollDirection.Horizontal) {
return ev.absoluteX;
} else {
return ev.absoluteY;
}
} else {
if (direction.value === ScrollDirection.Horizontal) {
return ev.offsetX;
} else {
return ev.offsetY;
}
}
};
let identifier = -2;
let downPos = 0;
/** 拖动内容时,内容原本所在的位置 */
let contentBefore = 0;
const down = (ev: IActionEvent) => {
identifier = ev.identifier;
downPos = getPos(ev, true);
contentBefore = contentTarget;
};
const move = (ev: IActionEvent) => {
if (ev.identifier !== identifier) return;
let pos = 0;
if (ev.touch) {
pos = getPos(ev);
} else {
if (ev.buttons & MouseType.Left) {
pos = getPos(ev);
} else {
return;
}
}
const movement = pos - downPos;
scrollTo(contentBefore - movement, 0);
};
/** 最初滚动条在哪 */
let scrollBefore = 0;
/** 本次拖动滚动条的操作标识符 */
let scrollIdentifier = -2;
/** 点击滚动条时,点击位置在平行于滚动条方向的位置 */
let scrollDownPos = 0;
/** 是否是点击了滚动条区域中滚动条之外的地方,这样视为类滚轮操作 */
let scrollMutate = false;
/** 点击滚动条时,点击位置垂直于滚动条方向的位置 */
let scrollPin = 0;
/**
* 获取点击滚动条时,垂直于滚动条方向的位置
*/
const getScrollPin = (ev: IActionEvent) => {
if (direction.value === ScrollDirection.Horizontal) {
return ev.absoluteY;
} else {
return ev.absoluteX;
}
};
const downScroll = (ev: IActionEvent) => {
scrollBefore = contentTarget;
scrollIdentifier = ev.identifier;
const pos = getPos(ev, true);
// 计算点击在了滚动条的哪个位置
const offsetPos = getPos(ev);
const sEnd = scrollPos + scrollLength;
if (offsetPos >= scrollPos && offsetPos <= sEnd) {
scrollDownPos = pos - scrollPos;
scrollMutate = false;
scrollPin = getScrollPin(ev);
} else {
scrollMutate = true;
}
scrollAlpha.set(0.9);
};
const moveScroll = (ev: IActionEvent) => {
if (ev.identifier !== scrollIdentifier || scrollMutate) return;
const pos = getPos(ev, true);
const scrollPos = pos - scrollDownPos;
let deltaPin = 0;
let threshold = 0;
if (ev.touch) {
const pin = getScrollPin(ev);
deltaPin = Math.abs(pin - scrollPin);
threshold = 200;
} else {
const pin = getScrollPin(ev);
deltaPin = Math.abs(pin - scrollPin);
threshold = 100;
}
if (deltaPin > threshold) {
scrollTo(scrollBefore, 0);
} else {
const pos = (scrollPos / height.value) * maxLength;
scrollTo(pos, 0);
}
};
const upScroll = (ev: IActionEvent) => {
scrollAlpha.set(0.7);
if (!scrollMutate) return;
const pos = getPos(ev);
if (pos < scrollPos) {
scrollTo(contentTarget - 50, 300);
} else {
scrollTo(contentTarget + 50, 300);
}
};
const enter = () => {
scrollAlpha.set(0.7);
};
const leave = () => {
scrollAlpha.set(0.5);
};
//#endregion
onMounted(() => {
scroll.value?.root?.on('move', move);
scroll.value?.root?.on('move', moveScroll);
});
onUnmounted(() => {
scroll.value?.root?.off('move', move);
scroll.value?.root?.off('move', moveScroll);
transition.ticker.destroy();
});
//#region expose 函数
const getScrollLength = () => {
return maxLength - height.value;
};
expose<ScrollExpose>({
scrollTo,
getScrollLength
});
//#endregion
return () => {
return (
<container loc={props.loc} onWheel={wheel}>
<container-custom
loc={[0, 0, props.loc[2], props.loc[3]]}
ref={content}
onDown={down}
render={renderContent}
zIndex={0}
>
{slots.default?.()}
</container-custom>
<sprite
nocache
hidden={props.noscroll}
loc={sp.value}
ref={scroll}
render={drawScroll}
onDown={downScroll}
onUp={upScroll}
zIndex={10}
onEnter={enter}
onLeave={leave}
></sprite>
</container>
);
};
},
scrollProps
);
@@ -0,0 +1,593 @@
import {
ElementLocator,
Font,
Sprite,
DefaultProps,
Text,
MotaOffscreenCanvas2D
} from '@motajs/render';
import {
computed,
defineComponent,
nextTick,
onMounted,
onUnmounted,
ref,
shallowReactive,
shallowRef,
SlotsType,
VNode,
watch
} from 'vue';
import { logger } from '@motajs/common';
import { isNil } from 'lodash-es';
import { SetupComponentOptions } from './types';
import EventEmitter from 'eventemitter3';
import {
ITextContentConfig,
TextContentTyper,
TyperRenderable,
TextContentType,
WordBreak,
TextAlign
} from './textboxTyper';
export interface TextContentProps
extends DefaultProps,
Partial<ITextContentConfig> {
/** 显示的文字 */
text?: string;
/** 是否填充 */
fill?: boolean;
/** 是否描边 */
stroke?: boolean;
/** 是否自适应高度 */
autoHeight?: boolean;
/** 文字的最大宽度 */
width: number;
}
export type TextContentEmits = {
typeEnd: () => void;
typeStart: () => void;
updateHeight: (height: number) => void;
};
export interface TextContentExpose {
/**
* 重新开始打字
*/
retype(): void;
/**
* 立刻显示所有文字
*/
showAll(): void;
/**
* 获取这段 TextContent 的总高度
*/
getHeight(): number;
}
const textContentOptions = {
props: [
'breakChars',
'font',
'ignoreLineEnd',
'ignoreLineStart',
'interval',
'keepLast',
'lineHeight',
'text',
'textAlign',
'wordBreak',
'fill',
'fillStyle',
'strokeStyle',
'strokeWidth',
'stroke',
'loc',
'width',
'autoHeight'
],
emits: ['typeEnd', 'typeStart', 'updateHeight']
} satisfies SetupComponentOptions<
TextContentProps,
TextContentEmits,
keyof TextContentEmits
>;
export const TextContent = defineComponent<
TextContentProps,
TextContentEmits,
keyof TextContentEmits
>((props, { emit, expose }) => {
const loc = ref<ElementLocator>(
(props.loc?.slice() as ElementLocator) ?? []
);
if (props.width < 0) {
logger.warn(41, String(props.width));
}
const typer = new TextContentTyper(props);
let renderable: TyperRenderable[] = [];
let needUpdate = false;
const retype = () => {
if (needUpdate) return;
needUpdate = true;
if (!spriteElement.value) {
needUpdate = false;
}
renderable = [];
spriteElement.value?.requestBeforeFrame(() => {
typer.setConfig(props);
typer.setText(props.text ?? '');
typer.type();
needUpdate = false;
updateLoc();
});
};
const showAll = () => {
typer.typeAll();
};
watch(props, () => {
typer.setConfig(props);
retype();
});
const getHeight = () => {
return typer.getHeight();
};
const updateLoc = () => {
const height = getHeight();
if (props.autoHeight) {
const [x = 0, y = 0, width = 200, , ax = 0, ay = 0] = loc.value;
loc.value = [x, y, width, height, ax, ay];
}
emit('updateHeight', height);
};
expose<TextContentExpose>({ retype, showAll, getHeight });
const spriteElement = shallowRef<Sprite>();
const renderContent = (canvas: MotaOffscreenCanvas2D) => {
const ctx = canvas.ctx;
ctx.textBaseline = 'top';
renderable.forEach(v => {
switch (v.type) {
case TextContentType.Text: {
if (v.text.length === 0) return;
ctx.fillStyle = v.fillStyle;
ctx.strokeStyle = v.strokeStyle;
ctx.font = v.font;
const text = v.text.slice(0, v.pointer);
if (props.fill ?? true) {
ctx.fillText(text, v.x, v.y);
}
if (props.stroke) {
ctx.strokeText(text, v.x, v.y);
}
break;
}
case TextContentType.Icon: {
const { renderable: r, x: dx, y: dy, width, height } = v;
const render = r.render;
const [x, y, w, h] = render[0];
const icon = r.autotile ? r.image[0] : r.image;
ctx.drawImage(icon, x, y, w, h, dx, dy, width, height);
break;
}
}
});
};
const renderFunc = (data: TyperRenderable[]) => {
renderable = data;
spriteElement.value?.update();
};
typer.setRender(renderFunc);
typer.on('typeStart', () => {
emit('typeStart');
});
typer.on('typeEnd', () => {
emit('typeEnd');
});
onMounted(retype);
return () => {
return (
<sprite
loc={loc.value}
ref={spriteElement}
render={renderContent}
></sprite>
);
};
}, textContentOptions);
export interface TextboxProps extends TextContentProps, DefaultProps {
/** 背景颜色 */
backColor?: CanvasStyle;
/** 背景 winskin */
winskin?: ImageIds;
/** 边框与文字间的距离,默认为8 */
padding?: number;
/** 标题 */
title?: string;
/** 标题字体 */
titleFont?: Font;
/** 标题填充样式 */
titleFill?: CanvasStyle;
/** 标题描边样式 */
titleStroke?: CanvasStyle;
/** 标题文字与边框间的距离,默认为4 */
titlePadding?: number;
/** 最大宽度 */
width: number;
}
export interface TextboxExpose {
/**
* 显示这个文本框
*/
show(): void;
/**
* 隐藏这个文本框
*/
hide(): void;
/**
* 重新开始打字
*/
retype(): void;
/**
* 立刻显示所有文字
*/
showAll(): void;
}
type TextboxEmits = TextContentEmits;
type TextboxSlots = SlotsType<{
default: (data: TextboxProps) => VNode[];
title: (data: TextboxProps) => VNode[];
}>;
const textboxOptions = {
props: (textContentOptions.props as (keyof TextboxProps)[]).concat([
'backColor',
'winskin',
'padding',
'titleFill',
'titleStroke',
'titleFont',
'titlePadding',
'id',
'hidden',
'title'
]),
emits: textContentOptions.emits
} satisfies SetupComponentOptions<TextboxProps, {}, string, TextboxSlots>;
let id = 0;
function getNextTextboxId() {
return `@default-textbox-${id++}`;
}
export const Textbox = defineComponent<
TextboxProps,
TextboxEmits,
keyof TextboxEmits,
TextboxSlots
>((props, { slots, expose }) => {
const contentData = shallowReactive<TextContentProps>({ width: 200 });
const data = shallowReactive<TextboxProps>({ width: 200 });
const setContentData = () => {
contentData.breakChars = props.breakChars ?? '';
contentData.font = props.font ?? new Font();
contentData.ignoreLineEnd = props.ignoreLineEnd ?? '';
contentData.ignoreLineStart = props.ignoreLineStart ?? '';
contentData.interval = props.interval ?? 0;
contentData.keepLast = props.keepLast ?? false;
contentData.lineHeight = props.lineHeight ?? 0;
contentData.text = props.text ?? '';
contentData.textAlign = props.textAlign ?? TextAlign.Left;
contentData.wordBreak = props.wordBreak ?? WordBreak.Space;
contentData.fill = props.fill ?? true;
contentData.stroke = props.stroke ?? false;
contentData.fillStyle = props.fillStyle ?? '#fff';
contentData.strokeStyle = props.strokeStyle ?? '#000';
contentData.strokeWidth = props.strokeWidth ?? 2;
contentData.loc = props.loc;
contentData.width = props.width;
};
const setTextboxData = () => {
data.backColor = props.backColor ?? '#222';
data.winskin = props.winskin;
data.padding = props.padding ?? 8;
data.titleFill = props.titleFill ?? 'gold';
data.titleStroke = props.titleStroke ?? 'transparent';
data.titleFont = props.titleFont ?? new Font('Verdana', 18);
data.titlePadding = props.titlePadding ?? 8;
data.width = props.width ?? props.loc?.[2] ?? 200;
data.height = props.height ?? props.loc?.[3] ?? 200;
data.title = props.title ?? '';
};
setContentData();
setTextboxData();
watch(props, () => {
const needUpdateTitle = data.title !== props.title;
setTextboxData();
if (needUpdateTitle) {
onSetText();
}
});
const titleElement = ref<Text>();
const content = ref<TextContentExpose>();
const hidden = ref(props.hidden);
/** 标题宽度 */
const tw = ref(data.titlePadding! * 2);
/** 标题高度 */
const th = ref(data.titlePadding! * 2);
const contentY = computed(() => {
const height = th.value;
return data.title ? height : 0;
});
const backHeight = computed(() => data.height! - contentY.value);
const contentWidth = computed(() => data.width! - data.padding! * 2);
const contentHeight = computed(
() => data.height! - data.padding! * 2 - contentY.value
);
const onSetText = () => {
nextTick(() => {
titleElement.value?.requestBeforeFrame(() => {
if (titleElement.value) {
const { width, height } = titleElement.value;
tw.value = width + data.padding! * 2;
th.value = height + data.padding! * 2;
}
});
});
};
// ----- store
/** 结束打字机 */
const storeEmits: TextboxStoreEmits = {
endType() {
content.value?.showAll();
},
hide() {
hidden.value = true;
},
show() {
hidden.value = false;
},
update(value) {
if (data.title !== value.title) {
data.title = value.title;
onSetText();
}
},
setText(text) {
if (contentData.text === text) {
content.value?.retype();
} else {
contentData.text = text;
}
}
};
const store = TextboxStore.use(
props.id ?? getNextTextboxId(),
contentData,
storeEmits
);
const onTypeStart = () => {
store.emitTypeStart();
};
const onTypeEnd = () => {
store.emitTypeEnd();
};
expose<TextboxExpose>({
show() {
hidden.value = false;
},
hide() {
hidden.value = true;
},
retype() {
content.value?.retype();
},
showAll() {
content.value?.showAll();
}
});
return () => (
<container
id={props.id}
hidden={hidden.value}
alpha={data.alpha}
loc={props.loc}
>
{data.title && (
<container zIndex={10} loc={[0, 0, tw.value, th.value]}>
{slots.title ? (
slots.title(data)
) : props.winskin ? (
<winskin
image={props.winskin}
loc={[0, 0, tw.value, th.value]}
></winskin>
) : (
<g-rect loc={[0, 0, tw.value, th.value]}></g-rect>
)}
<text
ref={titleElement}
text={data.title}
loc={[data.titlePadding, data.titlePadding]}
fillStyle={data.titleFill}
strokeStyle={data.titleStroke}
font={data.titleFont}
></text>
</container>
)}
{slots.default ? (
slots.default(data)
) : props.winskin ? (
<winskin
image={props.winskin}
loc={[0, contentY.value, data.width!, backHeight.value]}
></winskin>
) : (
<g-rect
loc={[0, contentY.value, data.width!, backHeight.value]}
fill
fillStyle={data.backColor}
></g-rect>
)}
<TextContent
{...contentData}
ref={content}
x={data.padding!}
y={contentY.value + data.padding!}
width={contentWidth.value}
height={contentHeight.value}
onTypeEnd={onTypeEnd}
onTypeStart={onTypeStart}
></TextContent>
</container>
);
}, textboxOptions);
interface TextboxStoreEmits {
endType: () => void;
hide: () => void;
show: () => void;
update: (value: TextboxProps) => void;
setText: (text: string) => void;
}
interface TextboxStoreEvent {
update: [value: TextboxProps];
show: [];
hide: [];
typeStart: [];
typeEnd: [];
}
export class TextboxStore extends EventEmitter<TextboxStoreEvent> {
static list: Map<string, TextboxStore> = new Map();
typing: boolean = false;
private constructor(
private readonly data: TextboxProps,
private readonly emits: TextboxStoreEmits
) {
super();
}
/**
* 开始打字,由组件调用,而非组件外调用
*/
emitTypeStart() {
this.typing = true;
this.emit('typeStart');
}
/**
* 结束打字,由组件调用,而非组件外调用
*/
emitTypeEnd() {
this.typing = false;
this.emit('typeEnd');
}
/**
* 结束打字机的打字
*/
endType() {
this.emits.endType();
}
/**
* 修改渲染数据
*/
modify(data: Partial<TextboxProps>) {
for (const [key, value] of Object.entries(data)) {
// @ts-expect-error 无法推导
if (!isNil(value)) this.data[key] = value;
}
this.emits.update(this.data);
this.emit('update', this.data);
}
/**
* 设置显示的文本
* @param text 要显示的文本
*/
setText(text: string) {
this.emits.setText(text);
}
/**
* 显示文本框
*/
show() {
this.emits.show();
}
/**
* 隐藏文本框
*/
hide() {
this.emits.hide();
}
/**
* 获取文本框
* @param id 文本框id
*/
static get(id: string): TextboxStore | undefined {
return this.list.get(id);
}
/**
* 在当前作用域下生成文本框控制器
* @param id 文本框id
* @param props 文本框渲染数据
*/
static use(id: string, props: TextboxProps, emits: TextboxStoreEmits) {
const store = new TextboxStore(props, emits);
if (this.list.has(id)) {
logger.warn(42, id);
}
this.list.set(id, store);
onUnmounted(() => {
this.list.delete(id);
});
return store;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,169 @@
import { DefaultProps, ElementLocator, Font, texture } from '@motajs/render';
import { logger } from '@motajs/common';
import { computed, defineComponent, onUnmounted, ref } from 'vue';
import { SetupComponentOptions } from './types';
import { transitioned } from '../use';
import { hyper } from 'mutate-animate';
import { debounce } from 'lodash-es';
export interface TipProps extends DefaultProps {
loc: ElementLocator;
pad?: [number, number];
corner?: number;
id?: string;
}
export interface TipExpose {
/**
* 显示提示文本
* @param text 提示文字
* @param icon 显示的图标,不填则不显示
*/
drawTip(text: string, icon?: AllIds | AllNumbers): void;
}
const tipProps = {
props: ['loc', 'pad', 'corner', 'id']
} satisfies SetupComponentOptions<TipProps>;
let id = 0;
function getNextTipId() {
return `@default-tip-${id++}`;
}
export const Tip = defineComponent<TipProps>((props, { expose }) => {
const iconNum = ref<AllNumbers>(0);
const text = ref<string>('');
const textWidth = ref(0);
const font = new Font('normal');
const alpha = transitioned(0, 500, hyper('sin', 'in-out'))!;
const pad = computed(() => props.pad ?? [4, 4]);
const locHeight = computed(() => props.loc[3] ?? 200);
const hidden = computed(() => alpha.ref.value === 0);
const showIcon = computed(() => iconNum.value !== 0);
const iconSize = computed<[number, number]>(() => {
const renderable = texture.getRenderable(iconNum.value);
if (!renderable) return [1, 1];
const [, , width, height] = renderable.render[0];
return [width, height];
});
const iconLoc = computed<ElementLocator>(() => {
const [width, height] = iconSize.value;
const aspect = width / height;
const realHeight = locHeight.value - pad.value[1] * 2;
const realWidth = realHeight * aspect;
return [pad.value[0], pad.value[1], realWidth, realHeight];
});
const textLoc = computed<ElementLocator>(() => {
if (showIcon.value) {
const [, , width] = iconLoc.value;
const x = width! + pad.value[0] + pad.value[1];
return [x, locHeight.value / 2, void 0, void 0, 0, 0.5];
} else {
return [pad.value[0], locHeight.value / 2, void 0, void 0, 0, 0.5];
}
});
const containerLoc = computed<ElementLocator>(() => {
const [x = 0, y = 0, , height = 200] = props.loc;
const iconWidth = iconLoc.value[2] ?? 32;
if (showIcon.value) {
const width =
textWidth.value + iconWidth + pad.value[0] * 2 + pad.value[1];
return [x, y, width, height];
} else {
const width = textWidth.value + pad.value[0] * 2;
return [x, y, width, height];
}
});
const rectLoc = computed<ElementLocator>(() => {
const [, , width = 200, height = 200] = containerLoc.value;
return [1, 1, width - 2, height - 2];
});
const hide = debounce(() => {
alpha.set(0);
}, 3000);
const drawTip = (tipText: string, iconId: AllIds | AllNumbers = 0) => {
if (typeof iconId === 'string') {
const num = texture.idNumberMap[iconId];
iconNum.value = num;
} else {
iconNum.value = iconId;
}
text.value = core.replaceText(tipText);
alpha.set(0, 0);
alpha.set(1);
hide();
};
const onSetText = (_: string, width: number) => {
textWidth.value = width;
};
const ex: TipExpose = { drawTip };
TipStore.use(props.id ?? getNextTipId(), ex);
expose<TipExpose>(ex);
return () => (
<container
loc={containerLoc.value}
alpha={alpha.ref.value}
hidden={hidden.value}
noevent
>
<g-rectr
loc={rectLoc.value}
circle={[props.corner ?? 4]}
fill
fillStyle="rgba(40,40,40,0.8)"
/>
<icon
hidden={!showIcon.value}
icon={iconNum.value}
loc={iconLoc.value}
/>
<text
loc={textLoc.value}
text={text.value}
onSetText={onSetText}
font={font}
/>
</container>
);
}, tipProps);
export class TipStore {
static list: Map<string, TipStore> = new Map();
private constructor(private readonly data: TipExpose) {}
/**
* 显示提示文本
* @param text 提示文字
* @param icon 显示的图标,不填则不显示
*/
drawTip(text: string, icon: AllIds | AllNumbers = 0) {
this.data.drawTip(text, icon);
}
static get(id: string) {
return TipStore.list.get(id);
}
static use(id: string, data: TipExpose) {
const store = new TipStore(data);
if (this.list.has(id)) {
logger.warn(60, id);
}
this.list.set(id, store);
onUnmounted(() => {
this.list.delete(id);
});
return store;
}
}
@@ -0,0 +1,12 @@
import { ComponentOptions, EmitsOptions, SlotsType } from 'vue';
export type SetupComponentOptions<
Props extends Record<string, any>,
E extends EmitsOptions = {},
EE extends string = string,
S extends SlotsType = {}
> = Pick<ComponentOptions, 'name' | 'inheritAttrs'> & {
props?: (keyof Props)[];
emits?: E | EE[];
slots?: S;
};
@@ -0,0 +1,43 @@
import { MotaRenderer, createApp } from '@motajs/render';
import { defineComponent } from 'vue';
import { UIController } from '@motajs/system-ui';
import { mainSceneUI } from './ui/main';
import { MAIN_HEIGHT, MAIN_WIDTH } from './shared';
import { TextboxStore } from './components';
export function create() {
const main = new MotaRenderer();
main.size(MAIN_WIDTH, MAIN_HEIGHT);
const App = defineComponent(_props => {
const ui = new UIController('root-ui');
ui.open(mainSceneUI, {});
return () => (
<container width={MAIN_WIDTH} height={MAIN_HEIGHT}>
{ui.render()}
</container>
);
});
main.hide();
createApp(App).mount(main);
Mota.require('var', 'hook').on('reset', () => {
main.show();
});
Mota.require('var', 'hook').on('restart', () => {
main.hide();
});
console.log(main);
}
Mota.register('module', 'MainUI', {
TextboxStore
});
export * from './components';
export * from './ui';
export * from './use';
@@ -0,0 +1,10 @@
export const STATUS_BAR_WIDTH = 180;
export const STATUS_BAR_HEIGHT = 480;
export const ENABLE_RIGHT_STATUS_BAR = true;
export const MAP_WIDTH = 480;
export const MAP_HEIGHT = 480;
export const MAIN_WIDTH = 480 + 180 * 2;
export const MAIN_HEIGHT = 480;
@@ -0,0 +1,2 @@
export * from './main';
export * from './statusBar';
@@ -0,0 +1,238 @@
import { LayerShadowExtends } from '@/core/fx/shadow';
import {
ILayerGroupRenderExtends,
FloorDamageExtends,
LayerGroupAnimate,
FloorViewport,
ILayerRenderExtends,
HeroRenderer,
LayerDoorAnimate,
Props,
LayerGroup,
Font
} from '@motajs/render';
import { WeatherController } from '@/module/weather';
import { FloorChange } from '@/plugin/fallback';
import { LayerGroupFilter } from '@/plugin/fx/gameCanvas';
import { LayerGroupHalo } from '@/plugin/fx/halo';
import { FloorItemDetail } from '@/plugin/fx/itemDetail';
import { PopText } from '@/plugin/fx/pop';
import { LayerGroupPortal } from '@/plugin/fx/portal';
import { defineComponent, onMounted, reactive, ref } from 'vue';
import { Textbox, Tip } from '../components';
import { GameUI, UIController } from '@motajs/system-ui';
import {
MAIN_HEIGHT,
MAIN_WIDTH,
STATUS_BAR_HEIGHT,
STATUS_BAR_WIDTH
} from '../shared';
import {
ILeftHeroStatus,
IRightHeroStatus,
LeftStatusBar,
RightStatusBar
} from './statusBar';
import { onLoaded } from '../use';
import { ReplayingStatus } from './toolbar';
const MainScene = defineComponent(() => {
const layerGroupExtends: ILayerGroupRenderExtends[] = [
new FloorDamageExtends(),
new FloorItemDetail(),
new LayerGroupFilter(),
new LayerGroupPortal(),
new LayerGroupHalo(),
new LayerGroupAnimate(),
new FloorViewport()
];
const eventExtends: ILayerRenderExtends[] = [
new HeroRenderer(),
new LayerDoorAnimate(),
new LayerShadowExtends()
];
const mapDrawProps: Props<'container'> = {
width: core._PX_,
height: core._PY_
};
const mainTextboxProps: Props<typeof Textbox> = {
text: '',
hidden: true,
loc: [0, 330, 480, 150],
zIndex: 30,
fillStyle: '#fff',
titleFill: 'gold',
font: new Font('normal'),
titleFont: new Font('normal', 20, 'px', 700),
winskin: 'winskin2.png',
interval: 100,
lineHeight: 4,
width: 480
};
const map = ref<LayerGroup>();
const hideStatus = ref(false);
const weather = new WeatherController('main');
onMounted(() => {
weather.bind(map.value);
});
const leftStatus: ILeftHeroStatus = reactive({
hp: 0,
atk: 0,
def: 0,
mdef: 0,
money: 0,
exp: 0,
yellowKey: 0,
blueKey: 0,
redKey: 0,
floor: 'MT0',
lv: '',
regen: 0,
exAtk: 0,
magicDef: 0
});
const replayStatus: ReplayingStatus = reactive({
playing: false,
speed: 1,
played: 0,
total: 0
});
const rightStatus: IRightHeroStatus = reactive({
autoSkill: false,
skillName: '',
skillDesc: '',
jumpCount: 0,
springCount: 0,
floor: 'MT0',
replaying: false,
replayStatus,
night: 0
});
const { getHeroStatusOn } = Mota.requireAll('fn');
const updateStatus = () => {
if (!core.status || !core.status.hero || !core.status.floorId) return;
hideStatus.value = core.getFlag('hideStatusBar', false);
const hero = core.status.hero;
const floor = core.status.floorId;
leftStatus.atk = getHeroStatusOn('atk');
leftStatus.hp = getHeroStatusOn('hp');
leftStatus.def = getHeroStatusOn('def');
leftStatus.mdef = getHeroStatusOn('mdef');
leftStatus.money = getHeroStatusOn('money');
leftStatus.exp = core.getNextLvUpNeed() ?? 0;
leftStatus.yellowKey = core.itemCount('yellowKey');
leftStatus.blueKey = core.itemCount('blueKey');
leftStatus.redKey = core.itemCount('redKey');
leftStatus.floor = core.status.floorId;
leftStatus.lv = core.getLvName(hero.lv);
leftStatus.regen = getHeroStatusOn('hpmax');
leftStatus.exAtk = getHeroStatusOn('mana');
leftStatus.magicDef = getHeroStatusOn('magicDef');
const { HeroSkill, NightSpecial } = Mota.require('module', 'Mechanism');
rightStatus.autoSkill = HeroSkill.getAutoSkill();
rightStatus.skillName = HeroSkill.getSkillName();
rightStatus.skillDesc = HeroSkill.getSkillDesc();
rightStatus.night = NightSpecial.getNight(floor);
rightStatus.floor = floor;
rightStatus.replaying = core.isReplaying();
const { pausing, speed, toReplay, totalList } = core.status.replay;
replayStatus.playing = !pausing;
replayStatus.speed = speed;
replayStatus.played = totalList.length - toReplay.length;
replayStatus.total = totalList.length;
if (HeroSkill.learnedSkill(HeroSkill.Jump)) {
if (Mota.Plugin.require('skill_g').jumpIgnoreFloor.has(floor)) {
rightStatus.jumpCount = -2;
} else {
rightStatus.jumpCount = 3 - (flags[`jump_${floor}`] ?? 0);
}
} else {
rightStatus.jumpCount = -1;
}
if (core.hasFlag('spring')) {
rightStatus.springCount = 50 - (flags.springCount ?? 0);
} else {
rightStatus.springCount = -1;
}
};
const loaded = ref(false);
onLoaded(() => {
loaded.value = true;
});
Mota.require('var', 'hook').on('statusBarUpdate', updateStatus);
return () => (
<container id="main-scene" width={MAIN_WIDTH} height={MAIN_HEIGHT}>
{loaded.value && (
<LeftStatusBar
loc={[0, 0, STATUS_BAR_WIDTH, STATUS_BAR_HEIGHT]}
status={leftStatus}
hidden={hideStatus.value}
></LeftStatusBar>
)}
<g-line line={[180, 0, 180, 480]} lineWidth={1} />
<container id="map-draw" {...mapDrawProps} x={180} zIndex={10}>
<layer-group id="layer-main" ex={layerGroupExtends} ref={map}>
<layer layer="bg" zIndex={10}></layer>
<layer layer="bg2" zIndex={20}></layer>
<layer layer="event" zIndex={30} ex={eventExtends}></layer>
<layer layer="fg" zIndex={40}></layer>
<layer layer="fg2" zIndex={50}></layer>
<PopText id="pop-main" zIndex={80}></PopText>
</layer-group>
<Textbox id="main-textbox" {...mainTextboxProps}></Textbox>
<FloorChange id="floor-change" zIndex={50}></FloorChange>
<Tip
id="main-tip"
zIndex={80}
loc={[8, 8, 200, 32]}
pad={[12, 6]}
corner={16}
/>
</container>
<g-line line={[180 + 480, 0, 180 + 480, 480]} lineWidth={1} />
{loaded.value && (
<RightStatusBar
loc={[480 + 180, 0, STATUS_BAR_WIDTH, STATUS_BAR_HEIGHT]}
status={rightStatus}
hidden={hideStatus.value}
></RightStatusBar>
)}
<container
loc={[0, 0, MAIN_WIDTH, MAIN_HEIGHT]}
hidden={mainUIController.showBack.value}
>
{mainUIController.render()}
</container>
<g-rect
loc={[0, 0, MAIN_WIDTH, MAIN_HEIGHT]}
hidden={hideStatus.value}
zIndex={100}
stroke
noevent
></g-rect>
<g-line
line={[180, 0, 480 + 180, 0]}
hidden={!hideStatus.value}
zIndex={100}
/>
<g-line
line={[180, 480, 480 + 180, 480]}
hidden={!hideStatus.value}
zIndex={100}
/>
</container>
);
});
export const mainSceneUI = new GameUI('main-scene', MainScene);
export const mainUIController = new UIController('main-ui');
@@ -0,0 +1,579 @@
import { ElementLocator } from '@motajs/render';
import { GameUI, UIComponentProps } from '@motajs/system-ui';
import { defineComponent } from 'vue';
import {
ChoiceItem,
ChoiceKey,
Choices,
ChoicesProps,
getConfirm,
SetupComponentOptions,
waitbox
} from '../components';
import { mainUi } from '@motajs/legacy-ui';
import { gameKey } from '@motajs/system-action';
import { generateKeyboardEvent } from '@motajs/system-action';
import { getVitualKeyOnce } from '@motajs/legacy-ui';
import { getAllSavesData, getSaveData } from '@/module/utils';
export interface SettingsProps extends Partial<ChoicesProps>, UIComponentProps {
loc: ElementLocator;
}
const settingsProps = {
props: ['loc', 'controller', 'instance']
} satisfies SetupComponentOptions<SettingsProps>;
const enum MainChoice {
SystemSetting,
VirtualKey,
ViewMap,
/** @see {@link ReplaySettings} */
Replay,
/** @see {@link SyncSave} */
SyncSave,
/** @see {@link GameInfo} */
GameInfo,
Restart,
Back
}
export const MainSettings = defineComponent<SettingsProps>(props => {
const choices: ChoiceItem[] = [
[MainChoice.SystemSetting, '系统设置'],
[MainChoice.VirtualKey, '虚拟键盘'],
[MainChoice.ViewMap, '浏览地图'],
[MainChoice.Replay, '录像回放'],
[MainChoice.SyncSave, '同步存档'],
[MainChoice.GameInfo, '游戏信息'],
[MainChoice.Restart, '返回标题'],
[MainChoice.Back, '返回游戏']
];
const choose = (key: ChoiceKey) => {
switch (key) {
case MainChoice.SystemSetting: {
mainUi.open('settings');
break;
}
case MainChoice.VirtualKey: {
getVitualKeyOnce().then(value => {
gameKey.emitKey(
value.key,
value.assist,
'up',
generateKeyboardEvent(value.key, value.assist)
);
});
break;
}
case MainChoice.ViewMap: {
// todo
break;
}
case MainChoice.Replay: {
props.controller.open(ReplaySettingsUI, { loc: props.loc });
break;
}
case MainChoice.SyncSave: {
props.controller.open(SyncSaveUI, { loc: props.loc });
break;
}
case MainChoice.GameInfo: {
props.controller.open(GameInfoUI, { loc: props.loc });
break;
}
case MainChoice.Restart: {
props.controller.closeAll();
core.restart();
break;
}
case MainChoice.Back: {
props.controller.close(props.instance);
break;
}
}
};
return () => (
<Choices
loc={props.loc}
choices={choices}
width={240}
onChoose={choose}
/>
);
}, settingsProps);
const enum ReplayChoice {
Start,
StartFromSave,
ResumeReplay,
ReplayRest,
ChooseReplay,
Download,
Back
}
export const ReplaySettings = defineComponent<SettingsProps>(props => {
const choice: ChoiceItem[] = [
[ReplayChoice.Start, '从头回放录像'],
[ReplayChoice.StartFromSave, '从存档开始回放'],
[ReplayChoice.ResumeReplay, '接续播放剩余录像'],
[ReplayChoice.ReplayRest, '播放存档剩余录像'],
[ReplayChoice.ChooseReplay, '选择录像文件'],
[ReplayChoice.Download, '下载当前录像'],
[ReplayChoice.Back, '返回游戏']
];
const choose = (key: ChoiceKey) => {
switch (key) {
case ReplayChoice.Start: {
props.controller.closeAll();
core.ui.closePanel();
const route = core.status.route.slice();
const seed = core.getFlag<number>('__seed__');
core.startGame(core.status.hard, seed, route);
break;
}
case ReplayChoice.StartFromSave: {
// todo
break;
}
case ReplayChoice.ResumeReplay: {
// todo
break;
}
case ReplayChoice.ReplayRest: {
// todo
break;
}
case ReplayChoice.ChooseReplay: {
props.controller.closeAll();
core.chooseReplayFile();
break;
}
case ReplayChoice.Download: {
core.download(
core.firstData.name + '_' + core.formatDate2() + '.h5route',
// @ts-expect-error 暂时无法推导
LZString.compressToBase64(
JSON.stringify({
name: core.firstData.name,
hard: core.status.hard,
seed: core.getFlag('__seed__'),
route: core.encodeRoute(core.status.route)
})
)
);
break;
}
case ReplayChoice.Back: {
props.controller.close(props.instance);
break;
}
}
};
return () => (
<Choices
loc={props.loc}
choices={choice}
width={240}
onChoose={choose}
/>
);
}, settingsProps);
const enum GameInfoChoice {
Statistics,
Project,
Tower,
Help,
Download,
Back
}
export const GameInfo = defineComponent<SettingsProps>(props => {
const choices: ChoiceItem[] = [
[GameInfoChoice.Statistics, '数据统计'],
[GameInfoChoice.Project, '查看工程'],
[GameInfoChoice.Tower, '游戏主页'],
[GameInfoChoice.Help, '操作帮助'],
[GameInfoChoice.Download, '下载离线版本'],
[GameInfoChoice.Back, '返回主菜单']
];
const choose = async (key: ChoiceKey) => {
switch (key) {
case GameInfoChoice.Statistics: {
// todo
break;
}
case GameInfoChoice.Project: {
if (core.platform.isPC) window.open('editor.html', '_blank');
else {
const confirm = await getConfirm(
props.controller,
'即将离开本游戏,跳转至工程页面,确认跳转?',
props.loc,
240
);
if (confirm) {
window.location.href = 'editor-mobile.html';
}
}
break;
}
case GameInfoChoice.Tower: {
const name = core.firstData.name;
const href = `/tower/?name=${name}`;
if (core.platform.isPC) {
window.open(href, '_blank');
} else {
const confirm = await getConfirm(
props.controller,
'即将离开本游戏,跳转至评论页面,确认跳转?',
props.loc,
240
);
if (confirm) {
window.location.href = href;
}
}
break;
}
case GameInfoChoice.Download: {
const name = core.firstData.name;
const href = `/games/${name}/${name}.zip`;
if (core.platform.isPC) window.open(href);
else window.location.href = href;
break;
}
case GameInfoChoice.Help: {
// todo
break;
}
case GameInfoChoice.Back: {
props.controller.close(props.instance);
break;
}
}
};
return () => (
<Choices
loc={props.loc}
choices={choices}
width={240}
onChoose={choose}
/>
);
});
const enum SyncSaveChoice {
// ----- 主菜单
ToServer,
FromServer,
ToLocal,
FromLocal,
ClearLocal,
Back,
// ----- 子菜单
AllSaves,
NowSave
}
export const SyncSave = defineComponent<SettingsProps>(props => {
const choices: ChoiceItem[] = [
[SyncSaveChoice.ToServer, '同步存档至服务器'],
[SyncSaveChoice.FromServer, '从服务器加载存档'],
[SyncSaveChoice.ToLocal, '存档至本地文件'],
[SyncSaveChoice.FromLocal, '存本地文件读档'],
[SyncSaveChoice.ClearLocal, '清空本地存档'],
[SyncSaveChoice.Back, '返回上一级']
];
const choose = (key: ChoiceKey) => {
switch (key) {
case SyncSaveChoice.ToServer: {
props.controller.open(SyncSaveSelectUI, { loc: props.loc });
break;
}
case SyncSaveChoice.FromServer: {
// todo
break;
}
case SyncSaveChoice.ToLocal: {
props.controller.open(DownloadSaveSelectUI, { loc: props.loc });
break;
}
case SyncSaveChoice.FromLocal: {
// todo
break;
}
case SyncSaveChoice.ClearLocal: {
props.controller.open(ClearSaveSelectUI, { loc: props.loc });
break;
}
case SyncSaveChoice.Back: {
props.controller.close(props.instance);
break;
}
}
};
return () => (
<Choices
loc={props.loc}
width={240}
choices={choices}
onChoose={choose}
/>
);
});
export const SyncSaveSelect = defineComponent<SettingsProps>(props => {
const choices: ChoiceItem[] = [
[SyncSaveChoice.AllSaves, '同步全部存档'],
[SyncSaveChoice.NowSave, '同步当前存档'],
[SyncSaveChoice.Back, '返回上一级']
];
const choose = async (key: ChoiceKey) => {
switch (key) {
case SyncSaveChoice.AllSaves: {
core.playSound('confirm.opus');
const confirm = await getConfirm(
props.controller,
'你确定要同步全部存档么?这可能在存档较多的时候比较慢。',
props.loc,
240
);
if (confirm) {
core.syncSave('all');
}
break;
}
case SyncSaveChoice.NowSave: {
core.playSound('confirm.opus');
const confirm = await getConfirm(
props.controller,
'确定要同步当前存档吗?',
props.loc,
240
);
if (confirm) {
core.syncSave();
}
break;
}
case SyncSaveChoice.Back: {
props.controller.close(props.instance);
break;
}
}
};
return () => (
<Choices
loc={props.loc}
width={240}
choices={choices}
onChoose={choose}
/>
);
});
export const DownloadSaveSelect = defineComponent<SettingsProps>(props => {
const choices: ChoiceItem[] = [
[SyncSaveChoice.AllSaves, '下载全部存档'],
[SyncSaveChoice.NowSave, '下载当前存档'],
[SyncSaveChoice.Back, '返回上一级']
];
const choose = async (key: ChoiceKey) => {
switch (key) {
case SyncSaveChoice.AllSaves: {
const confirm = await getConfirm(
props.controller,
'确认要下载所有存档吗?',
props.loc,
240
);
if (confirm) {
const data = await waitbox(
props.controller,
props.loc,
240,
getAllSavesData(),
{ text: '请等待处理完毕' }
);
core.download(
`${core.firstData.name}_${core.formatDate2(new Date())}.h5save`,
data
);
}
break;
}
case SyncSaveChoice.NowSave: {
const confirm = await getConfirm(
props.controller,
'确认要下载当前存档吗?',
props.loc,
240
);
if (confirm) {
const data = await getSaveData(core.saves.saveIndex);
core.download(
`${core.firstData.name}_${core.formatDate2(new Date())}.h5save`,
data
);
}
break;
}
case SyncSaveChoice.Back: {
props.controller.close(props.instance);
break;
}
}
};
return () => (
<Choices
loc={props.loc}
width={240}
choices={choices}
onChoose={choose}
/>
);
});
export const ClearSaveSelect = defineComponent<SettingsProps>(props => {
const choices: ChoiceItem[] = [
[SyncSaveChoice.AllSaves, '清空全部塔存档'],
[SyncSaveChoice.NowSave, '清空当前塔存档'],
[SyncSaveChoice.Back, '返回上一级']
];
const choose = async (key: ChoiceKey) => {
switch (key) {
case SyncSaveChoice.AllSaves: {
const confirm = await getConfirm(
props.controller,
'你确定要清除【全部游戏】的所有本地存档?此行为不可逆!!!',
props.loc,
240
);
if (confirm) {
await waitbox(
props.controller,
props.loc,
240,
new Promise<void>(res => {
core.clearLocalForage(() => {
core.saves.ids = {};
core.saves.autosave.data = null;
core.saves.autosave.updated = false;
core.saves.autosave.now = 0;
// @ts-expect-error 沙比样板
core.saves.cache = {};
core.saves.saveIndex = 1;
core.saves.favorite = [];
core.saves.favoriteName = {};
// @ts-expect-error 沙比样板
core.control._updateFavoriteSaves();
core.removeLocalStorage('saveIndex');
res();
});
}),
{ text: '正在情况,请稍后...' }
);
await getConfirm(
props.controller,
'所有塔的存档已经全部清空',
props.loc,
240
);
}
break;
}
case SyncSaveChoice.NowSave: {
const confirm = await getConfirm(
props.controller,
'你确定要清除【当前游戏】的所有本地存档?此行为不可逆!!!',
props.loc,
240
);
if (confirm) {
await waitbox(
props.controller,
props.loc,
240,
new Promise<void>(res => {
Object.keys(core.saves.ids).forEach(function (v) {
core.removeLocalForage('save' + v);
});
core.removeLocalForage('autoSave', () => {
core.saves.ids = {};
core.saves.autosave.data = null;
core.saves.autosave.updated = false;
core.saves.autosave.now = 0;
core.ui.closePanel();
core.saves.saveIndex = 1;
core.saves.favorite = [];
core.saves.favoriteName = {};
// @ts-expect-error 沙比样板
core.control._updateFavoriteSaves();
core.removeLocalStorage('saveIndex');
res();
});
}),
{ text: '正在情况,请稍后...' }
);
await getConfirm(
props.controller,
'当前塔的存档已被清空',
props.loc,
240
);
}
break;
}
case SyncSaveChoice.Back: {
props.controller.close(props.instance);
break;
}
}
};
return () => (
<Choices
loc={props.loc}
width={240}
choices={choices}
onChoose={choose}
/>
);
});
/** @see {@link MainSettings} */
export const MainSettingsUI = new GameUI('main-settings', MainSettings);
/** @see {@link ReplaySettings} */
export const ReplaySettingsUI = new GameUI('replay-settings', ReplaySettings);
/** @see {@link GameInfo} */
export const GameInfoUI = new GameUI('game-info', GameInfo);
/** @see {@link SyncSave} */
export const SyncSaveUI = new GameUI('sync-save', SyncSave);
/** @see {@link SyncSaveSelect} */
export const SyncSaveSelectUI = new GameUI('sync-save-select', SyncSaveSelect);
/** @see {@link DownloadSaveSelect} */
export const DownloadSaveSelectUI = new GameUI(
'download-save-select',
DownloadSaveSelect
);
/** @see {@link ClearSaveSelect} */
export const ClearSaveSelectUI = new GameUI(
'clear-save-select',
ClearSaveSelect
);
@@ -0,0 +1,419 @@
import { GameUI, UIComponentProps } from '@motajs/system-ui';
import { computed, defineComponent, ref, watch } from 'vue';
import { SetupComponentOptions, TextContent } from '../components';
import {
DefaultProps,
ElementLocator,
Sprite,
Font,
MotaOffscreenCanvas2D
} from '@motajs/render';
import { transitionedColor } from '../use';
import { linear } from 'mutate-animate';
import { Scroll } from '../components/scroll';
import { getArea, MinimapDrawer } from '@motajs/legacy-ui';
import {
NumpadToolbar,
PlayingToolbar,
ReplayingStatus,
ReplayingToolbar
} from './toolbar';
export interface ILeftHeroStatus {
hp: number;
atk: number;
def: number;
mdef: number;
money: number;
exp: number;
yellowKey: number;
blueKey: number;
redKey: number;
floor: FloorIds;
lv: string;
/** 生命回复 */
regen: number;
/** 额外攻击 */
exAtk: number;
/** 魔法防御 */
magicDef: number;
}
interface StatusBarProps<T> extends DefaultProps, UIComponentProps {
loc: ElementLocator;
status: T;
hidden: boolean;
}
const statusBarProps = {
props: ['loc', 'status', 'hidden']
} satisfies SetupComponentOptions<StatusBarProps<unknown>>;
export const LeftStatusBar = defineComponent<StatusBarProps<ILeftHeroStatus>>(
p => {
const hpIcon = core.material.images.images['hp.png'];
const atkIcon = core.material.images.images['atk.png'];
const defIcon = core.material.images.images['def.png'];
const mdefIcon = core.material.images.images['IQ.png'];
const moneyIcon = core.material.images.images['money.png'];
const expIcon = core.material.images.images['exp.png'];
const s = p.status;
const f = core.formatBigNumber;
const floorName = computed(() => core.floors[s.floor]?.title ?? '');
const key = (num: number) => {
return num.toString().padStart(2, '0');
};
const font1 = new Font('normal', 18);
const font2 = new Font('normal', 18, 'px', 700);
const font3 = new Font('normal', 14, 'px', 700);
const iconLoc = (n: number): ElementLocator => {
return [16, 76 + 44 * n, 32, 32];
};
const textLoc = (n: number): ElementLocator => {
return [60, 92 + 44 * n, void 0, void 0, 0, 0.5];
};
const central = (y: number): ElementLocator => {
const width = p.loc[2] ?? 200;
return [width / 2, y, void 0, void 0, 0.5, 0.5];
};
const right = (y: number): ElementLocator => {
const width = p.loc[2] ?? 200;
return [width - 16, y, void 0, void 0, 1, 0.5];
};
const keyCount = 3;
const keyY = 92 + 44 * 6;
const keyLoc = (n: number): ElementLocator => {
const width = p.loc[2] ?? 200;
const per = width / (keyCount + 1);
return [per * (n + 1), keyY, void 0, void 0, 0.5, 0.5];
};
return () => {
return (
<container loc={p.loc} hidden={p.hidden}>
<text
text={floorName.value}
loc={central(24)}
font={font1}
cursor="pointer"
></text>
<text text={s.lv} loc={central(54)} font={font1}></text>
<image image={hpIcon} loc={iconLoc(0)}></image>
<text text={f(s.hp)} loc={textLoc(0)} font={font1}></text>
<text
text={`+${f(s.regen)}/t`}
loc={right(110)}
font={font3}
fillStyle="#a7ffa7"
></text>
<image image={atkIcon} loc={iconLoc(1)}></image>
<text text={f(s.atk)} loc={textLoc(1)} font={font1}></text>
<text
text={`+${f(s.exAtk)}`}
loc={right(154)}
font={font3}
fillStyle="#ffd3d3"
></text>
<image image={defIcon} loc={iconLoc(2)}></image>
<text text={f(s.def)} loc={textLoc(2)} font={font1}></text>
{s.magicDef > 0 && (
<text
text={`+${f(s.magicDef)}`}
loc={right(198)}
font={font3}
fillStyle="#b0bdff"
></text>
)}
<image image={mdefIcon} loc={iconLoc(3)}></image>
<text text={f(s.mdef)} loc={textLoc(3)} font={font1}></text>
<image image={moneyIcon} loc={iconLoc(4)}></image>
<text text={f(s.money)} loc={textLoc(4)} font={font1} />
<image image={expIcon} loc={iconLoc(5)}></image>
<text text={f(s.exp)} loc={textLoc(5)} font={font1}></text>
<text
text={key(s.yellowKey)}
loc={keyLoc(0)}
font={font2}
fillStyle="#fca"
></text>
<text
text={key(s.blueKey)}
loc={keyLoc(1)}
font={font2}
fillStyle="#aad"
></text>
<text
text={key(s.redKey)}
loc={keyLoc(2)}
font={font2}
fillStyle="#f88"
></text>
<text
text="技能树"
loc={central(396)}
font={font1}
cursor="pointer"
></text>
<text
text="查看技能"
loc={central(428)}
font={font1}
cursor="pointer"
></text>
</container>
);
};
},
statusBarProps
);
interface RightStatusBarMisc {
name: string;
value: string;
nameColor: string;
valueColor: string;
}
export interface IRightHeroStatus {
/** 自动切换技能 */
autoSkill: boolean;
/** 当前开启的技能 */
skillName: string;
/** 技能描述 */
skillDesc: string;
/** 跳跃剩余次数,-1 表示未开启,-2表示当前楼层不能跳 */
jumpCount: number;
/** 治愈之泉剩余次数,-1 表示未开启 */
springCount: number;
/** 当前楼层 */
floor: FloorIds;
/** 是否正在录像播放 */
replaying: boolean;
/** 录像播放状态 */
replayStatus: ReplayingStatus;
/** 极昼永夜 */
night: number;
}
export const RightStatusBar = defineComponent<StatusBarProps<IRightHeroStatus>>(
p => {
const font1 = new Font('normal', 18);
const font2 = new Font('normal', 16);
const minimap = ref<Sprite>();
const inNumpad = ref(false);
const onNumpad = () => {
inNumpad.value = !inNumpad.value;
};
const s = p.status;
const skill = computed(() =>
s.autoSkill ? '已开启自动切换' : s.skillName
);
const skillDesc = computed(() =>
s.autoSkill ? '自动切换技能时,会自动选择最优技能' : s.skillDesc
);
const skillColor = transitionedColor('#284', 200, linear())!;
watch(
() => s.autoSkill,
value => {
skillColor.set(value ? '#284' : '#824');
}
);
const miscData = computed<RightStatusBarMisc[]>(() => {
const data: RightStatusBarMisc[] = [];
if (s.jumpCount !== -1) {
const text =
s.jumpCount === -2 ? '不可跳跃' : s.jumpCount.toString();
data.push({
name: '跳跃剩余',
nameColor: '#fff',
value: text,
valueColor: '#fff'
});
}
if (s.springCount >= 0) {
data.push({
name: '治愈之泉',
nameColor: '#a7ffa7',
value: s.springCount.toString(),
valueColor: '#a7ffa7'
});
}
if (s.night !== 0) {
const text = s.night.toString();
data.push({
name: '极昼永夜',
nameColor: '#a3f8ff',
value: s.night > 0 ? '+' + text : text,
valueColor: s.night > 0 ? '#a7ffa7' : '#ffa7a7'
});
}
return data;
});
const central = (y: number): ElementLocator => {
const width = p.loc[2] ?? 200;
return [width / 2, y, void 0, void 0, 0.5, 0.5];
};
const middle = (x: number, y: number): ElementLocator => {
return [x, y, void 0, void 0, 0, 0.5];
};
const changeAutoSkill = () => {
const { HeroSkill } = Mota.require('module', 'Mechanism');
const auto = !s.autoSkill;
HeroSkill.setAutoSkill(auto);
core.status.route.push(`set:autoSkill:${auto}`);
core.updateStatusBar();
};
const area = getArea();
const minimapDrawer = new MinimapDrawer(
document.createElement('canvas')
);
minimapDrawer.noBorder = true;
minimapDrawer.scale = 4;
minimapDrawer.showInfo = true;
let linked = false;
const drawMinimap = (canvas: MotaOffscreenCanvas2D) => {
const ctx = canvas.ctx;
ctx.save();
ctx.scale(
1 / core.domStyle.scale / devicePixelRatio,
1 / core.domStyle.scale / devicePixelRatio
);
if (!linked) {
minimapDrawer.link(canvas.canvas);
linked = true;
}
if (minimapDrawer.nowFloor !== s.floor) {
minimapDrawer.drawedThumbnail = {};
} else {
minimapDrawer.drawToTarget();
ctx.restore();
return;
}
minimapDrawer.nowFloor = s.floor;
minimapDrawer.nowArea =
Object.keys(area).find(v =>
area[v].includes(core.status.floorId)
) ?? '';
minimapDrawer.locateMap(minimapDrawer.nowFloor);
minimapDrawer.drawMap();
ctx.restore();
};
watch(
() => s.floor,
() => {
minimap.value?.update();
}
);
return () => {
return (
<container loc={p.loc} hidden={p.hidden}>
<g-rectr
loc={[10, 10, 160, 24]}
circle={[6]}
fillStyle={skillColor.ref.value}
onClick={changeAutoSkill}
cursor="pointer"
></g-rectr>
<text
loc={central(22)}
text={skill.value}
font={font1}
onClick={changeAutoSkill}
cursor="pointer"
/>
<TextContent
loc={[10, 42, 160, 60]}
text={skillDesc.value}
font={new Font('normal', 14)}
width={160}
lineHeight={4}
></TextContent>
<g-line
line={[0, 107, 180, 107]}
strokeStyle="#888"
lineWidth={1}
zIndex={-20}
></g-line>
<Scroll loc={[0, 107, 180, 100]}>
{miscData.value
.map((v, i) => {
return [
<text
text={v.name}
loc={middle(10, 16 + i * 22)}
fillStyle={v.nameColor}
font={font2}
></text>,
<text
text={v.value}
loc={middle(100, 16 + i * 22)}
fillStyle={v.valueColor}
font={font2}
></text>
];
})
.flat()}
</Scroll>
<g-line
line={[0, 207, 180, 207]}
strokeStyle="#888"
lineWidth={1}
zIndex={-20}
></g-line>
<sprite
ref={minimap}
loc={[10, 207, 160, 160]}
render={drawMinimap}
></sprite>
<g-line
line={[0, 367, 180, 367]}
strokeStyle="#888"
lineWidth={1}
zIndex={-20}
></g-line>
{inNumpad.value ? (
<NumpadToolbar
loc={[0, 367, 180, 113]}
onNumpad={onNumpad}
/>
) : s.replaying ? (
<ReplayingToolbar
loc={[0, 367, 180, 113]}
status={s.replayStatus}
/>
) : (
<PlayingToolbar
loc={[0, 367, 180, 113]}
onNumpad={onNumpad}
/>
)}
</container>
);
};
},
statusBarProps
);
export const leftStatusBarUI = new GameUI('left-status-bar', LeftStatusBar);
export const rightStatusBarUI = new GameUI('right-status-bar', RightStatusBar);
@@ -0,0 +1,364 @@
import { DefaultProps, ElementLocator, Font } from '@motajs/render';
import { computed, defineComponent, ref } from 'vue';
import { SetupComponentOptions } from '../components';
import {
DanmakuIcon,
DoubleArrow,
NumpadIcon,
PauseIcon,
PlayIcon,
ReplayIcon,
RetweetIcon,
RollbackIcon,
StepForward,
ViewMapIcon
} from '../components/icons';
import {
generateBinary,
getVitualKeyOnce,
openDanmakuPoster
} from '@motajs/legacy-ui';
import { gameKey } from '@motajs/system-action';
import { generateKeyboardEvent } from '@motajs/system-action';
import { transitioned } from '../use';
import { linear } from 'mutate-animate';
import { KeyCode } from '@motajs/client-base';
import { Progress } from '../components/misc';
interface ToolbarProps extends DefaultProps {
loc?: ElementLocator;
}
type ToolbarEmits = {
numpad: () => void;
};
const toolbarProps = {
props: ['loc'],
emits: ['numpad']
} satisfies SetupComponentOptions<
ToolbarProps,
ToolbarEmits,
keyof ToolbarEmits
>;
const im = (col: number, row: number): ElementLocator => {
return [5 + 34 * col, 5 + 36 * row, 32, 32];
};
const ic = (col: number, row: number): ElementLocator => {
return [7 + 34 * col, 7 + 36 * row, 28, 28];
};
const ic2 = (col: number, row: number): ElementLocator => {
return [9 + 34 * col, 9 + 36 * row, 24, 24];
};
const middle = (col: number, row: number): ElementLocator => {
return [21 + 34 * col, 21 + 36 * row, void 0, void 0, 0.5, 0.5];
};
const middle2 = (
col: number,
row: number,
width: number,
height: number
): ElementLocator => {
return [21 + 34 * col, 21 + 36 * row, width, height, 0.5, 0.5];
};
export const PlayingToolbar = defineComponent<
ToolbarProps,
ToolbarEmits,
keyof ToolbarEmits
>((props, { emit }) => {
const bookIcon = core.statusBar.icons.book;
const flyIcon = core.statusBar.icons.fly;
const toolIcon = core.statusBar.icons.toolbox;
const equipIcon = core.statusBar.icons.equipbox;
const keyIcon = core.statusBar.icons.keyboard;
const shopIcon = core.statusBar.icons.shop;
const saveIcon = core.statusBar.icons.save;
const loadIcon = core.statusBar.icons.load;
const setIcon = core.statusBar.icons.settings;
const iconFont = new Font('Verdana', 12);
const book = () => core.openBook(true);
const tool = () => core.openEquipbox(true);
const fly = () => core.useFly(true);
const save = () => core.save(true);
const load = () => core.load(true);
const equip = () => core.openEquipbox(true);
const shop = () => core.openQuickShop(true);
const key = () => {
getVitualKeyOnce().then(value => {
gameKey.emitKey(
value.key,
value.assist,
'up',
generateKeyboardEvent(value.key, value.assist)
);
});
};
const undo = () => core.doSL('autoSave', 'load');
const redo = () => core.doSL('autoSave', 'reload');
const numpad = () => emit('numpad');
const view = () => {
if (core.isPlaying() && !core.isMoving() && !core.status.lockControl) {
core.ui._drawViewMaps();
}
};
const danmaku = () => requestAnimationFrame(openDanmakuPoster);
const replay = () => core.ui._drawReplay();
const settings = () => core.openSettings(true);
return () => (
<container loc={props.loc} cursor="pointer">
<image image={bookIcon} loc={im(0, 0)} noanti onClick={book} />
<image image={toolIcon} loc={im(1, 0)} noanti onClick={tool} />
<image image={flyIcon} loc={im(2, 0)} noanti onClick={fly} />
<image image={saveIcon} loc={im(3, 0)} noanti onClick={save} />
<image image={loadIcon} loc={im(4, 0)} noanti onClick={load} />
<image image={equipIcon} loc={im(0, 1)} noanti onClick={equip} />
<image image={shopIcon} loc={im(1, 1)} noanti onClick={shop} />
<image image={keyIcon} loc={im(2, 1)} noanti onClick={key} />
<RollbackIcon loc={ic(3, 1)} strokeStyle="#eee" onClick={undo} />
<RetweetIcon loc={ic(4, 1)} strokeStyle="#eee" onClick={redo} />
<NumpadIcon loc={ic(0, 2)} strokeStyle="#eee" onClick={numpad} />
<ViewMapIcon loc={ic(1, 2)} strokeStyle="#eee" onClick={view} />
<DanmakuIcon loc={ic(2, 2)} strokeStyle="#eee" onClick={danmaku} />
<ReplayIcon loc={ic(3, 2)} strokeStyle="#eee" onClick={replay} />
<text text="R" loc={middle(3, 2)} font={iconFont} noevent />
<image image={setIcon} loc={im(4, 2)} noanti onClick={settings} />
</container>
);
}, toolbarProps);
export interface ReplayingStatus {
/** 是否正在播放 */
playing: boolean;
/** 录像播放速度 */
speed: number;
/** 已播放的长度 */
played: number;
/** 总长度 */
total: number;
}
export interface ReplayingProps extends ToolbarProps {
/** 录像播放状态 */
status: ReplayingStatus;
}
const replayingProps = {
props: ['status', 'loc']
} satisfies SetupComponentOptions<ReplayingProps>;
export const ReplayingToolbar = defineComponent<ReplayingProps>(props => {
const status = props.status;
const bookIcon = core.statusBar.icons.book;
const saveIcon = core.statusBar.icons.save;
const font1 = new Font('normal', 16);
const font2 = new Font('Verdana', 12);
const speedText = computed(() => `${status.speed}速`);
const progress = computed(() => status.played / status.total);
const progressText1 = computed(() => `${status.played}/${status.total}`);
const progressText2 = computed(
() => `${(progress.value * 100).toFixed(2)}%`
);
const play = () => core.resumeReplay();
const pause = () => core.pauseReplay();
const stop = () => core.stopReplay(true);
const speedDown = () => core.speedDownReplay();
const speedUp = () => core.speedUpReplay();
const book = () => core.openBook(true);
const save = () => core.save(true);
const view = () => {
if (core.isPlaying() && !core.isMoving() && !core.status.lockControl) {
core.ui._drawViewMaps();
}
};
const rewind = () => core.rewindReplay();
const step = () => core.stepReplay();
return () => {
return (
<container loc={props.loc} cursor="pointer">
{status.playing ? (
<PauseIcon loc={ic(0, 0)} onClick={pause} />
) : (
<PlayIcon loc={ic(0, 0)} onClick={play} />
)}
<g-rectr loc={[47, 13, 16, 16]} circle={[2]} onClick={stop} />
<DoubleArrow
loc={middle2(2, 0, 28, 28)}
scale={[-1, 1]}
onClick={speedDown}
/>
<text text={speedText.value} loc={middle(3, 0)} font={font1} />
<DoubleArrow loc={ic(4, 0)} onClick={speedUp} />
<image image={bookIcon} loc={im(0, 1)} noanti onClick={book} />
<image image={saveIcon} loc={im(1, 1)} noanti onClick={save} />
<ViewMapIcon loc={ic(2, 1)} onClick={view} />
<StepForward
loc={middle2(3, 1, 28, 28)}
scale={[-1, 1]}
onClick={rewind}
/>
<StepForward loc={ic(4, 1)} onClick={step} />
<text
text={progressText1.value}
loc={[12, 98, void 0, void 0, 0, 1]}
font={font2}
/>
<text
text={progressText2.value}
loc={[168, 98, void 0, void 0, 1, 1]}
font={font2}
/>
<Progress
loc={[12, 101, 156, 4]}
progress={progress.value}
success="lightgreen"
/>
</container>
);
};
}, replayingProps);
export const NumpadToolbar = defineComponent<
ToolbarProps,
ToolbarEmits,
keyof ToolbarEmits
>((props, { emit }) => {
const numpad = () => emit('numpad');
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
const ctrlEnabled = ref(false);
const shiftEnabled = ref(false);
const altEnabled = ref(false);
const ctrlAlpha = transitioned(0, 100, linear())!;
const shiftAlpha = transitioned(0, 100, linear())!;
const altAlpha = transitioned(0, 100, linear())!;
const ctrlColor = computed(
() => `rgba(221,221,221,${ctrlAlpha.ref.value})`
);
const ctrlTextColor = computed(() => {
const rgb = Math.floor(255 - ctrlAlpha.ref.value * 255);
return `rgba(${rgb},${rgb},${rgb},1)`;
});
const shiftColor = computed(
() => `rgba(221,221,221,${shiftAlpha.ref.value})`
);
const shiftTextColor = computed(() => {
const rgb = Math.floor(255 - shiftAlpha.ref.value * 255);
return `rgba(${rgb},${rgb},${rgb},1)`;
});
const altColor = computed(() => `rgba(221,221,221,${altAlpha.ref.value})`);
const altTextColor = computed(() => {
const rgb = Math.floor(255 - altAlpha.ref.value * 255);
return `rgba(${rgb},${rgb},${rgb},1)`;
});
const clickCtrl = () => {
ctrlEnabled.value = !ctrlEnabled.value;
ctrlAlpha.set(ctrlEnabled.value ? 1 : 0);
};
const clickShift = () => {
shiftEnabled.value = !shiftEnabled.value;
shiftAlpha.set(shiftEnabled.value ? 1 : 0);
};
const clickAlt = () => {
altEnabled.value = !altEnabled.value;
altAlpha.set(altEnabled.value ? 1 : 0);
};
const clickNum = (num: number) => {
const bin = generateBinary([
ctrlEnabled.value,
shiftEnabled.value,
altEnabled.value
]);
const code = (KeyCode.Digit0 + num) as KeyCode;
gameKey.emitKey(code, bin, 'up', generateKeyboardEvent(code, bin));
};
return () => (
<container loc={props.loc} cursor="pointer">
<container loc={[0, 0, 180, 81]}>
{nums
.map((v, i) => {
const col = i % 5;
const row = Math.floor(i / 5);
return [
<g-rectr
loc={ic2(col, row)}
circle={[4]}
stroke
onClick={() => clickNum(v)}
/>,
<text
text={v.toString()}
loc={middle(col, row)}
noevent
/>
];
})
.flat()}
</container>
<g-rectr
loc={[41, 81, 36, 24]}
circle={[4]}
stroke
fill
fillStyle={ctrlColor.value}
onClick={clickCtrl}
></g-rectr>
<text
text="Ctrl"
loc={[59, 93, void 0, void 0, 0.5, 0.5]}
fillStyle={ctrlTextColor.value}
noevent
/>
<g-rectr
loc={[86, 81, 44, 24]}
circle={[4]}
stroke
fill
fillStyle={shiftColor.value}
onClick={clickShift}
></g-rectr>
<text
text="Shift"
loc={[108, 93, void 0, void 0, 0.5, 0.5]}
fillStyle={shiftTextColor.value}
noevent
/>
<g-rectr
loc={[139, 81, 30, 24]}
circle={[4]}
stroke
fill
fillStyle={altColor.value}
onClick={clickAlt}
></g-rectr>
<text
text="Alt"
loc={[154, 93, void 0, void 0, 0.5, 0.5]}
fillStyle={altTextColor.value}
noevent
/>
<NumpadIcon loc={ic(0, 2)} strokeStyle="gold" onClick={numpad} />
</container>
);
}, toolbarProps);
@@ -0,0 +1,293 @@
import { TimingFn, Transition } from 'mutate-animate';
import {
ComponentInternalInstance,
getCurrentInstance,
onMounted,
onUnmounted,
ref,
Ref
} from 'vue';
export const enum Orientation {
/** 横屏 */
Landscape,
/** 竖屏 */
Portrait
}
export type OrientationHook = (
orientation: Orientation,
width: number,
height: number
) => void;
let nowOrientation = Orientation.Landscape;
const orientationHooks = new Set<OrientationHook>();
function checkOrientation() {
const before = nowOrientation;
// 只要宽度大于高度,那么就视为横屏
if (window.innerWidth >= window.innerHeight) {
nowOrientation = Orientation.Landscape;
} else {
nowOrientation = Orientation.Portrait;
}
if (nowOrientation === before) return;
orientationHooks.forEach(v => {
v(nowOrientation, window.innerWidth, window.innerHeight);
});
}
window.addEventListener('resize', checkOrientation);
/**
* 当屏幕方向改变时执行函数
* @param hook 当屏幕方向改变时执行的函数
*/
export function onOrientationChange(hook: OrientationHook) {
onMounted(() => {
orientationHooks.add(hook);
hook(nowOrientation, window.innerWidth, window.innerHeight);
});
onUnmounted(() => {
orientationHooks.delete(hook);
});
}
/**
* 当游戏加载完成时执行函数,如果调用此函数时游戏已经加载,那么会立刻调用传入的钩子函数
* @param hook 当游戏加载完成时执行的函数
*/
export function onLoaded(hook: () => void) {
const loading = Mota.require('var', 'loading');
if (!loading.loaded) {
loading.once('loaded', hook);
} else {
hook();
}
}
export interface ITransitionedController<T> {
readonly ref: Ref<T>;
readonly value: T;
set(value: T, time?: number): void;
}
class RenderTransition implements ITransitionedController<number> {
private static key: number = 0;
private readonly key: string = `$${RenderTransition.key++}`;
public readonly ref: Ref<number>;
set value(v: number) {
this.transition.transition(this.key, v);
}
get value() {
return this.transition.value[this.key];
}
constructor(
value: number,
public readonly transition: Transition,
public readonly time: number,
public readonly curve: TimingFn
) {
this.ref = ref(value);
transition.value[this.key] = value;
transition.ticker.add(() => {
this.ref.value = transition.value[this.key];
});
}
set(value: number, time: number = this.time): void {
this.transition.time(time).mode(this.curve).transition(this.key, value);
}
}
type ColorRGBA = [number, number, number, number];
class RenderColorTransition implements ITransitionedController<string> {
private static key: number = 0;
private readonly keyR: string = `$colorR${RenderColorTransition.key++}`;
private readonly keyG: string = `$colorG${RenderColorTransition.key++}`;
private readonly keyB: string = `$colorB${RenderColorTransition.key++}`;
private readonly keyA: string = `$colorA${RenderColorTransition.key++}`;
public readonly ref: Ref<string>;
set value(v: string) {
this.set(v);
}
get value() {
return this.encodeColor();
}
constructor(
value: string,
public readonly transition: Transition,
public readonly time: number,
public readonly curve: TimingFn
) {
this.ref = ref(value);
const [r, g, b, a] = this.decodeColor(value);
transition.value[this.keyR] = r;
transition.value[this.keyG] = g;
transition.value[this.keyB] = b;
transition.value[this.keyA] = a;
transition.ticker.add(() => {
this.ref.value = this.encodeColor();
});
}
set(value: string, time: number = this.time): void {
this.transitionColor(this.decodeColor(value), time);
}
private transitionColor([r, g, b, a]: ColorRGBA, time: number) {
this.transition
.mode(this.curve)
.time(time)
.transition(this.keyR, r)
.transition(this.keyG, g)
.transition(this.keyB, b)
.transition(this.keyA, a);
}
private decodeColor(color: string): ColorRGBA {
if (color.startsWith('#')) {
return this.decodeHash(color);
} else if (color.startsWith('rgba')) {
return this.decodeRGBA(color);
} else if (color.startsWith('rgb')) {
return this.decodeRGB(color);
}
return [0, 0, 0, 1];
}
private decodeHash(color: string): ColorRGBA {
switch (color.length) {
case 4:
return [
Number(`0x${color.slice(1, 2).repeat(2)}`),
Number(`0x${color.slice(2, 3).repeat(2)}`),
Number(`0x${color.slice(3, 4).repeat(2)}`),
1
];
case 5:
return [
Number(`0x${color.slice(1, 2).repeat(2)}`),
Number(`0x${color.slice(2, 3).repeat(2)}`),
Number(`0x${color.slice(3, 4).repeat(2)}`),
Number(`0x${color.slice(4, 5).repeat(2)}`)
];
case 7:
return [
Number(`0x${color.slice(1, 3)}`),
Number(`0x${color.slice(3, 5)}`),
Number(`0x${color.slice(5, 7)}`),
1
];
case 9:
return [
Number(`0x${color.slice(1, 3)}`),
Number(`0x${color.slice(3, 5)}`),
Number(`0x${color.slice(5, 7)}`),
Number(`0x${color.slice(7, 9)}`)
];
}
return [0, 0, 0, 0];
}
private decodeRGBA(color: string): ColorRGBA {
const data = color.slice(color.indexOf('(') + 1, color.indexOf(')'));
const [r, g, b, a] = data.split(',');
return [Number(r), Number(g), Number(b), Number(a)];
}
private decodeRGB(color: string): ColorRGBA {
const data = color.slice(color.indexOf('(') + 1, color.indexOf(')'));
const [r, g, b] = data.split(',');
return [Number(r), Number(g), Number(b), 1];
}
private encodeColor() {
const r = this.transition.value[this.keyR];
const g = this.transition.value[this.keyG];
const b = this.transition.value[this.keyB];
const a = this.transition.value[this.keyA];
return `rgba(${r},${g},${b},${a})`;
}
}
const transitionMap = new Map<ComponentInternalInstance, Transition>();
function checkTransition() {
const instance = getCurrentInstance();
if (!instance) return null;
if (instance.isUnmounted) {
const tran = transitionMap.get(instance);
tran?.ticker.destroy();
transitionMap.delete(instance);
return null;
}
if (!transitionMap.has(instance)) {
const tran = new Transition();
transitionMap.set(instance, tran);
onUnmounted(() => {
transitionMap.delete(instance);
tran.ticker.destroy();
});
}
const tran = transitionMap.get(instance);
if (!tran) return null;
return tran;
}
/**
* 创建一个渐变数值,当数值发生变化时会缓慢变化值目标值而非突变,只可以用于组件内,不可用于组件外
* ```tsx
* const value = transitioned(10, 300, linear()); // 创建渐变,初始值为 10,渐变时长 300ms,线性变化
* value.set(100); // 渐变至 100
*
* // 直接在元素上使用
* <text text={value.ref.value} />
* ```
* @param value 初始值
* @param time 渐变时长
* @param curve 渐变的速率曲线
*/
export function transitioned(
value: number,
time: number,
curve: TimingFn
): ITransitionedController<number> | null {
const tran = checkTransition();
if (!tran) return null;
return new RenderTransition(value, tran, time, curve);
}
/**
* 创建一个渐变颜色,当颜色发生变化时会缓慢变化值目标值而非突变,自动判断颜色字符串类型,只可用于组件内,不可用于组件外
* ```tsx
* // 创建渐变,初始值为 '#fff'(白色),渐变时长 300ms,线性变化
* const color = transitionedColor('#fff', 300, linear());
* color.set('rgba(129, 30, 40, 0.7)'); // 渐变至这个颜色
*
* // 直接在元素上使用
* <text text='文本' fillStyle={color.ref.value} />
* ```
* @param color 颜色的初始值
* @param time 渐变时长
* @param curve 渐变的速率曲线
*/
export function transitionedColor(
color: string,
time: number,
curve: TimingFn
): ITransitionedController<string> | null {
const tran = checkTransition();
if (!tran) return null;
return new RenderColorTransition(color, tran, time, curve);
}