feat: 사령부의 턴 선택기에 고급 모드 적용 (#212)

- 사령부 턴 페이지를 vue3 setup 형태로 변경
- 턴 조작기 함수 중 공용 함수 분리
- 사령부 턴 조작기 코드 범위를 다시 조정
- 사령부 일반 모드, 고급 모드 이원화
- 사령부에서 다른 수뇌의 턴 '복사하기' 제공

Co-authored-by: Hide_D <hided62@gmail.com>
Reviewed-on: https://storage.hided.net/gitea/devsam/core/pulls/212
Co-authored-by: hide_d <hided62@gmail.com>
Co-committed-by: hide_d <hided62@gmail.com>
This commit is contained in:
2022-03-26 23:11:58 +09:00
parent 585667dfe8
commit ab9bdf3822
12 changed files with 1677 additions and 1212 deletions
@@ -0,0 +1,76 @@
<?php
namespace sammo\API\NationCommand;
use sammo\Session;
use DateTimeInterface;
use sammo\GameConst;
use sammo\Util;
use sammo\Validator;
use function sammo\setNationCommand;
class ReserveBulkCommand extends \sammo\BaseAPI
{
public function validateArgs(): ?string
{
foreach ($this->args as $idx => $turn) {
$v = new Validator($turn);
$v->rule('required', [
'action',
'turnList'
])
->rule('lengthMin', 'action', 1)
->rule('integerArray', 'turnList');
if (!$v->validate()) {
return "{$idx}:{$v->errorStr()}";
}
}
return null;
}
public function getRequiredSessionMode(): int
{
return static::REQ_GAME_LOGIN | static::REQ_READ_ONLY;
}
public function launch(Session $session, ?DateTimeInterface $modifiedSince, ?string $reqEtag)
{
$briefList = [];
foreach ($this->args as $idx => $turn) {
$action = $turn['action'];
$turnList = $turn['turnList'];
$arg = $turn['arg'] ?? [];
if (!$turnList) {
return "{$idx}: 턴이 입력되지 않았습니다";
}
if (!in_array($action, Util::array_flatten(GameConst::$availableChiefCommand))) {
return "{$idx}: 사용할 수 없는 커맨드입니다.";
}
if (!is_array($arg)) {
return "{$idx}: 올바른 arg 형태가 아닙니다.";
}
$partialResult = setNationCommand($session->generalID, $turnList, $action, $arg);
if(!$partialResult['result']){
return [
'result' => false,
'briefList' => $briefList,
'errorIdx' => $idx,
'reason' => $partialResult['reason']
];
}
$briefList[$idx] = $partialResult['brief'];
}
return [
'result' => true,
'briefList' => $briefList,
'reason' => 'success'
];
}
}
+9 -5
View File
@@ -31,11 +31,16 @@ $modcolor2: color.adjust($nbase2color, $lightness: -5%);
line-height: 30px; line-height: 30px;
} }
.time_pad.inverted{
background-color: gray;
color: white;
}
.turn_pad { .turn_pad {
line-height: 30px; line-height: 30px;
} }
.row:nth-child(odd) .turn_pad { .row:nth-of-type(odd) .turn_pad {
background-color: $modcolor2; background-color: $modcolor2;
} }
} }
@@ -83,7 +88,7 @@ $modcolor2: color.adjust($nbase2color, $lightness: -5%);
} }
.commandBox .controlPad { .commandBox .controlPad {
.turn_pad:nth-child(2n) { .turn_pad:nth-of-type(even) {
background-color: $modcolor2; background-color: $modcolor2;
} }
} }
@@ -109,7 +114,6 @@ $modcolor2: color.adjust($nbase2color, $lightness: -5%);
width: 500px; width: 500px;
height: 460px; height: 460px;
margin: auto; margin: auto;
overflow: hidden;
} }
#mainTable { #mainTable {
@@ -131,7 +135,7 @@ $modcolor2: color.adjust($nbase2color, $lightness: -5%);
.commandBox .controlPad { .commandBox .controlPad {
margin-top: 10px; margin-top: 10px;
.turn_pad:nth-child(even) { .turn_pad:nth-of-type(even) {
background-color: $modcolor2; background-color: $modcolor2;
} }
} }
@@ -145,7 +149,7 @@ $modcolor2: color.adjust($nbase2color, $lightness: -5%);
overflow: hidden; overflow: hidden;
.turn_pad:nth-child(even) { .turn_pad:nth-of-type(even) {
background-color: $modcolor2; background-color: $modcolor2;
} }
} }
+151 -69
View File
@@ -1,88 +1,170 @@
<template> <template>
<div :class="['subRows', 'chiefCommand']" :style="style"> <div style="position:relative">
<div class="bg1 center row gx-0" style="font-size: 1.2em"> <DragSelect
<div class="col-5 align-self-center text-end"> :class="['subRows', 'chiefCommand']"
{{ officer ? `${officer.officerLevelText} : ` : "" }} :style="style"
:disabled="!props.officer || !isEditMode"
attribute="turnIdx"
@dragStart="dragStart()"
@dragDone="dragDone(...$event)"
v-slot="{ selected }"
>
<div class="bg1 center row gx-0" style="font-size: 1.2em">
<div
class="col-5 align-self-center text-end"
>{{ officer ? `${officer.officerLevelText} : ` : "" }}</div>
<div
class="col-7 align-self-center"
:style="{
color: getNpcColor(officer?.npcType ?? 0),
}"
>{{ officer?.name }}</div>
</div> </div>
<div <div :turnIdx="vidx" class="row c-bg2 gx-0" v-for="vidx in maxTurn" :key="vidx">
class="col-7 align-self-center" <div
:style="{ :class="['col-2', 'time_pad', 'f_tnum', ((isDragToggle || isCopyButtonShown) && selected.has(vidx.toString())) ? 'inverted' : undefined]"
color: getNpcColor(officer?.npcType ?? 0), >{{ turnTimes[vidx - 1] }}</div>
}" <div class="center" v-if="!officer || (!officer.turn) || !(vidx - 1 in officer.turn)"></div>
> <div
{{ officer?.name }} v-else
class="tableCell align-self-center col-10 center turn_pad"
:style="{
fontSize:
mb_strwidth(officer.turn[vidx - 1].brief) > 28
? `${28 / mb_strwidth(officer.turn[vidx - 1].brief)}em`
: undefined,
}"
>{{ officer.turn[vidx - 1].brief }}</div>
</div> </div>
</div> </DragSelect>
<div class="row c-bg2 gx-0" v-for="vidx in maxTurn" :key="vidx"> <BButton
<div class="col-2 time_pad f_tnum"> ref="btnCopy"
{{ turnTimes[vidx - 1] }} :style="{
</div> position: 'absolute',
<div display: isCopyButtonShown ? 'block' : 'none',
class="center" top: `${btnPos * 30 + 25}px`,
v-if="!officer || (!officer.turn) || !(vidx - 1 in officer.turn)" right: '10px',
></div> }"
<div @blur="isCopyButtonShown = false"
v-else @click="tryCopy()"
class="tableCell align-self-center col-10 center turn_pad" >복사하기</BButton>
:style="{
fontSize:
mb_strwidth(officer.turn[vidx - 1].brief) > 28
? `${28 / mb_strwidth(officer.turn[vidx - 1].brief)}em`
: undefined,
}"
>
{{ officer.turn[vidx - 1].brief }}
</div>
</div>
</div> </div>
</template> </template>
<script lang="ts"> <script setup lang="ts">
import { getNpcColor } from "@/common_legacy"; import { getNpcColor } from "@/common_legacy";
import { ChiefResponse } from "@/defs"; import type { ChiefResponse } from "@/defs";
import { formatTime } from "@/util/formatTime"; import { formatTime } from "@/util/formatTime";
import { mb_strwidth } from "@/util/mb_strwidth"; import { mb_strwidth } from "@/util/mb_strwidth";
import { parseTime } from "@/util/parseTime"; import { parseTime } from "@/util/parseTime";
import type { StoredActionsHelper } from "@/util/StoredActionsHelper";
import addMinutes from "date-fns/esm/addMinutes/index"; import addMinutes from "date-fns/esm/addMinutes/index";
import { range } from "lodash"; import { range } from "lodash";
import { defineComponent, PropType } from "vue"; import { defineProps, inject, onMounted, ref, type PropType } from "vue";
import VueTypes from "vue-types"; import VueTypes from "vue-types";
import DragSelect from "@/components/DragSelect.vue";
import { BButton } from "bootstrap-vue-3";
import { QueryActionHelper } from "@/util/QueryActionHelper";
export default defineComponent({
props: { const props = defineProps({
style: VueTypes.object.isRequired, style: VueTypes.object.isRequired,
officer: { officer: {
type: Object as PropType<ChiefResponse["chiefList"][0]>, type: Object as PropType<ChiefResponse["chiefList"][0]>,
},
turnTerm: VueTypes.integer.isRequired,
maxTurn: VueTypes.integer.isRequired,
},
methods: {
getNpcColor,
mb_strwidth,
}, },
turnTerm: VueTypes.integer.isRequired,
maxTurn: VueTypes.integer.isRequired,
})
data() { const btnPos = ref(0);
const turnTimes: string[] = []; const btnCopy = ref<InstanceType<typeof BButton> | null>(null);
if (!this.officer || !this.officer.turnTime) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for (const _ of range(this.maxTurn)) {
turnTimes.push("\xa0");
}
} else {
const baseTurnTime = parseTime(this.officer.turnTime);
for (const idx of range(this.officer.turn.length)) {
turnTimes.push(
formatTime(
addMinutes(baseTurnTime, idx * this.turnTerm),
this.turnTerm >= 5 ? "HH:mm" : "mm:ss"
)
);
}
}
const storedActionsHelper = inject<StoredActionsHelper>('storedNationActionsHelper');
const isEditMode = (storedActionsHelper?.isEditMode) ?? ref(false);
const isDragToggle = ref(false);
const isCopyButtonShown = ref(false);
const queryActionHelper = new QueryActionHelper(props.maxTurn);
const selectedTurnList = queryActionHelper.selectedTurnList;
onMounted(() => {
if (props.officer === undefined) {
return;
}
queryActionHelper.reservedCommandList.value = props.officer.turn.map(rawTurn => {
return { return {
turnTimes, ...rawTurn,
}; time: '',
}, }
});
console.log(queryActionHelper.reservedCommandList.value);
}); });
function dragStart() {
isDragToggle.value = true;
}
function eqSet<T>(as: Set<T>, bs: Set<T>) {
if (as.size !== bs.size) return false;
for (var a of as) if (!bs.has(a)) return false;
return true;
}
function dragDone(...rawSelectedTurn: string[]) {
if (rawSelectedTurn.length === 0) {
return;
}
const newSelectedTurnList = new Set<number>();
let maxPos = -1;
for (const rawIdx of rawSelectedTurn) {
const idx = parseInt(rawIdx) - 1;
newSelectedTurnList.add(idx);
maxPos = Math.max(maxPos, idx);
}
btnPos.value = maxPos;
isDragToggle.value = false;
if (newSelectedTurnList.size == 1 && eqSet(selectedTurnList.value, newSelectedTurnList)) {
isCopyButtonShown.value = false;
return;
}
selectedTurnList.value = newSelectedTurnList;
isCopyButtonShown.value = true;
setTimeout(() => {
(btnCopy.value?.$el as HTMLButtonElement).focus();
}, 0);
}
function tryCopy() {
const actions = queryActionHelper.extractQueryActions();
isCopyButtonShown.value = false;
if (!storedActionsHelper) {
return;
}
storedActionsHelper.clipboard.value = [...actions];
}
const turnTimes = ref<string[]>([]);
if (!props.officer || !props.officer.turnTime) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for (const _ of range(props.maxTurn)) {
turnTimes.value.push("\xa0");
}
} else {
const baseTurnTime = parseTime(props.officer.turnTime);
for (const idx of range(props.officer.turn.length)) {
turnTimes.value.push(
formatTime(
addMinutes(baseTurnTime, idx * props.turnTerm),
props.turnTerm >= 5 ? "HH:mm" : "mm:ss"
)
);
}
}
</script> </script>
+141 -391
View File
@@ -7,10 +7,7 @@
v-if="chiefList !== undefined" v-if="chiefList !== undefined"
:class="`${targetIsMe ? 'targetIsMe' : 'targetIsNotMe'}`" :class="`${targetIsMe ? 'targetIsMe' : 'targetIsNotMe'}`"
> >
<template <template v-for="(chiefLevel, vidx) in [12, 10, 8, 6, 11, 9, 7, 5]" :key="chiefLevel">
v-for="(chiefLevel, vidx) in [12, 10, 8, 6, 11, 9, 7, 5]"
:key="chiefLevel"
>
<div <div
v-if="vidx % 4 == 0" v-if="vidx % 4 == 0"
:class="[ :class="[
@@ -24,9 +21,7 @@
v-for="idx in maxChiefTurn" v-for="idx in maxChiefTurn"
:class="[`turnIdxLeft`, 'align-self-center', 'center']" :class="[`turnIdxLeft`, 'align-self-center', 'center']"
:key="idx" :key="idx"
> >{{ idx }}</div>
{{ idx }}
</div>
</div> </div>
</div> </div>
<div <div
@@ -41,137 +36,23 @@
:maxTurn="maxChiefTurn" :maxTurn="maxChiefTurn"
:turnTerm="turnTerm" :turnTerm="turnTerm"
/> />
<div class="commandBox" v-else> <ChiefReservedCommand
<div v-else
class="only1000px bg1 center row gx-0" :key="idx"
style="height: 24px; font-size: 1.2em" :targetIsMe="targetIsMe"
> :year="year"
<div class="col-5 align-self-center text-end"> :month="month"
{{ officer.officerLevelText }} : :turn="officer.turn"
</div> :turnTerm="turnTerm"
<div :commandList="unwrap(commandList)"
class="col-7 align-self-center" :turnTime="officer.turnTime"
:style="{ :maxTurn="maxChiefTurn"
color: getNpcColor(officer.npcType ?? 0), :maxPushTurn="Math.floor(maxChiefTurn / 2)"
}" :date="date"
> @raiseReload="reloadTable()"
{{ officer.name }} :officer="officer"
</div> :timeDiff="timeDiff"
</div> />
<div
:class="[
'row',
'controlPad',
chiefLevel == officerLevel ? 'targetIsMe' : 'targetIsNotMe',
]"
>
<div class="col-3 col-md-12 order-md-last">
<div class="d-grid mb-1 py-1 only500px bg1 center">
<div
:style="{
color: getNpcColor(officer.npcType ?? 0),
fontSize: '1.2em',
}"
>
{{ officer.name }}
</div>
<div>{{ officer.officerLevelText }}</div>
</div>
<div class="row gx-1 gy-1 py-1">
<div class="col-md-4 mx-0 mb-0 mt-1 d-grid">
<div
class="alert alert-primary mb-0 center"
style="padding: 0.5rem 0"
>
{{ serverNow }}
</div>
</div>
<b-dropdown class="col-md-4" left text="턴 선택">
<b-dropdown-item @click="selectNone()"
>해제</b-dropdown-item
>
<b-dropdown-item @click="selectAll(true)"
>모든턴</b-dropdown-item
>
<b-dropdown-item @click="selectStep(0, 2)"
>홀수턴</b-dropdown-item
>
<b-dropdown-item @click="selectStep(1, 2)"
>짝수턴</b-dropdown-item
>
<b-dropdown-divider></b-dropdown-divider>
<b-dropdown-text
v-for="spanIdx in [3, 4, 5, 6, 7]"
:key="spanIdx"
>
{{ spanIdx }} 간격<br />
<b-button-group>
<b-button
class="ignoreMe"
v-for="beginIdx in spanIdx"
:key="beginIdx"
@click="selectStep(beginIdx - 1, spanIdx)"
>{{ beginIdx }}</b-button
>
</b-button-group>
</b-dropdown-text>
</b-dropdown>
<b-dropdown class="col-md-4" text="반복">
<b-dropdown-item
v-for="turnIdx in maxPushTurn"
:key="turnIdx"
@click="repeatNationCommand(turnIdx)"
>{{ turnIdx }}
</b-dropdown-item>
</b-dropdown>
<b-dropdown
class="col-md-6"
split
text="당기기"
@click="pullNationCommandSingle"
>
<b-dropdown-item
v-for="turnIdx in maxPushTurn"
:key="turnIdx"
@click="pushNationCommand(-turnIdx)"
>{{ turnIdx }}
</b-dropdown-item>
</b-dropdown>
<b-dropdown
class="col-md-6"
split
text="미루기"
@click="pushNationCommandSingle"
>
<b-dropdown-item
v-for="turnIdx in maxPushTurn"
:key="turnIdx"
@click="pushNationCommand(turnIdx)"
>{{ turnIdx }}
</b-dropdown-item>
</b-dropdown>
</div>
</div>
<div class="col">
<ChiefReservedCommand
:key="idx"
:year="year"
:month="month"
:turn="officer.turn"
:turnTerm="turnTerm"
:commandList="unwrap(commandList)"
:turnTime="officer.turnTime"
:maxTurn="maxChiefTurn"
:maxPushTurn="Math.floor(maxChiefTurn / 2)"
:date="date"
v-model:selectedTurn="turnList"
@raiseReload="reloadTable()"
/>
</div>
</div>
</div>
</div> </div>
<div <div
v-if="vidx % 4 == 3" v-if="vidx % 4 == 3"
@@ -186,9 +67,7 @@
v-for="idx in maxChiefTurn" v-for="idx in maxChiefTurn"
:class="[`turnIdxRight`, 'align-self-center', 'center']" :class="[`turnIdxRight`, 'align-self-center', 'center']"
:key="idx" :key="idx"
> >{{ idx }}</div>
{{ idx }}
</div>
</div> </div>
</div> </div>
</template> </template>
@@ -196,19 +75,10 @@
</div> </div>
<div id="bottomChiefBox" v-if="chiefList"> <div id="bottomChiefBox" v-if="chiefList">
<div id="bottomChiefList" class="c-bg2"> <div id="bottomChiefList" class="c-bg2">
<template <template v-for="(chiefLevel, vidx) in [12, 10, 8, 6, 11, 9, 7, 5]" :key="chiefLevel">
v-for="(chiefLevel, vidx) in [12, 10, 8, 6, 11, 9, 7, 5]" <div class="turnIdx subRows bg0" :style="subTableGridRows" v-if="vidx % 4 == 0">
:key="chiefLevel"
>
<div
class="turnIdx subRows bg0"
:style="subTableGridRows"
v-if="vidx % 4 == 0"
>
<div class="bg1" style="grid-row: 1/3"></div> <div class="bg1" style="grid-row: 1/3"></div>
<div v-for="idx in maxChiefTurn" :class="[`turnIdxLeft`]" :key="idx"> <div v-for="idx in maxChiefTurn" :class="[`turnIdxLeft`]" :key="idx">{{ idx }}</div>
{{ idx }}
</div>
</div> </div>
<BottomItem <BottomItem
:chiefLevel="chiefLevel" :chiefLevel="chiefLevel"
@@ -217,15 +87,9 @@
:isMe="chiefLevel == officerLevel" :isMe="chiefLevel == officerLevel"
@click="viewTarget = chiefLevel" @click="viewTarget = chiefLevel"
/> />
<div <div class="turnIdx subRows bg0" :style="subTableGridRows" v-if="vidx % 4 == 3">
class="turnIdx subRows bg0"
:style="subTableGridRows"
v-if="vidx % 4 == 3"
>
<div class="bg1" style="grid-row: 1/3"></div> <div class="bg1" style="grid-row: 1/3"></div>
<div v-for="idx in maxChiefTurn" :class="`turnIdxRight`" :key="idx"> <div v-for="idx in maxChiefTurn" :class="`turnIdxRight`" :key="idx">{{ idx }}</div>
{{ idx }}
</div>
</div> </div>
</template> </template>
</div> </div>
@@ -235,258 +99,144 @@
</div> </div>
</template> </template>
<script lang="ts"> <script lang="ts">
declare const staticValues: {
serverNick: string,
mapName: string,
unitSet: string,
}
</script>
<script lang="ts" setup>
import "@scss/common/bootstrap5.scss"; import "@scss/common/bootstrap5.scss";
import "@scss/game_bg.scss"; import "@scss/game_bg.scss";
import "../../css/config.css"; import "../../css/config.css";
import { computed, defineComponent, reactive, ref, toRefs, watch } from "vue"; import { computed, defineProps, provide, reactive, ref, toRefs, watch } from "vue";
import ChiefReservedCommand from "@/components/ChiefReservedCommand.vue"; import ChiefReservedCommand from "@/components/ChiefReservedCommand.vue";
import TopBackBar from "@/components/TopBackBar.vue"; import TopBackBar from "@/components/TopBackBar.vue";
import BottomBar from "@/components/BottomBar.vue"; import BottomBar from "@/components/BottomBar.vue";
import VueTypes from "vue-types"; import VueTypes from "vue-types";
import { isString, range } from "lodash"; import { isString } from "lodash";
import { mb_strwidth } from "./util/mb_strwidth";
import { entriesWithType } from "./util/entriesWithType"; import { entriesWithType } from "./util/entriesWithType";
import { addMilliseconds } from "date-fns";
import { formatTime } from "./util/formatTime";
import { parseTime } from "./util/parseTime"; import { parseTime } from "./util/parseTime";
import { getNpcColor } from "./common_legacy";
import TopItem from "@/ChiefCenter/TopItem.vue"; import TopItem from "@/ChiefCenter/TopItem.vue";
import BottomItem from "@/ChiefCenter/BottomItem.vue"; import BottomItem from "@/ChiefCenter/BottomItem.vue";
import type { ChiefResponse, OptionalFull } from "./defs"; import type { ChiefResponse, OptionalFull } from "./defs";
import { SammoAPI } from "./SammoAPI"; import { SammoAPI } from "./SammoAPI";
import { unwrap } from "@/util/unwrap"; import { unwrap } from "@/util/unwrap";
import { StoredActionsHelper } from "./util/StoredActionsHelper";
function isDropdownChildren(e?: Event): boolean { const {
if (!e) { serverNick,
return false; mapName,
unitSet,
} = staticValues;
const props = defineProps({
maxChiefTurn: VueTypes.number.isRequired,
})
const tableObj = reactive<Omit<OptionalFull<ChiefResponse>, "result">>({
lastExecute: undefined,
year: undefined,
month: undefined,
turnTerm: undefined,
date: undefined,
chiefList: undefined,
isChief: undefined,
autorun_limit: undefined,
officerLevel: undefined,
commandList: undefined,
mapName: undefined,
unitSet: undefined,
});
const {
year,
month,
turnTerm,
date,
chiefList,
officerLevel,
commandList,
} = toRefs(tableObj);
const viewTarget = ref<number | undefined>();
const targetIsMe = ref<boolean>(false);
watch(viewTarget, (val) => {
console.log("targetChange!", val, targetIsMe);
if (val === undefined) {
targetIsMe.value = false;
return;
} }
if (!e.target) { if (tableObj.officerLevel === undefined) {
return false; targetIsMe.value = false;
} }
if ( targetIsMe.value = val === tableObj.officerLevel;
(e.target as HTMLElement).classList.contains("dropdown-item") || console.log("result", targetIsMe.value);
(e.target as HTMLElement).classList.contains("dropdown-toggle-split") || });
(e.target as HTMLElement).classList.contains("ignoreMe")
) { const timeDiff = ref(0);
return true; async function reloadTable(): Promise<void> {
try {
const response =
await SammoAPI.NationCommand.GetReservedCommand<ChiefResponse>();
console.log(response);
for (const [key, value] of entriesWithType(response)) {
if (key === "result") {
continue;
}
if (key === "officerLevel") {
if (value < 5) {
tableObj.officerLevel = undefined;
} else {
tableObj.officerLevel = value as number;
}
continue;
}
//HACK:
tableObj[key as unknown as "year"] = value as unknown as undefined;
}
const serverNowObj = parseTime(response.date);
const clientNowObj = new Date();
timeDiff.value = serverNowObj.getTime() - clientNowObj.getTime();
if (viewTarget.value === undefined) {
if (!tableObj.officerLevel) {
viewTarget.value = 12;
} else {
viewTarget.value = tableObj.officerLevel;
}
}
} catch (e) {
if (isString(e)) {
alert(e);
}
console.error(e);
return;
} }
return false;
} }
export default defineComponent({ const mainTableGridRows = computed(() => {
components: { return {
TopBackBar, gridTemplateRows: `24px repeat(${props.maxChiefTurn}, 30px)`,
BottomBar, };
ChiefReservedCommand,
TopItem,
BottomItem,
},
props: {
maxChiefTurn: VueTypes.number.isRequired,
},
watch: {
year() {
console.log(this.lastExecute);
},
},
methods: {
toggleTurn(turnIdx: number) {
if (this.turnList.has(turnIdx)) {
this.turnList.delete(turnIdx);
} else {
this.turnList.add(turnIdx);
}
},
selectTurn(turnIdx: number) {
this.turnList.clear();
this.turnList.add(turnIdx);
},
selectNone() {
this.turnList.clear();
},
selectAll(e: Event | true) {
//NOTE: split 구현에 버그가 있어서, 수동으로 구분해야함
if (e !== true && isDropdownChildren(e)) {
return;
}
if (this.turnList.size * 3 > this.maxChiefTurn) {
this.turnList.clear();
} else {
for (let i = 0; i < this.maxChiefTurn; i++) {
this.turnList.add(i);
}
}
},
selectStep(begin: number, step: number) {
this.turnList.clear();
for (const idx of range(0, this.maxChiefTurn)) {
if ((idx - begin) % step == 0) {
this.turnList.add(idx);
}
}
},
async repeatNationCommand(amount: number) {
try {
await SammoAPI.NationCommand.RepeatCommand({ amount });
} catch (e) {
console.error(e);
alert(`실패했습니다: ${e}`);
return;
}
await this.reloadTable();
},
async pushNationCommand(amount: number) {
try {
await SammoAPI.NationCommand.PushCommand({ amount });
} catch (e) {
console.error(e);
alert(`실패했습니다: ${e}`);
return;
}
await this.reloadTable();
},
pushNationCommandSingle(e: Event) {
//NOTE: split 구현에 버그가 있어서, 수동으로 구분해야함
if (isDropdownChildren(e)) {
return;
}
void this.pushNationCommand(1);
},
pullNationCommandSingle(e: Event) {
//NOTE: split 구현에 버그가 있어서, 수동으로 구분해야함
if (isDropdownChildren(e)) {
return;
}
void this.pushNationCommand(-1);
},
},
setup(props) {
const viewTarget = ref<number | undefined>();
const turnList = ref(new Set<number>());
const targetIsMe = ref<boolean>(false);
watch(viewTarget, (val) => {
console.log("targetChange!", val, targetIsMe);
if (val === undefined) {
targetIsMe.value = false;
return;
}
if (tableObj.officerLevel === undefined) {
targetIsMe.value = false;
}
targetIsMe.value = val === tableObj.officerLevel;
console.log("result", targetIsMe.value);
});
const tableObj = reactive<Omit<OptionalFull<ChiefResponse>, "result">>({
lastExecute: undefined,
year: undefined,
month: undefined,
turnTerm: undefined,
date: undefined,
chiefList: undefined,
isChief: undefined,
autorun_limit: undefined,
officerLevel: undefined,
commandList: undefined,
mapName: undefined,
unitSet: undefined,
});
async function reloadTable(): Promise<void> {
try {
const response =
await SammoAPI.NationCommand.GetReservedCommand<ChiefResponse>();
console.log(response);
for (const [key, value] of entriesWithType(response)) {
if (key === "result") {
continue;
}
if (key === "officerLevel") {
if (value < 5) {
tableObj.officerLevel = undefined;
} else {
tableObj.officerLevel = value as number;
}
continue;
}
//HACK:
tableObj[key as unknown as "year"] = value as unknown as undefined;
}
const serverNowObj = parseTime(response.date);
const clientNowObj = new Date();
timeDiff.value = serverNowObj.getTime() - clientNowObj.getTime();
if (viewTarget.value === undefined) {
if (!tableObj.officerLevel) {
viewTarget.value = 12;
} else {
viewTarget.value = tableObj.officerLevel;
}
}
} catch (e) {
if (isString(e)) {
alert(e);
}
console.error(e);
return;
}
}
//
const mainTableGridRows = computed(() => {
return {
gridTemplateRows: `24px repeat(${props.maxChiefTurn}, 30px)`,
};
});
const subTableGridRows = computed(() => {
return {
gridTemplateRows: `36px repeat(${props.maxChiefTurn + 1}, 1fr)`,
};
});
void reloadTable();
const serverNow = ref(formatTime(new Date(), "HH:mm:ss"));
const timeDiff = ref(0);
function updateNow() {
const serverNowObj = addMilliseconds(new Date(), timeDiff.value);
serverNow.value = formatTime(serverNowObj, "HH:mm:ss");
setTimeout(() => {
updateNow();
}, 1000 - serverNowObj.getMilliseconds());
}
setTimeout(() => {
updateNow();
}, 500);
return {
updateNow,
serverNow,
timeDiff,
turnList,
...toRefs(tableObj),
mb_strwidth,
mainTableGridRows,
subTableGridRows,
reloadTable,
getNpcColor,
unwrap,
viewTarget,
targetIsMe,
maxPushTurn: props.maxChiefTurn / 2,
};
},
}); });
const subTableGridRows = computed(() => {
return {
gridTemplateRows: `36px repeat(${props.maxChiefTurn + 1}, 1fr)`,
};
});
void reloadTable();
const storedActionsHelper = new StoredActionsHelper(staticValues.serverNick, 'nation', staticValues.mapName, staticValues.unitSet);
provide('storedNationActionsHelper', storedActionsHelper);
</script> </script>
<style lang="scss"> <style lang="scss">
@import "@scss/chiefCenter.scss"; @import "@scss/chiefCenter.scss";
+144 -284
View File
@@ -30,102 +30,114 @@
</div> </div>
</div> </div>
<div class="commandSelectFormAnchor"> <div v-if="isEditMode" class="row gx-1">
<div v-if="isEditMode" class="row gx-1"> <div class="col-4 d-grid">
<div class="col-4 d-grid"> <BDropdown left text="범위">
<BDropdown left text="범위"> <BDropdownItem @click="queryActionHelper.selectTurn()">해제</BDropdownItem>
<BDropdownItem @click="selectTurn()">해제</BDropdownItem> <BDropdownItem @click="queryActionHelper.selectAll()">모든턴</BDropdownItem>
<BDropdownItem @click="selectAll(true)">모든</BDropdownItem> <BDropdownItem @click="queryActionHelper.selectStep(0, 2)">홀수</BDropdownItem>
<BDropdownItem @click="selectStep(0, 2)">수턴</BDropdownItem> <BDropdownItem @click="queryActionHelper.selectStep(1, 2)">수턴</BDropdownItem>
<BDropdownItem @click="selectStep(1, 2)">짝수턴</BDropdownItem> <BDropdownDivider></BDropdownDivider>
<BDropdownDivider></BDropdownDivider>
<BDropdownText v-for="spanIdx in [3, 4, 5, 6, 7]" :key="spanIdx"> <BDropdownText v-for="spanIdx in [3, 4, 5, 6, 7]" :key="spanIdx">
{{ spanIdx }} 간격 {{ spanIdx }} 간격
<br /> <br />
<BButtonGroup> <BButtonGroup>
<BButton <BButton
class="ignoreMe" class="ignoreMe"
v-for="beginIdx in spanIdx" v-for="beginIdx in spanIdx"
:key="beginIdx" :key="beginIdx"
@click="selectStep(beginIdx - 1, spanIdx)" @click="queryActionHelper.selectStep(beginIdx - 1, spanIdx)"
>{{ beginIdx }}</BButton> >{{ beginIdx }}</BButton>
</BButtonGroup> </BButtonGroup>
</BDropdownText> </BDropdownText>
</BDropdown> </BDropdown>
</div> </div>
<div class="col-4 d-grid"> <div class="col-4 d-grid">
<BDropdown left text="보관함"> <BDropdown left text="보관함">
<BDropdownItem <BDropdownItem
v-for="[actionKey, actions] of storedActions" v-for="[actionKey, actions] of storedActions"
:key="actionKey" :key="actionKey"
@click="useStoredAction(actions)" @click.self="useStoredAction(actions)"
> >
{{ actionKey }} {{ actionKey }}
<BButton @click.prevent="deleteStoredActions(actionKey)" size="sm">삭제</BButton> <BButton @click.prevent="deleteStoredActions(actionKey)" size="sm">삭제</BButton>
</BDropdownItem> </BDropdownItem>
</BDropdown> </BDropdown>
</div> </div>
<div class="col-4 d-grid"> <div class="col-4 d-grid">
<BDropdown right text="최근 실행"> <BDropdown right text="최근 실행">
<BDropdownItem <BDropdownItem
v-for="(action, idx) in recentActions" v-for="(action, idx) in recentActions"
:key="idx" :key="idx"
@click="void reserveCommandDirect([[Array.from(turnList.values()), action]])" @click="void reserveCommandDirect([[Array.from(selectedTurnList.values()), action]])"
>{{ action.brief }}</BDropdownItem> >{{ action.brief }}</BDropdownItem>
</BDropdown> </BDropdown>
</div> </div>
<div class="col-5 d-grid"> <div class="col-5 d-grid">
<BDropdown left variant="info" text="선택한 턴을"> <BDropdown left variant="info" text="선택한 턴을">
<BDropdownItem @click="clipboardCut"> <BDropdownItem @click="clipboardCut">
<i class="bi bi-scissors"></i>&nbsp;잘라내기 <i class="bi bi-scissors"></i>&nbsp;잘라내기
</BDropdownItem> </BDropdownItem>
<BDropdownItem @click="clipboardCopy"> <BDropdownItem @click="clipboardCopy">
<i class="bi bi-files"></i>&nbsp;복사하기 <i class="bi bi-files"></i>&nbsp;복사하기
</BDropdownItem> </BDropdownItem>
<BDropdownItem @click="clipboardPaste"> <BDropdownItem @click="clipboardPaste">
<i class="bi bi-clipboard-fill"></i>&nbsp;붙여넣기 <i class="bi bi-clipboard-fill"></i>&nbsp;붙여넣기
</BDropdownItem> </BDropdownItem>
<BDropdownDivider /> <BDropdownDivider />
<BDropdownItem @click="setStoredActions"> <BDropdownItem @click="setStoredActions">
<i class="bi bi-bookmark-plus-fill"></i>&nbsp;보관하기 <i class="bi bi-bookmark-plus-fill"></i>&nbsp;보관하기
</BDropdownItem> </BDropdownItem>
<BDropdownItem @click="subRepeatCommand"> <BDropdownItem @click="subRepeatCommand">
<i class="bi bi-arrow-repeat"></i>&nbsp;반복하기 <i class="bi bi-arrow-repeat"></i>&nbsp;반복하기
</BDropdownItem> </BDropdownItem>
<BDropdownDivider /> <BDropdownDivider />
<BDropdownItem @click="eraseSelectedTurnList"> <BDropdownItem @click="eraseSelectedTurnList">
<i class="bi bi-eraser"></i>&nbsp;비우기 <i class="bi bi-eraser"></i>&nbsp;비우기
</BDropdownItem> </BDropdownItem>
<BDropdownItem @click="eraseAndPullCommand"> <BDropdownItem @click="eraseAndPullCommand">
<i class="bi bi-arrow-bar-up"></i>&nbsp;지우고 당기기 <i class="bi bi-arrow-bar-up"></i>&nbsp;지우고 당기기
</BDropdownItem> </BDropdownItem>
<BDropdownItem @click="pushEmptyCommand"> <BDropdownItem @click="pushEmptyCommand">
<i class="bi bi-arrow-bar-down"></i>&nbsp;뒤로 밀기 <i class="bi bi-arrow-bar-down"></i>&nbsp;뒤로 밀기
</BDropdownItem> </BDropdownItem>
<!-- 최근에 실행한 10 --> <!-- 최근에 실행한 10 -->
</BDropdown> </BDropdown>
</div> </div>
<div class="col-7 d-grid"> <div class="col-7 d-grid">
<BButton variant="light" @click="toggleForm($event)" :style="{ color: 'black' }">명령 선택 </BButton> <BButton variant="light" @click="toggleForm($event)" :style="{ color: 'black' }">명령 선택 </BButton>
</div>
</div> </div>
</div> </div>
<CommandSelectForm
:commandList="commandList"
ref="commandSelectForm"
@on-close="chooseCommand($event)"
v-model:activatedCategory="activatedCategory"
/>
<div :style="{ position: 'relative' }"> <div :style="{ position: 'relative' }">
<div <div
class="commandQuickReserveFormAnchor bg-dark" class="bg-dark"
:style="{ :style="{
position: 'absolute', position: 'absolute',
top: `${basicModeRowHeight * currentQuickReserveTarget + 30}px`, top: `${basicModeRowHeight * currentQuickReserveTarget + 30}px`,
width: '100%', width: '100%',
zIndex: 9, zIndex: 9,
}" }"
></div> >
<CommandSelectForm
:commandList="commandList"
ref="commandQuickReserveForm"
@on-close="chooseQuickReserveCommand($event)"
:hideClose="false"
v-model:activatedCategory="activatedCategory"
/>
</div>
</div> </div>
<div :class="{ <div :class="{
commandTable: true, commandTable: true,
@@ -138,7 +150,7 @@
@dragStart="isDragToggle = true" @dragStart="isDragToggle = true"
@dragDone=" @dragDone="
isDragToggle = false; isDragToggle = false;
toggleTurn(...$event); queryActionHelper.toggleTurn(...$event);
" "
v-slot="{ selected }" v-slot="{ selected }"
> >
@@ -156,9 +168,9 @@ toggleTurn(...$event);
size="sm" size="sm"
:variant=" :variant="
(isDragToggle && selected.has(`${turnIdx}`)) ? 'light' : (isDragToggle && selected.has(`${turnIdx}`)) ? 'light' :
turnList.has(turnIdx) selectedTurnList.has(turnIdx)
? 'info' ? 'info'
: turnList.size == 0 && prevTurnList.has(turnIdx) : selectedTurnList.size == 0 && prevSelectedTurnList.has(turnIdx)
? 'success' ? 'success'
: 'primary' : 'primary'
" "
@@ -173,7 +185,7 @@ toggleTurn(...$event);
@dragStart="isDragSingle = true" @dragStart="isDragSingle = true"
@dragDone=" @dragDone="
isDragSingle = false; isDragSingle = false;
selectTurn(...$event); queryActionHelper.selectTurn(...$event);
" "
v-slot="{ selected }" v-slot="{ selected }"
> >
@@ -276,19 +288,6 @@ selectTurn(...$event);
</div> </div>
</div> </div>
</div> </div>
<CommandSelectForm
:commandList="commandList"
anchor=".commandSelectFormAnchor"
ref="commandSelectForm"
@on-close="chooseCommand($event)"
/>
<CommandSelectForm
:commandList="commandList"
anchor=".commandQuickReserveFormAnchor"
ref="commandQuickReserveForm"
@on-close="chooseQuickReserveCommand($event)"
:hideClose="false"
/>
</template> </template>
<script lang="ts"> <script lang="ts">
@@ -309,7 +308,7 @@ declare const staticValues: {
<script lang="ts" setup> <script lang="ts" setup>
import addMilliseconds from "date-fns/esm/addMilliseconds"; import addMilliseconds from "date-fns/esm/addMilliseconds";
import addMinutes from "date-fns/esm/addMinutes"; import addMinutes from "date-fns/esm/addMinutes";
import { clone, isString, min, range, repeat, trim } from "lodash"; import { range, trim } from "lodash";
import { stringifyUrl } from "query-string"; import { stringifyUrl } from "query-string";
import { onMounted, ref, watch } from "vue"; import { onMounted, ref, watch } from "vue";
import { formatTime } from "@util/formatTime"; import { formatTime } from "@util/formatTime";
@@ -318,22 +317,16 @@ import { mb_strwidth } from "@util/mb_strwidth";
import { parseTime } from "@util/parseTime"; import { parseTime } from "@util/parseTime";
import { parseYearMonth } from "@util/parseYearMonth"; import { parseYearMonth } from "@util/parseYearMonth";
import DragSelect from "@/components/DragSelect.vue"; import DragSelect from "@/components/DragSelect.vue";
import { SammoAPI, type InvalidResponse } from "./SammoAPI"; import { SammoAPI } from "./SammoAPI";
import type { CommandItem, ReserveBulkCommandResponse, ReserveCommandResponse } from "@/defs"; import type { CommandItem, ReserveCommandResponse } from "@/defs";
import CommandSelectForm from "@/components/CommandSelectForm.vue"; import CommandSelectForm from "@/components/CommandSelectForm.vue";
import { BButton, BButtonGroup, BDropdownItem, BDropdown, BDropdownText, BDropdownDivider } from "bootstrap-vue-3"; import { BButton, BButtonGroup, BDropdownItem, BDropdown, BDropdownText, BDropdownDivider } from "bootstrap-vue-3";
import { StoredActionsHelper } from "./util/StoredActionsHelper"; import { StoredActionsHelper } from "./util/StoredActionsHelper";
import type { TurnObj } from '@/defs'; import type { TurnObj } from '@/defs';
import { unwrap } from "./util/unwrap";
import type { Args } from "./processing/args"; import type { Args } from "./processing/args";
import { QueryActionHelper } from "./util/QueryActionHelper";
type TurnObjWithTime = TurnObj & {
time: string;
year?: number;
month?: number;
tooltip?: string;
style?: Record<string, unknown>;
};
type ReservedCommandResponse = { type ReservedCommandResponse = {
result: true; result: true;
@@ -405,24 +398,14 @@ setTimeout(() => {
updateNow(); updateNow();
}, 1000 - serverNow.value.getMilliseconds()); }, 1000 - serverNow.value.getMilliseconds());
const queryActionHelper = new QueryActionHelper(staticValues.maxTurn);
const storedActionsHelper = new StoredActionsHelper(staticValues.serverNick, 'general', staticValues.mapName, staticValues.unitSet);
const emptyTurn: TurnObjWithTime[] = Array.from<TurnObjWithTime>({ const reservedCommandList = queryActionHelper.reservedCommandList;
length: staticValues.maxTurn, const prevSelectedTurnList = queryActionHelper.prevSelectedTurnList;
}).fill({ const selectedTurnList = queryActionHelper.selectedTurnList;
arg: {},
brief: "",
action: "",
year: undefined,
month: undefined,
time: "",
});
const editModeKey = `sammo_edit_mode_key`; const isEditMode = storedActionsHelper.isEditMode;
const prevTurnList = ref(new Set([0]));
const turnList = ref(new Set<number>());
const reservedCommandList = ref(emptyTurn);
const isEditMode = ref(localStorage.getItem(editModeKey) === '1');
const flippedMaxTurn = 14; const flippedMaxTurn = 14;
@@ -456,53 +439,7 @@ function updateNow() {
}, 1000 - serverNow.value.getMilliseconds()); }, 1000 - serverNow.value.getMilliseconds());
} }
function toggleTurn(...reqTurnList: number[] | string[]) {
for (let turnIdx of reqTurnList) {
if (isString(turnIdx)) {
turnIdx = parseInt(turnIdx);
}
if (turnList.value.has(turnIdx)) {
turnList.value.delete(turnIdx);
} else {
turnList.value.add(turnIdx);
}
}
}
function selectTurn(...reqTurnList: number[] | string[]) {
turnList.value.clear();
for (const turnIdx of reqTurnList) {
if (isString(turnIdx)) {
turnList.value.add(parseInt(turnIdx));
} else {
turnList.value.add(turnIdx);
}
}
}
function selectAll(e: Event | true) {
//NOTE: split 구현에 버그가 있어서, 수동으로 구분해야함
if (e !== true && isDropdownChildren(e)) {
return;
}
if (turnList.value.size * 3 > maxTurn) {
turnList.value.clear();
} else {
for (let i = 0; i < maxTurn; i++) {
turnList.value.add(i);
}
}
}
function selectStep(begin: number, step: number) {
turnList.value.clear();
for (const idx of range(0, maxTurn)) {
if ((idx - begin) % step == 0) {
turnList.value.add(idx);
}
}
}
function toggleViewMaxTurn() { function toggleViewMaxTurn() {
if (viewMaxTurn.value == flippedMaxTurn) { if (viewMaxTurn.value == flippedMaxTurn) {
@@ -620,8 +557,6 @@ async function reloadCommandList() {
} }
async function reserveCommandDirect(args: [number[], TurnObj][], reload = true): Promise<boolean> { async function reserveCommandDirect(args: [number[], TurnObj][], reload = true): Promise<boolean> {
const waiterList: Promise<ReserveCommandResponse | InvalidResponse>[] = [];
const query: { const query: {
turnList: number[], turnList: number[],
action: string, action: string,
@@ -637,7 +572,7 @@ async function reserveCommandDirect(args: [number[], TurnObj][], reload = true):
try { try {
await SammoAPI.Command.ReserveBulkCommand(query); await SammoAPI.Command.ReserveBulkCommand(query);
releaseSelectedTurnList(); queryActionHelper.releaseSelectedTurnList();
} catch (e) { } catch (e) {
console.error(e); console.error(e);
alert(`실패했습니다: ${e}`); alert(`실패했습니다: ${e}`);
@@ -650,28 +585,8 @@ async function reserveCommandDirect(args: [number[], TurnObj][], reload = true):
return true; return true;
} }
function getSelectedTurnList(): number[] {
if (turnList.value.size) {
return Array.from(turnList.value);
}
if (prevTurnList.value.size) {
return Array.from(prevTurnList.value);
}
return [0];
}
function releaseSelectedTurnList() {
if (turnList.value.size > 0) {
prevTurnList.value.clear();
for (const v of turnList.value) {
prevTurnList.value.add(v);
}
turnList.value.clear();
}
}
async function reserveCommand() { async function reserveCommand() {
let reqTurnList: number[] = getSelectedTurnList(); let reqTurnList: number[] = queryActionHelper.getSelectedTurnList();
const commandName = selectedCommand.value.value; const commandName = selectedCommand.value.value;
@@ -698,7 +613,7 @@ async function reserveCommand() {
arg: {} arg: {}
}); });
releaseSelectedTurnList(); queryActionHelper.releaseSelectedTurnList();
} catch (e) { } catch (e) {
@@ -725,8 +640,8 @@ function chooseQuickReserveCommand(val?: string) {
return; return;
} }
selectedCommand.value = invCommandMap[val]; selectedCommand.value = invCommandMap[val];
turnList.value.clear(); selectedTurnList.value.clear();
turnList.value.add(currentQuickReserveTarget.value); selectedTurnList.value.add(currentQuickReserveTarget.value);
void reserveCommand(); void reserveCommand();
} }
function toggleQuickReserveForm(turnIdx: number) { function toggleQuickReserveForm(turnIdx: number) {
@@ -740,7 +655,6 @@ function toggleQuickReserveForm(turnIdx: number) {
watch(isEditMode, newEditMode => { watch(isEditMode, newEditMode => {
localStorage.setItem(editModeKey, newEditMode ? '1' : '0');
if (newEditMode) { if (newEditMode) {
commandQuickReserveForm.value?.close(); commandQuickReserveForm.value?.close();
currentQuickReserveTarget.value = -1; currentQuickReserveTarget.value = -1;
@@ -752,85 +666,23 @@ watch(isEditMode, newEditMode => {
const emptyTurnObj: TurnObj = { action: '휴식', brief: '휴식', arg: {} }; const emptyTurnObj: TurnObj = { action: '휴식', brief: '휴식', arg: {} };
const storedActionsHelper = new StoredActionsHelper(staticValues.serverNick, 'general', staticValues.mapName, staticValues.unitSet);
const recentActions = storedActionsHelper.recentActions; const recentActions = storedActionsHelper.recentActions;
const storedActions = storedActionsHelper.storedActions; const storedActions = storedActionsHelper.storedActions;
const activatedCategory = storedActionsHelper.activatedCategory;
async function eraseSelectedTurnList(releaseSelect = true): Promise<boolean> { async function eraseSelectedTurnList(releaseSelect = true): Promise<boolean> {
const result = await reserveCommandDirect([[ const result = await reserveCommandDirect([[
getSelectedTurnList(), queryActionHelper.getSelectedTurnList(),
emptyTurnObj emptyTurnObj
]]); ]]);
if (releaseSelect) { if (releaseSelect) {
releaseSelectedTurnList(); queryActionHelper.releaseSelectedTurnList();
} }
return result; return result;
} }
const clipboard = storedActionsHelper.clipboard;
function refineQueryActions(): [number[], TurnObj][] {
const reqTurnList = getSelectedTurnList();
const selectedMinTurnIdx = unwrap(min<number>(reqTurnList));
const buffer: [number[], TurnObj][] = [];
for (const rawTurnIdx of reqTurnList) {
const turnIdx = rawTurnIdx - selectedMinTurnIdx;
const rawAction = reservedCommandList.value[rawTurnIdx]
buffer.push([[turnIdx], {
action: rawAction.action,
arg: clone(rawAction.arg),
brief: rawAction.brief
}]);
}
return buffer;
}
function amplifyQueryActions(rawActions: [number[], TurnObj][], reqTurnList: number[]): [number[], TurnObj][] {
if (reqTurnList.length < 1) {
return [];
}
let minQueryIdx = maxTurn;
let maxQueryIdx = 0;
for (const [turnList] of rawActions) {
for (const turnIdx of turnList) {
minQueryIdx = Math.min(minQueryIdx, turnIdx);
maxQueryIdx = Math.max(maxQueryIdx, turnIdx);
}
}
const queryLength = maxQueryIdx - minQueryIdx + 1;
const queryTurnList: number[] = [reqTurnList[0]];
for (const reqTurnIdx of reqTurnList) {
const last = queryTurnList[queryTurnList.length - 1];
if (reqTurnIdx < last + queryLength) {
continue;
}
queryTurnList.push(reqTurnIdx);
}
const actions: [number[], TurnObj][] = [];
for (const [baseTurnList, action] of rawActions) {
const subTurnList: number[] = [];
for (const baseTurnIdx of baseTurnList) {
for (const queryTurnIdx of queryTurnList) {
const targetTurn = baseTurnIdx + queryTurnIdx;
if (targetTurn >= maxTurn) {
continue;
}
subTurnList.push(baseTurnIdx + queryTurnIdx);
}
}
if (subTurnList.length == 0) {
continue;
}
actions.push([subTurnList, action]);
}
return actions;
}
const clipboard = ref<[number[], TurnObj][] | undefined>(undefined);
async function clipboardCut(releaseSelect = true) { async function clipboardCut(releaseSelect = true) {
clipboardCopy(false); clipboardCopy(false);
@@ -838,9 +690,9 @@ async function clipboardCut(releaseSelect = true) {
} }
function clipboardCopy(releaseSelect = true) { function clipboardCopy(releaseSelect = true) {
clipboard.value = refineQueryActions(); clipboard.value = queryActionHelper.extractQueryActions();
if (releaseSelect) { if (releaseSelect) {
releaseSelectedTurnList(); queryActionHelper.releaseSelectedTurnList();
} }
} }
@@ -850,37 +702,37 @@ async function clipboardPaste(releaseSelect = true) {
return; return;
} }
const actions = amplifyQueryActions(rawActions, getSelectedTurnList()); const actions = queryActionHelper.amplifyQueryActions(rawActions, queryActionHelper.getSelectedTurnList());
if (actions.length === 0) { if (actions.length === 0) {
return; return;
} }
const result = await reserveCommandDirect(actions); const result = await reserveCommandDirect(actions);
if (releaseSelect) { if (releaseSelect) {
releaseSelectedTurnList(); queryActionHelper.releaseSelectedTurnList();
} }
return result; return result;
} }
async function subRepeatCommand(releaseSelect = true): Promise<boolean> { async function subRepeatCommand(releaseSelect = true): Promise<boolean> {
const reqTurnList = getSelectedTurnList().sort((a, b) => (a - b)); const reqTurnList = queryActionHelper.getSelectedTurnList();
const selectedMinTurnIdx = reqTurnList[0]; const selectedMinTurnIdx = reqTurnList[0];
const selectedMaxTurnIdx = reqTurnList[reqTurnList.length - 1]; const selectedMaxTurnIdx = reqTurnList[reqTurnList.length - 1];
const queryLength = selectedMaxTurnIdx - selectedMinTurnIdx + 1; const queryLength = selectedMaxTurnIdx - selectedMinTurnIdx + 1;
const rawActions = refineQueryActions(); const rawActions = queryActionHelper.extractQueryActions();
const actions = amplifyQueryActions(rawActions, range(selectedMinTurnIdx, maxTurn, queryLength)); const actions = queryActionHelper.amplifyQueryActions(rawActions, range(selectedMinTurnIdx, maxTurn, queryLength));
const result = await reserveCommandDirect(actions); const result = await reserveCommandDirect(actions);
if (releaseSelect) { if (releaseSelect) {
releaseSelectedTurnList(); queryActionHelper.releaseSelectedTurnList();
} }
return result; return result;
} }
async function eraseAndPullCommand(releaseSelect = true): Promise<boolean> { async function eraseAndPullCommand(releaseSelect = true): Promise<boolean> {
const reqTurnList = getSelectedTurnList().sort((a, b) => (a - b)); const reqTurnList = queryActionHelper.getSelectedTurnList();
const selectedMinTurnIdx = reqTurnList[0]; const selectedMinTurnIdx = reqTurnList[0];
const selectedMaxTurnIdx = reqTurnList[reqTurnList.length - 1]; const selectedMaxTurnIdx = reqTurnList[reqTurnList.length - 1];
const queryLength = selectedMaxTurnIdx - selectedMinTurnIdx + 1; const queryLength = selectedMaxTurnIdx - selectedMinTurnIdx + 1;
@@ -917,13 +769,13 @@ async function eraseAndPullCommand(releaseSelect = true): Promise<boolean> {
const result = await reserveCommandDirect(actions); const result = await reserveCommandDirect(actions);
if (releaseSelect) { if (releaseSelect) {
releaseSelectedTurnList(); queryActionHelper.releaseSelectedTurnList();
} }
return result; return result;
} }
async function pushEmptyCommand(releaseSelect = true): Promise<boolean> { async function pushEmptyCommand(releaseSelect = true): Promise<boolean> {
const reqTurnList = getSelectedTurnList().sort((a, b) => (a - b)); const reqTurnList = queryActionHelper.getSelectedTurnList();
const selectedMinTurnIdx = reqTurnList[0]; const selectedMinTurnIdx = reqTurnList[0];
const selectedMaxTurnIdx = reqTurnList[reqTurnList.length - 1]; const selectedMaxTurnIdx = reqTurnList[reqTurnList.length - 1];
const queryLength = selectedMaxTurnIdx - selectedMinTurnIdx + 1; const queryLength = selectedMaxTurnIdx - selectedMinTurnIdx + 1;
@@ -960,26 +812,34 @@ async function pushEmptyCommand(releaseSelect = true): Promise<boolean> {
const result = await reserveCommandDirect(actions); const result = await reserveCommandDirect(actions);
if (releaseSelect) { if (releaseSelect) {
releaseSelectedTurnList(); queryActionHelper.releaseSelectedTurnList();
} }
return result; return result;
} }
function setStoredActions() { function setStoredActions() {
const actions = refineQueryActions(); const actions = queryActionHelper.extractQueryActions();
const turnBrief: string[] = []; const turnBrief = new Map<number, string>();
for (const [subTurnList, action] of actions) { for (const [subTurnList, action] of actions) {
const actionName = action.action.split('_'); const actionName = action.action.split('_');
const actionShortName = actionName.length == 1 ? actionName[0] : actionName[1]; const actionShortName = actionName.length == 1 ? actionName[0] : actionName[1];
turnBrief.push(repeat(actionShortName[0], subTurnList.length)); for (const turnIdx of subTurnList) {
turnBrief.set(turnIdx, actionShortName[0]);
}
} }
const nickName = trim(prompt('선택한 턴들의 별명을 지어주세요', turnBrief.join()) ?? '');
const turnBriefStr = Array.from(turnBrief.entries())
.sort(([turnA], [turnB]) => turnA - turnB)
.map(([, action]) => action)
.join('');
const nickName = trim(prompt('선택한 턴들의 별명을 지어주세요', turnBriefStr) ?? '');
if (nickName == '') { if (nickName == '') {
return; return;
} }
storedActionsHelper.setStoredActions(nickName, actions); storedActionsHelper.setStoredActions(nickName, actions);
releaseSelectedTurnList(); queryActionHelper.releaseSelectedTurnList();
} }
function deleteStoredActions(actionKey: string) { function deleteStoredActions(actionKey: string) {
@@ -987,10 +847,10 @@ function deleteStoredActions(actionKey: string) {
} }
async function useStoredAction(rawActions: [number[], TurnObj][]) { async function useStoredAction(rawActions: [number[], TurnObj][]) {
const reqTurnList = getSelectedTurnList().sort((a, b) => (a - b)); const reqTurnList = queryActionHelper.getSelectedTurnList();
const actions = amplifyQueryActions(rawActions, reqTurnList) const actions = queryActionHelper.amplifyQueryActions(rawActions, reqTurnList)
const result = await reserveCommandDirect(actions); const result = await reserveCommandDirect(actions);
releaseSelectedTurnList(); queryActionHelper.releaseSelectedTurnList();
return result; return result;
} }
+5
View File
@@ -38,6 +38,11 @@ const apiRealPath = {
PushCommand: done, PushCommand: done,
RepeatCommand: done, RepeatCommand: done,
ReserveCommand: done, ReserveCommand: done,
ReserveBulkCommand: done as CallbackT<{
turnList: number[],
action: string,
arg: Args
}[], ReserveBulkCommandResponse>,
}, },
Nation: { Nation: {
SetNotice: done, SetNotice: done,
+876 -419
View File
@@ -1,151 +1,295 @@
<template> <template>
<div class="commandPad chiefReservedCommand"> <div class="commandBox">
<div class="commandTable"> <div class="only1000px bg1 center row gx-0" style="height: 24px; font-size: 1.2em">
<DragSelect <div class="col-5 align-self-center text-end">{{ officer.officerLevelText }} :</div>
:style="rowGridStyle" <div
attribute="turnIdx" class="col-7 align-self-center"
@dragStart="isDragSingle = true" :style="{
@dragDone=" color: getNpcColor(officer.npcType ?? 0),
isDragSingle = false; }"
selectTurn(...$event); >{{ officer.name }}</div>
"
v-slot="{ selected }"
>
<div
v-for="(turnObj, turnIdx) in reservedCommandList"
:key="turnIdx"
:turnIdx="turnIdx"
class="time_pad center f_tnum"
:style="{
backgroundColor: 'black',
whiteSpace: 'nowrap',
overflow: 'hidden',
color:
isDragSingle && selected.has(`${turnIdx}`) ? 'cyan' : undefined,
}"
>
{{ turnObj.time }}
</div>
</DragSelect>
<DragSelect
:style="rowGridStyle"
attribute="turnIdx"
@dragStart="isDragToggle = true"
@dragDone="
isDragToggle = false;
toggleTurn(...$event);
"
v-slot="{ selected }"
>
<div
v-for="(turnObj, turnIdx) in reservedCommandList"
:key="turnIdx"
:turnIdx="turnIdx"
class="idx_pad center d-grid"
>
<b-button
size="sm"
:variant="
isDragToggle && selected.has(`${turnIdx}`)
? 'light'
: turnList.has(turnIdx)
? 'info'
: turnList.size == 0 && prevTurnList.has(turnIdx)
? 'success'
: 'primary'
"
>{{ turnIdx + 1 }}</b-button
>
</div>
</DragSelect>
<div :style="rowGridStyle">
<div
v-for="(turnObj, turnIdx) in reservedCommandList"
:key="turnIdx"
class="turn_pad center"
@click="chooseCommand(turnObj.action)"
>
<span
class="turn_text"
:style="turnObj.style"
v-b-tooltip.hover
:title="turnObj.tooltip"
v-html="turnObj.brief"
></span>
</div>
</div>
</div> </div>
<div class="row gx-0"> <div
<div class="col-2 d-grid"> :class="[
<b-button 'row',
:pressed="searchModeOn" 'controlPad',
@click="toggleSearchCommand()" props.targetIsMe ? 'targetIsMe' : 'targetIsNotMe',
:variant="searchModeOn ? 'info' : 'primary'" ]"
v-b-tooltip.hover >
title="검색 기능을 활성화합니다." <div class="col-3 col-md-12 order-md-last">
><i class="bi bi-search"></i <div class="d-grid mb-1 py-1 only500px bg1 center">
></b-button> <div
</div> :style="{
<div class="col-7"> color: getNpcColor(officer.npcType ?? 0),
<v-multiselect fontSize: '1.2em',
v-model="selectedCommand" }"
:allow-empty="false" >{{ officer.name }}</div>
:options="commandList" <div>{{ officer.officerLevelText }}</div>
:group-select="false" </div>
group-values="values" <div class="row gx-1 gy-1 py-1">
group-label="category" <div class="col-md-4 mx-0 mb-0 mt-1 d-grid">
label="searchText" <div class="alert alert-primary mb-0 center" style="padding: 0.5rem 0">{{ serverNow }}</div>
track-by="value" </div>
open-direction="top"
:show-labels="false" <div class="col-md-4 d-grid">
selectLabel="선택(엔터)" <BButton
selectGroupLabel="" variant="secondary"
selectedLabel="선택됨" @click="isEditMode = !isEditMode"
deselectLabel="해제(엔터)" >{{ isEditMode ? '일반 모드' : '고급 모드' }}</BButton>
deselectGroupLabel="" </div>
placeholder="턴 선택"
:maxHeight="400" <BDropdown class="col-md-4" text="반복">
:searchable="searchModeOn" <BDropdownItem
> v-for="turnIdx in maxPushTurn"
<template v-slot:noResult>검색 결과가 없습니다.</template> :key="turnIdx"
<template v-slot:option="props" @click="repeatNationCommand(turnIdx)"
><!--FIXME: 카테고리--> >
<template v-if="props.option.title"> {{
<span turnIdx
class="compensatePositive" }}
v-if="props.option.compensation > 0" </BDropdownItem>
></span </BDropdown>
<template v-if="isEditMode">
<BDropdown class="col-md-4" left text="범위">
<BDropdownItem @click="queryActionHelper.selectTurn()">해제</BDropdownItem>
<BDropdownItem @click="queryActionHelper.selectAll()">모든턴</BDropdownItem>
<BDropdownItem @click="queryActionHelper.selectStep(0, 2)">홀수턴</BDropdownItem>
<BDropdownItem @click="queryActionHelper.selectStep(1, 2)">짝수턴</BDropdownItem>
<BDropdownDivider></BDropdownDivider>
<BDropdownText v-for="spanIdx in [3, 4, 5, 6, 7]" :key="spanIdx">
{{ spanIdx }} 간격
<br />
<BButtonGroup>
<BButton
class="ignoreMe"
v-for="beginIdx in spanIdx"
:key="beginIdx"
@click="queryActionHelper.selectStep(beginIdx - 1, spanIdx)"
>{{ beginIdx }}</BButton>
</BButtonGroup>
</BDropdownText>
</BDropdown>
<BDropdown class="col-md-4" left text="보관함">
<BDropdownItem
v-for="[actionKey, actions] of storedActions"
:key="actionKey"
@click.self="useStoredAction(actions)"
> >
<span {{ actionKey }}
class="compensateNegative" <BButton @click.prevent="deleteStoredActions(actionKey)" size="sm">삭제</BButton>
v-else-if="props.option.compensation < 0" </BDropdownItem>
></span </BDropdown>
>
<span class="compensateNeutral" v-else></span> <div class="col-md-4 d-grid">
<span :class="[props.option.possible ? '' : 'commandImpossible']"> <BDropdown right text="최근">
{{ props.option.title }} <BDropdownItem
</span> v-for="(action, idx) in recentActions"
</template> :key="idx"
<template v-else-if="props.option.category"> @click="void reserveCommandDirect([[Array.from(selectedTurnList.values()), action]])"
{{ props.option.category }} >
</template> {{
action.brief
}}
</BDropdownItem>
</BDropdown>
</div>
</template> </template>
<template v-slot:singleLabel="props">
{{ props.option.simpleName }} <BDropdown class="col-md-6" split text="당기기" @click="pullNationCommandSingle">
</template> <BDropdownItem
</v-multiselect> v-for="turnIdx in maxPushTurn"
:key="turnIdx"
@click="pushNationCommand(-turnIdx)"
>
{{
turnIdx
}}
</BDropdownItem>
</BDropdown>
<BDropdown class="col-md-6" split text="미루기" @click="pushNationCommandSingle">
<BDropdownItem
v-for="turnIdx in maxPushTurn"
:key="turnIdx"
@click="pushNationCommand(turnIdx)"
>
{{
turnIdx
}}
</BDropdownItem>
</BDropdown>
</div>
</div> </div>
<div class="col-3 d-grid"> <div class="col">
<b-button @click="reserveCommand()" variant="primary">실행</b-button> <div :style="{ position: 'relative' }">
<div
class="commandQuickReserveFormAnchor bg-dark"
:style="{
position: 'absolute',
top: `${basicModeRowHeight * currentQuickReserveTarget + 26}px`,
width: '100%',
zIndex: 9,
}"
>
<CommandSelectForm
:commandList="commandList"
ref="commandQuickReserveForm"
@on-close="chooseQuickReserveCommand($event)"
:hideClose="false"
v-model:activatedCategory="activatedCategory"
class="bg-dark"
style="position:absolute"
/>
</div>
</div>
<div class="commandPad chiefReservedCommand">
<div :class="['commandTable', isEditMode ? 'editMode' : 'singleMode']">
<DragSelect
:style="rowGridStyle"
attribute="turnIdx"
:disabled="!isEditMode"
@dragStart="isDragSingle = true"
@dragDone="
isDragSingle = false;
queryActionHelper.selectTurn(...$event);
"
v-slot="{ selected }"
>
<div
v-for="(turnObj, turnIdx) in reservedCommandList"
:key="turnIdx"
:turnIdx="turnIdx"
class="time_pad center f_tnum"
:style="{
backgroundColor: 'black',
whiteSpace: 'nowrap',
overflow: 'hidden',
color:
isDragSingle && selected.has(`${turnIdx}`) ? 'cyan' : undefined,
}"
>{{ turnObj.time }}</div>
</DragSelect>
<DragSelect
:style="{ ...rowGridStyle, display: isEditMode ? 'grid' : 'none' }"
attribute="turnIdx"
:disabled="!isEditMode"
@dragStart="isDragToggle = true"
@dragDone="
isDragToggle = false;
toggleTurn(...$event);
"
v-slot="{ selected }"
>
<div
v-for="(turnObj, turnIdx) in reservedCommandList"
:key="turnIdx"
:turnIdx="turnIdx"
class="idx_pad center d-grid"
>
<BButton
size="sm"
:variant="
isDragToggle && selected.has(`${turnIdx}`)
? 'light'
: selectedTurnList.has(turnIdx)
? 'info'
: selectedTurnList.size == 0 && prevSelectedTurnList.has(turnIdx)
? 'success'
: 'primary'
"
>{{ turnIdx + 1 }}</BButton>
</div>
</DragSelect>
<div :style="rowGridStyle">
<div
v-for="(turnObj, turnIdx) in reservedCommandList"
:key="turnIdx"
class="turn_pad center"
>
<span
class="turn_text"
:style="turnObj.style"
v-b-tooltip.hover
:title="turnObj.tooltip"
v-html="turnObj.brief"
></span>
</div>
</div>
<div :style="{ ...rowGridStyle, display: isEditMode ? 'none' : 'grid' }">
<div v-for="turnIdx in range(props.maxTurn)" :key="turnIdx" class="action_pad d-grid">
<BButton
:variant="(turnIdx % 2 == 0) ? 'secondary' : 'dark'"
size="sm"
class="simple_action_btn bi bi-pencil"
@click="toggleQuickReserveForm(turnIdx)"
></BButton>
</div>
</div>
</div>
<div style="position:relative">
<CommandSelectForm
:commandList="commandList"
ref="commandSelectForm"
@on-close="chooseCommand($event)"
v-model:activatedCategory="activatedCategory"
class="bg-dark"
:style="{ position: 'absolute', bottom: '0' }"
/>
</div>
<div class="row gx-0" v-if="isEditMode">
<div class="col-5 col-md-6 d-grid">
<BDropdown left variant="info" text="선택한 턴을">
<BDropdownItem @click="clipboardCut">
<i class="bi bi-scissors"></i>&nbsp;잘라내기
</BDropdownItem>
<BDropdownItem @click="clipboardCopy">
<i class="bi bi-files"></i>&nbsp;복사하기
</BDropdownItem>
<BDropdownItem @click="clipboardPaste">
<i class="bi bi-clipboard-fill"></i>&nbsp;붙여넣기
</BDropdownItem>
<BDropdownDivider />
<BDropdownItem @click="setStoredActions">
<i class="bi bi-bookmark-plus-fill"></i>&nbsp;보관하기
</BDropdownItem>
<BDropdownItem @click="subRepeatCommand">
<i class="bi bi-arrow-repeat"></i>&nbsp;반복하기
</BDropdownItem>
<BDropdownDivider />
<BDropdownItem @click="eraseSelectedTurnList">
<i class="bi bi-eraser"></i>&nbsp;비우기
</BDropdownItem>
<BDropdownItem @click="eraseAndPullCommand">
<i class="bi bi-arrow-bar-up"></i>&nbsp;지우고 당기기
</BDropdownItem>
<BDropdownItem @click="pushEmptyCommand">
<i class="bi bi-arrow-bar-down"></i>&nbsp;뒤로 밀기
</BDropdownItem>
<!-- 최근에 실행한 10 -->
</BDropdown>
</div>
<div class="col-7 col-md-6 d-grid">
<BButton
variant="light"
@click="toggleForm($event)"
:style="{ color: 'black' }"
>명령 선택 </BButton>
</div>
</div>
</div>
</div> </div>
</div> </div>
</div> </div>
</template> </template>
<script lang="ts"> <script lang="ts" setup>
import addMinutes from "date-fns/esm/addMinutes"; import addMinutes from "date-fns/esm/addMinutes";
import { stringifyUrl } from "query-string"; import { stringifyUrl } from "query-string";
import { defineComponent, type PropType } from "vue"; import { defineProps, defineEmits, defineExpose, onMounted, ref, watch, type PropType, inject } from "vue";
import { formatTime } from "@util/formatTime"; import { formatTime } from "@util/formatTime";
import { joinYearMonth } from "@util/joinYearMonth"; import { joinYearMonth } from "@util/joinYearMonth";
import { mb_strwidth } from "@util/mb_strwidth"; import { mb_strwidth } from "@util/mb_strwidth";
@@ -154,16 +298,18 @@ import { parseYearMonth } from "@util/parseYearMonth";
import { convertSearch초성 } from "@util/convertSearch초성"; import { convertSearch초성 } from "@util/convertSearch초성";
import VueTypes from "vue-types"; import VueTypes from "vue-types";
import DragSelect from "@/components/DragSelect.vue"; import DragSelect from "@/components/DragSelect.vue";
import { isString } from "lodash"; import { isString, range, trim } from "lodash";
import { SammoAPI } from "@/SammoAPI"; import { SammoAPI } from "@/SammoAPI";
import type { ChiefResponse, CommandItem, TurnObj } from "@/defs"; import type { ChiefResponse, CommandItem, TurnObj } from "@/defs";
import { QueryActionHelper } from "@/util/QueryActionHelper";
import type { Args } from "@/processing/args";
import type { StoredActionsHelper } from "@/util/StoredActionsHelper";
import { getNpcColor } from "@/common_legacy";
import { BButton, BDropdownItem, BDropdownText, BButtonGroup, BDropdownDivider, BDropdown } from "bootstrap-vue-3";
import addMilliseconds from "date-fns/addMilliseconds";
import CommandSelectForm from "@/components/CommandSelectForm.vue";
/*declare const commandList: {
category: string;
values: commandItem[];
}[];*/
type TurnObjWithTime = TurnObj & { type TurnObjWithTime = TurnObj & {
time: string; time: string;
year?: number; year?: number;
@@ -172,295 +318,599 @@ type TurnObjWithTime = TurnObj & {
style?: Record<string, unknown>; style?: Record<string, unknown>;
}; };
const searchModeKey = `sammo_searchModeOn`; const props = defineProps({
maxTurn: VueTypes.integer.isRequired,
maxPushTurn: VueTypes.integer.isRequired,
date: VueTypes.string.isRequired,
year: VueTypes.integer.isRequired,
month: VueTypes.integer.isRequired,
turnTerm: VueTypes.integer.isRequired,
turnTime: VueTypes.string.isRequired,
targetIsMe: VueTypes.bool.isRequired,
export default defineComponent({ timeDiff: VueTypes.number.isRequired,
name: "NationReservedCommand",
components: {
DragSelect
},
props: {
maxTurn: VueTypes.integer.isRequired,
maxPushTurn: VueTypes.integer.isRequired,
date: VueTypes.string.isRequired,
year: VueTypes.integer.isRequired,
month: VueTypes.integer.isRequired,
turnTerm: VueTypes.integer.isRequired,
turnTime: VueTypes.string.isRequired,
selectedTurn: {
type: Object as PropType<Set<number>>,
required: false,
default: () => new Set(),
},
turn: {
type: Array as PropType<TurnObj[]>,
required: true,
},
commandList: {
type: Object as PropType<ChiefResponse['commandList']>,
required: true,
},
},
emits: ["raiseReload", "update:selectedTurn"],
watch: {
date() {
this.triggerUpdateCommandList("date");
},
year() {
this.triggerUpdateCommandList("year");
},
month() {
this.triggerUpdateCommandList("month");
},
turnTime() {
this.triggerUpdateCommandList("turnTime");
},
commandList() {
this.triggerUpdateCommandList("commandList");
},
selectedTurn(val: Set<number>) {
console.log(val);
if (val === this.turnList) {
console.log("pass!");
return;
}
this.turnList.clear();
for (const t of val.values()) {
this.turnList.add(t);
}
},
turnList: {
handler() {
console.log(this.turnList);
this.$emit("update:selectedTurn", this.turnList);
},
deep: true,
},
},
methods: {
triggerUpdateCommandList(type?: string) {
console.log("try update", type);
this.updated = false;
setTimeout(() => {
this.updateCommandList();
}, 1);
},
toggleTurn(...turnList: number[] | string[]) {
for (let turnIdx of turnList) {
if (isString(turnIdx)) {
turnIdx = parseInt(turnIdx);
}
if (this.turnList.has(turnIdx)) {
this.turnList.delete(turnIdx);
} else {
this.turnList.add(turnIdx);
}
}
this.$emit("update:selectedTurn", this.turnList);
},
selectTurn(...turnList: number[] | string[]) {
this.turnList.clear();
for (const turnIdx of turnList) {
if (isString(turnIdx)) {
this.turnList.add(parseInt(turnIdx));
} else {
this.turnList.add(turnIdx);
}
}
this.$emit("update:selectedTurn", this.turnList);
},
updateCommandList() {
if (this.updated) {
return;
}
console.log("do update!");
const reservedCommandList: TurnObjWithTime[] = [];
let yearMonth = joinYearMonth(this.year, this.month);
const turnTime = parseTime(this.turnTime); selectedTurn: {
let nextTurnTime = new Date(turnTime); type: Object as PropType<Set<number>>,
required: false,
default: () => new Set(),
},
turn: {
type: Array as PropType<TurnObj[]>,
required: true,
},
commandList: {
type: Object as PropType<ChiefResponse['commandList']>,
required: true,
},
const autorunLimitYearMonth = this.autorun_limit ?? yearMonth - 1; officer: {
const [autorunLimitYear, autorunLimitMonth] = parseYearMonth( type: Object as PropType<ChiefResponse['chiefList'][0]>,
autorunLimitYearMonth required: true,
}
})
const basicModeRowHeight = 30;
const listReqArgCommand = new Set<string>();
for (const commandCategories of props.commandList) {
if (!commandCategories.values) {
continue;
}
for (const commandObj of commandCategories.values) {
if (!commandObj.reqArg) {
continue;
}
listReqArgCommand.add(commandObj.value);
}
}
const selectedCommand = ref(props.commandList[0].values[0]);
for (const subCategory of props.commandList) {
for (const command of subCategory.values) {
if (command.searchText) {
continue;
}
command.searchText = convertSearch초성(command.simpleName).join("|");
}
}
const invCommandMap: Record<string, CommandItem> = {};
for (const category of props.commandList) {
for (const command of category.values) {
invCommandMap[command.value] = command;
}
}
const rowGridStyle = ref({
display: "grid",
gridTemplateRows: `repeat(${props.maxTurn}, 30px)`,
});
const updated = ref(false);
const isDragSingle = ref(false);
const isDragToggle = ref(false);
const autorun_limit = ref<number | null>(null);
const emit = defineEmits<{
(event: 'raiseReload'): void,
(event: 'update:selectedTurn', value: Set<number>): void,
}>();
function triggerUpdateCommandList(type?: string) {
console.log("try update", type);
updated.value = false;
setTimeout(() => {
updateCommandList();
}, 1);
}
function toggleTurn(...reqTurnList: number[] | string[]) {
for (let turnIdx of reqTurnList) {
if (isString(turnIdx)) {
turnIdx = parseInt(turnIdx);
}
if (selectedTurnList.value.has(turnIdx)) {
selectedTurnList.value.delete(turnIdx);
} else {
selectedTurnList.value.add(turnIdx);
}
}
emit("update:selectedTurn", selectedTurnList.value);
}
function isDropdownChildren(e?: Event): boolean {
if (!e) {
return false;
}
if (!e.target) {
return false;
}
if (
(e.target as HTMLElement).classList.contains("dropdown-item") ||
(e.target as HTMLElement).classList.contains("dropdown-toggle-split") ||
(e.target as HTMLElement).classList.contains("ignoreMe")
) {
return true;
}
return false;
}
async function repeatNationCommand(amount: number) {
try {
await SammoAPI.NationCommand.RepeatCommand({ amount });
} catch (e) {
console.error(e);
alert(`실패했습니다: ${e}`);
return;
}
emit('raiseReload');
}
function pushNationCommandSingle(e: Event) {
//NOTE: split 구현에 버그가 있어서, 수동으로 구분해야함
if (isDropdownChildren(e)) {
return;
}
void pushNationCommand(1);
}
function pullNationCommandSingle(e: Event) {
//NOTE: split 구현에 버그가 있어서, 수동으로 구분해야함
if (isDropdownChildren(e)) {
return;
}
void pushNationCommand(-1);
}
async function pushNationCommand(amount: number) {
try {
await SammoAPI.NationCommand.PushCommand({ amount });
} catch (e) {
console.error(e);
alert(`실패했습니다: ${e}`);
return;
}
emit('raiseReload');
}
const queryActionHelper = new QueryActionHelper(props.maxTurn);
const reservedCommandList = queryActionHelper.reservedCommandList;
const prevSelectedTurnList = queryActionHelper.prevSelectedTurnList;
const selectedTurnList = queryActionHelper.selectedTurnList;
async function reserveCommandDirect(args: [number[], TurnObj][], reload = true): Promise<boolean> {
const query: {
turnList: number[],
action: string,
arg: Args
}[] = [];
for (const [turnList, { action, arg }] of args) {
query.push({
turnList,
action,
arg
});
}
try {
await SammoAPI.NationCommand.ReserveBulkCommand(query);
queryActionHelper.releaseSelectedTurnList();
} catch (e) {
console.error(e);
alert(`실패했습니다: ${e}`);
return false;
}
if (reload) {
emit('raiseReload');
}
return true;
}
function updateCommandList() {
if (updated.value) {
return;
}
console.log("do update!");
const _reservedCommandList: TurnObjWithTime[] = [];
let yearMonth = joinYearMonth(props.year, props.month);
const turnTime = parseTime(props.turnTime);
let nextTurnTime = new Date(turnTime);
const autorunLimitYearMonth = autorun_limit.value ?? yearMonth - 1;
const [autorunLimitYear, autorunLimitMonth] = parseYearMonth(
autorunLimitYearMonth
);
for (const obj of props.turn) {
const [year, month] = parseYearMonth(yearMonth);
let tooltip: string[] = [];
let style: Record<string, unknown> = {};
const brief = obj.brief;
if (yearMonth <= autorunLimitYearMonth) {
if (obj.brief == "휴식") {
obj.brief = "휴식<small>(자율 행동)</small>";
}
style.color = "#aaffff";
tooltip.push(
`자율 행동 기간: ${autorunLimitYear}${autorunLimitMonth}월까지`
); );
for (const obj of this.turn) {
const [year, month] = parseYearMonth(yearMonth);
let tooltip: string[] = [];
let style: Record<string, unknown> = {};
const brief = obj.brief;
if (yearMonth <= autorunLimitYearMonth) {
if (obj.brief == "휴식") {
obj.brief = "휴식<small>(자율 행동)</small>";
}
style.color = "#aaffff";
tooltip.push(
`자율 행동 기간: ${autorunLimitYear}${autorunLimitMonth}월까지`
);
}
if (mb_strwidth(brief) > 22) {
tooltip.push(brief);
}
reservedCommandList.push({
...obj,
year,
month,
time: formatTime(
nextTurnTime,
this.turnTerm >= 5 ? "HH:mm" : "mm:ss"
),
tooltip: tooltip.length == 0 ? undefined : tooltip.join("\n"),
style,
});
yearMonth += 1;
nextTurnTime = addMinutes(nextTurnTime, this.turnTerm);
}
this.reservedCommandList = reservedCommandList;
const serverNowObj = parseTime(this.date);
const clientNowObj = new Date();
const timeDiff = serverNowObj.getTime() - clientNowObj.getTime();
this.timeDiff = timeDiff;
this.updated = true;
},
async reserveCommand() {
let turnList: number[];
if (this.turnList.size == 0) {
turnList = Array.from(this.prevTurnList.values());
} else {
turnList = Array.from(this.turnList.values());
}
if (turnList.length == 0) {
turnList.push(0);
}
const commandName = this.selectedCommand.value;
if (this.listReqArgCommand.has(commandName)) {
document.location.href = stringifyUrl({
url: "v_processing.php",
query: {
command: commandName,
turnList: turnList.join("_"),
is_chief: true,
},
});
return;
}
try {
await SammoAPI.NationCommand.ReserveCommand({
turnList,
action: commandName,
});
if (this.turnList.size > 0) {
this.prevTurnList.clear();
for (const v of this.turnList) {
this.prevTurnList.add(v);
}
this.turnList.clear();
}
} catch (e) {
console.error(e);
alert(`실패했습니다: ${e}`);
return;
}
this.$emit("raiseReload");
},
toggleSearchCommand() {
const searchModeOn = !this.searchModeOn;
this.searchModeOn = searchModeOn;
localStorage.setItem(searchModeKey, searchModeOn ? "1" : "0");
},
chooseCommand(val: string){
this.selectedCommand = this.invCommandMap[val];
},
},
data() {
const serverNowObj = parseTime(this.date);
const clientNowObj = new Date();
const timeDiff = serverNowObj.getTime() - clientNowObj.getTime();
const listReqArgCommand = new Set<string>();
for (const commandCategories of this.commandList) {
if (!commandCategories.values) {
continue;
}
for (const commandObj of commandCategories.values) {
if (!commandObj.reqArg) {
continue;
}
listReqArgCommand.add(commandObj.value);
}
} }
const selectedCommand = this.commandList[0].values[0]; if (mb_strwidth(brief) > 22) {
for (const subCategory of this.commandList) { tooltip.push(brief);
for (const command of subCategory.values) {
if (command.searchText) {
continue;
}
command.searchText = convertSearch초성(command.simpleName).join("|");
}
} }
const invCommandMap: Record<string, CommandItem> = {}; _reservedCommandList.push({
for(const category of this.commandList){ ...obj,
for(const command of category.values){ year,
invCommandMap[command.value] = command; month,
} time: formatTime(
} nextTurnTime,
props.turnTerm >= 5 ? "HH:mm" : "mm:ss"
const searchModeOn = (localStorage.getItem(searchModeKey) ?? "0") != "0"; ),
tooltip: tooltip.length == 0 ? undefined : tooltip.join("\n"),
const emptyTurn: TurnObjWithTime[] = Array.from<TurnObjWithTime>({ style,
length: this.maxTurn,
}).fill({
arg: {},
brief: "",
action: "",
year: undefined,
month: undefined,
time: "",
}); });
const prevTurnList = new Set([0]); yearMonth += 1;
nextTurnTime = addMinutes(nextTurnTime, props.turnTerm);
}
reservedCommandList.value = _reservedCommandList;
updated.value = true;
}
const rowGridStyle = { async function reserveCommand() {
display: "grid", const reqTurnList = queryActionHelper.getSelectedTurnList();
gridTemplateRows: `repeat(${this.maxTurn}, 30px)`, const commandName = selectedCommand.value.value;
};
return { if (listReqArgCommand.has(commandName)) {
updated: false, document.location.href = stringifyUrl({
listReqArgCommand, url: "v_processing.php",
serverNow: formatTime(serverNowObj, "HH:mm:ss"), query: {
timeDiff, command: commandName,
prevTurnList, turnList: reqTurnList.join("_"),
turnList: this.selectedTurn, is_chief: true,
selectedCommand, },
reservedCommandList: emptyTurn, });
autorun_limit: null as null | number, return;
searchModeOn, }
rowGridStyle,
isDragSingle: false, try {
isDragToggle: false, await SammoAPI.NationCommand.ReserveCommand({
invCommandMap, turnList: reqTurnList,
}; action: commandName,
}, });
mounted() {
this.updateCommandList(); queryActionHelper.releaseSelectedTurnList();
}, } catch (e) {
console.error(e);
alert(`실패했습니다: ${e}`);
return;
}
emit("raiseReload");
}
function chooseCommand(val?: string) {
if (val === undefined) {
return;
}
selectedCommand.value = invCommandMap[val];
void reserveCommand();
}
const emptyTurnObj: TurnObj = { action: '휴식', brief: '휴식', arg: {} };
const storedActionsHelper = inject('storedNationActionsHelper') as StoredActionsHelper;
const recentActions = storedActionsHelper.recentActions;
const storedActions = storedActionsHelper.storedActions;
const activatedCategory = storedActionsHelper.activatedCategory;
async function eraseSelectedTurnList(releaseSelect = true): Promise<boolean> {
const result = await reserveCommandDirect([[
queryActionHelper.getSelectedTurnList(),
emptyTurnObj
]]);
if (releaseSelect) {
queryActionHelper.releaseSelectedTurnList();
}
return result;
}
const clipboard = storedActionsHelper.clipboard;
async function clipboardCut(releaseSelect = true) {
clipboardCopy(false);
return eraseSelectedTurnList(releaseSelect);
}
function clipboardCopy(releaseSelect = true) {
clipboard.value = queryActionHelper.extractQueryActions();
if (releaseSelect) {
queryActionHelper.releaseSelectedTurnList();
}
}
async function clipboardPaste(releaseSelect = true) {
const rawActions = clipboard.value;
if (rawActions === undefined) {
return;
}
const actions = queryActionHelper.amplifyQueryActions(rawActions, queryActionHelper.getSelectedTurnList());
if (actions.length === 0) {
return;
}
const result = await reserveCommandDirect(actions);
if (releaseSelect) {
queryActionHelper.releaseSelectedTurnList();
}
return result;
}
async function subRepeatCommand(releaseSelect = true): Promise<boolean> {
const reqTurnList = queryActionHelper.getSelectedTurnList();
const selectedMinTurnIdx = reqTurnList[0];
const selectedMaxTurnIdx = reqTurnList[reqTurnList.length - 1];
const queryLength = selectedMaxTurnIdx - selectedMinTurnIdx + 1;
const rawActions = queryActionHelper.extractQueryActions();
const actions = queryActionHelper.amplifyQueryActions(rawActions, range(selectedMinTurnIdx, props.maxTurn, queryLength));
const result = await reserveCommandDirect(actions);
if (releaseSelect) {
queryActionHelper.releaseSelectedTurnList();
}
return result;
}
async function eraseAndPullCommand(releaseSelect = true): Promise<boolean> {
const reqTurnList = queryActionHelper.getSelectedTurnList();
const selectedMinTurnIdx = reqTurnList[0];
const selectedMaxTurnIdx = reqTurnList[reqTurnList.length - 1];
const queryLength = selectedMaxTurnIdx - selectedMinTurnIdx + 1;
if (selectedMinTurnIdx === 0) {
await pushNationCommand(-queryLength);
return true;
}
if (selectedMinTurnIdx + queryLength == props.maxTurn) {
return eraseSelectedTurnList(releaseSelect);
}
const actions: [number[], TurnObj][] = [];
const emptyTurnList: number[] = [];
for (const srcTurnIdx of range(selectedMinTurnIdx + queryLength, props.maxTurn)) {
const rawAction = reservedCommandList.value[srcTurnIdx];
if (rawAction.action == emptyTurnObj.action) {
emptyTurnList.push(srcTurnIdx - queryLength);
continue;
}
actions.push([[srcTurnIdx - queryLength], {
action: rawAction.action,
arg: rawAction.arg,
brief: rawAction.brief
}]);
}
emptyTurnList.push(...range(props.maxTurn - queryLength, props.maxTurn));
actions.push([emptyTurnList, emptyTurnObj]);
const result = await reserveCommandDirect(actions);
if (releaseSelect) {
queryActionHelper.releaseSelectedTurnList();
}
return result;
}
async function pushEmptyCommand(releaseSelect = true): Promise<boolean> {
const reqTurnList = queryActionHelper.getSelectedTurnList();
const selectedMinTurnIdx = reqTurnList[0];
const selectedMaxTurnIdx = reqTurnList[reqTurnList.length - 1];
const queryLength = selectedMaxTurnIdx - selectedMinTurnIdx + 1;
if (selectedMinTurnIdx === 0) {
await pushNationCommand(queryLength);
return true;
}
if (selectedMaxTurnIdx == props.maxTurn) {
return eraseSelectedTurnList(releaseSelect);
}
const actions: [number[], TurnObj][] = [];
const emptyTurnList: number[] = [];
for (const srcTurnIdx of range(selectedMinTurnIdx, props.maxTurn - queryLength)) {
const rawAction = reservedCommandList.value[srcTurnIdx];
if (rawAction.action == emptyTurnObj.action) {
emptyTurnList.push(srcTurnIdx + queryLength);
continue;
}
actions.push([[srcTurnIdx + queryLength], {
action: rawAction.action,
arg: rawAction.arg,
brief: rawAction.brief
}]);
}
emptyTurnList.push(...range(selectedMinTurnIdx, selectedMinTurnIdx + queryLength));
actions.push([emptyTurnList, emptyTurnObj]);
const result = await reserveCommandDirect(actions);
if (releaseSelect) {
queryActionHelper.releaseSelectedTurnList();
}
return result;
}
function setStoredActions() {
const actions = queryActionHelper.extractQueryActions();
const turnBrief = new Map<number, string>();
for (const [subTurnList, action] of actions) {
const actionName = action.action.split('_');
const actionShortName = actionName.length == 1 ? actionName[0] : actionName[1];
for (const turnIdx of subTurnList) {
turnBrief.set(turnIdx, actionShortName[0]);
}
}
const turnBriefStr = Array.from(turnBrief.entries())
.sort(([turnA], [turnB]) => turnA - turnB)
.map(([, action]) => action)
.join('');
const nickName = trim(prompt('선택한 턴들의 별명을 지어주세요', turnBriefStr) ?? '');
if (nickName == '') {
return;
}
storedActionsHelper.setStoredActions(nickName, actions);
queryActionHelper.releaseSelectedTurnList();
}
function deleteStoredActions(actionKey: string) {
storedActionsHelper.deleteStoredActions(actionKey)
}
async function useStoredAction(rawActions: [number[], TurnObj][]) {
const reqTurnList = queryActionHelper.getSelectedTurnList();
const actions = queryActionHelper.amplifyQueryActions(rawActions, reqTurnList)
const result = await reserveCommandDirect(actions);
queryActionHelper.releaseSelectedTurnList();
return result;
}
function getQueryActionHelper(): QueryActionHelper {
return queryActionHelper;
}
function getStoredActionHeler(): StoredActionsHelper {
return storedActionsHelper;
}
defineExpose({
useStoredAction,
deleteStoredActions,
clipboardCut,
clipboardCopy,
clipboardPaste,
getQueryActionHelper,
getStoredActionHeler,
})
watch(() => props.date, () => {
triggerUpdateCommandList("date");
})
watch(() => props.year, () => {
triggerUpdateCommandList("year");
})
watch(() => props.month, () => {
triggerUpdateCommandList("month");
})
watch(() => props.turnTime, () => {
triggerUpdateCommandList("turnTime");
})
watch(() => props.commandList, () => {
triggerUpdateCommandList("commandList");
})
watch(() => props.selectedTurn, (val: Set<number>) => {
console.log(val);
if (val === selectedTurnList.value) {
console.log("pass!");
return;
}
selectedTurnList.value.clear();
for (const t of val.values()) {
selectedTurnList.value.add(t);
}
})
watch(selectedTurnList, () => {
console.log(selectedTurnList.value);
emit("update:selectedTurn", selectedTurnList.value);
})
const commandQuickReserveForm = ref<InstanceType<typeof CommandSelectForm> | null>(null);
const commandSelectForm = ref<InstanceType<typeof CommandSelectForm> | null>(null);
const currentQuickReserveTarget = ref(-1);
function chooseQuickReserveCommand(val?: string) {
if (!val) {
return;
}
selectedCommand.value = invCommandMap[val];
selectedTurnList.value.clear();
selectedTurnList.value.add(currentQuickReserveTarget.value);
void reserveCommand();
}
function toggleQuickReserveForm(turnIdx: number) {
if (turnIdx == currentQuickReserveTarget.value) {
commandQuickReserveForm.value?.toggle();
return;
}
currentQuickReserveTarget.value = turnIdx;
commandQuickReserveForm.value?.show();
}
const isEditMode = storedActionsHelper.isEditMode;
watch(isEditMode, newEditMode => {
if (newEditMode) {
commandQuickReserveForm.value?.close();
currentQuickReserveTarget.value = -1;
}
else {
commandSelectForm.value?.close();
}
}); });
function toggleForm($event: Event): void {
$event.preventDefault();
const form = commandSelectForm.value;
if (!form) {
return;
}
form.toggle();
}
const serverNow = ref(formatTime(new Date(), "HH:mm:ss"));
function updateNow() {
const serverNowObj = addMilliseconds(new Date(), props.timeDiff);
serverNow.value = formatTime(serverNowObj, "HH:mm:ss");
setTimeout(() => {
updateNow();
}, 1000 - serverNowObj.getMilliseconds());
}
setTimeout(() => {
updateNow();
}, 500);
onMounted(() => {
updateCommandList();
})
</script> </script>
<style lang="scss"> <style lang="scss">
@import "@scss/common/break_500px.scss"; @import "@scss/common/break_500px.scss";
@@ -470,13 +920,20 @@ export default defineComponent({
.chiefReservedCommand { .chiefReservedCommand {
background-color: $gray-900; background-color: $gray-900;
.commandTable { .commandTable.editMode {
width: 100%; width: 100%;
display: grid; display: grid;
grid-template-columns: minmax(39.67px, 1fr) minmax(28px, 1fr) 5fr; grid-template-columns: minmax(39.67px, 1fr) minmax(28px, 1fr) 5fr;
//30, 70, 37.65, 160 //30, 70, 37.65, 160
} }
.commandTable.singleMode {
width: 100%;
display: grid;
grid-template-columns: minmax(39.67px, 1fr) 5fr minmax(28px, 1fr);
//30, 70, 160, 37.65
}
@include media-1000px { @include media-1000px {
.turn_pad { .turn_pad {
overflow: hidden; overflow: hidden;
+60 -40
View File
@@ -1,28 +1,41 @@
<template> <template>
<teleport :to="anchor"> <div v-if="showForm" class="my-1">
<div v-if="showForm" class="my-1"> <div class="commandCategory row gx-0 gy-1">
<div class="commandCategory row gx-0 gy-1"> <div
<div class="categoryItem col-4 d-grid"
class="categoryItem col-4 d-grid" v-for="[categoryKey, { deco: categoryDeco }] of commandList"
v-for="[categoryKey, { deco: categoryDeco }] of commandList" :key="categoryKey"
:key="categoryKey" >
> <BButton
<BButton variant="success"
variant="success" @click="chosenCategory = categoryKey"
@click="chosenCategory = categoryKey" :active="chosenCategory == categoryKey"
:active="chosenCategory == categoryKey" >{{ categoryDeco.altName ?? categoryDeco.name }}</BButton>
>{{ categoryDeco.altName ?? categoryDeco.name }}</BButton>
</div>
</div> </div>
<div class="commandList row gx-1 gy-1 my-1"> </div>
<div
class="commandList my-1"
:style="{
display: 'grid',
alignItems: 'self-start',
}"
>
<div
class="row gx-1 gy-1"
v-for="[category, { values }] of commandList"
:key="category"
:style="{ visibility: category == chosenCategory ? 'visible' : 'hidden', gridRow: '1', gridColumn: '1' }"
>
<div <div
class="col-6 d-grid" class="col-6 d-grid"
v-for="commandItem of chosenSubList" v-for="commandItem of values"
:key="commandItem.value" :key="commandItem.value"
@click="close(commandItem.value)" @click="close(commandItem.value)"
> >
<div class="commandItem"> <div class="commandItem">
<p :class="['center', 'my-0', commandItem.possible ? '' : 'commandImpossible']"> <p
:class="['center', 'my-0', commandItem.possible ? '' : 'commandImpossible']"
>
{{ commandItem.simpleName }} {{ commandItem.simpleName }}
<span <span
class="compensatePositive" class="compensatePositive"
@@ -43,35 +56,19 @@
</div> </div>
</div> </div>
</div> </div>
<div v-if="!hideClose" class="commandBottom row mt-1 mb-1"> </div>
<div class="offset-8 col-4 d-grid"> <div v-if="!hideClose" class="commandBottom row mt-1 mb-1">
<BButton @click="close()">닫기</BButton> <div class="offset-8 col-4 d-grid">
</div> <BButton @click="close()">닫기</BButton>
</div> </div>
</div> </div>
</teleport> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
/*
<template v-if="props.option.title">
<span class="compensatePositive" v-if="props.option.compensation > 0">▲</span>
<span class="compensateNegative" v-else-if="props.option.compensation < 0">▼</span>
<span class="compensateNeutral" v-else></span>
<span
:class="[props.option.possible ? '' : 'commandImpossible']"
>{{ props.option.title }}</span>
</template>
<template v-else-if="props.option.category">{{ props.option.category }}</template>
</template>
<template v-slot:singleLabel="props">{{ props.option.simpleName }}</template>
*/
import type { CommandItem } from "@/defs"; import type { CommandItem } from "@/defs";
import { BButton } from "bootstrap-vue-3"; import { BButton } from "bootstrap-vue-3";
import { ref, defineProps, defineEmits, defineExpose, type PropType, watch, onMounted } from "vue"; import { ref, defineProps, defineEmits, defineExpose, type PropType, watch, onMounted } from "vue";
const chosenCategory = ref<string>("-");
const chosenSubList = ref<CommandItem[]>([]);
interface CategoryDecoration { interface CategoryDecoration {
name: string, name: string,
altName?: string, altName?: string,
@@ -101,9 +98,23 @@ const props = defineProps({
type: Boolean, type: Boolean,
required: false, required: false,
default: true, default: true,
},
activatedCategory: {
type: String,
required: false,
default: "",
} }
}) })
const chosenCategory = ref<string>('-');
const chosenSubList = ref<CommandItem[]>([]);
const categories = new Set(props.commandList.map(({ category }) => category));
watch(() => props.activatedCategory, (newValue) => {
chosenCategory.value = newValue;
})
const showForm = ref(false); const showForm = ref(false);
function convCategoryDeco(category: string): CategoryDecoration { function convCategoryDeco(category: string): CategoryDecoration {
@@ -140,17 +151,25 @@ watch(() => props.commandList, updateCommandList);
updateCommandList(props.commandList); updateCommandList(props.commandList);
watch(chosenCategory, (category) => { watch(chosenCategory, (category) => {
console.log('sel', category);
const itemInfo = commandList.value?.get(category); const itemInfo = commandList.value?.get(category);
if (itemInfo === undefined) { if (itemInfo === undefined) {
console.error(`category 없음: ${category}`); console.error(`category 없음: ${category}`);
return; return;
} }
chosenSubList.value = itemInfo.values; chosenSubList.value = itemInfo.values;
if (props.activatedCategory !== category) {
emits('update:activatedCategory', category);
}
}); });
onMounted(() => { onMounted(() => {
chosenCategory.value = props.commandList[0].category; if (!categories.has(props.activatedCategory)) {
chosenCategory.value = props.commandList[0].category;
}
else {
chosenCategory.value = props.activatedCategory;
}
}); });
function show(): void { function show(): void {
@@ -171,6 +190,7 @@ function close(category?: string): void {
const emits = defineEmits<{ const emits = defineEmits<{
(event: 'onClose', command?: string): void, (event: 'onClose', command?: string): void,
(event: 'update:activatedCategory', category: string): void,
}>(); }>();
defineExpose({ defineExpose({
+1 -1
View File
@@ -156,7 +156,7 @@ export default defineComponent({
document.addEventListener("touchmove", touchMove); document.addEventListener("touchmove", touchMove);
box.style.top = start.y + "px"; box.style.top = start.y + "px";
box.style.left = start.x + "px"; box.style.left = start.x + "px";
uContainer.prepend(box); uContainer.append(box);
intersection(); intersection();
isMine = true; isMine = true;
emit("dragStart"); emit("dragStart");
+173
View File
@@ -0,0 +1,173 @@
import type { TurnObj } from "@/defs";
import { clone, isString, range } from "lodash";
import { ref, type Ref } from "vue";
import { unwrap } from "./unwrap";
type TurnObjWithTime = TurnObj & {
time: string;
year?: number;
month?: number;
tooltip?: string;
style?: Record<string, unknown>;
};
export const getEmptyTurn = (maxTurn: number): TurnObjWithTime[] => Array.from<TurnObjWithTime>({
length: maxTurn,
}).fill({
arg: {},
brief: "",
action: "",
year: undefined,
month: undefined,
time: "",
});
export class QueryActionHelper {
public readonly reservedCommandList: Ref<TurnObjWithTime[]>;
public readonly selectedTurnList: Ref<Set<number>>;
public readonly prevSelectedTurnList: Ref<Set<number>>;
constructor(
protected maxTurn: number,
) {
this.reservedCommandList = ref(getEmptyTurn(maxTurn));
this.selectedTurnList = ref(new Set());
this.prevSelectedTurnList = ref(new Set([0]));
}
toggleTurn(...reqTurnList: number[] | string[]) {
for (let turnIdx of reqTurnList) {
if (isString(turnIdx)) {
turnIdx = parseInt(turnIdx);
}
if (this.selectedTurnList.value.has(turnIdx)) {
this.selectedTurnList.value.delete(turnIdx);
} else {
this.selectedTurnList.value.add(turnIdx);
}
}
}
selectTurn(...reqTurnList: number[] | string[]) {
this.selectedTurnList.value.clear();
for (const turnIdx of reqTurnList) {
if (isString(turnIdx)) {
this.selectedTurnList.value.add(parseInt(turnIdx));
} else {
this.selectedTurnList.value.add(turnIdx);
}
}
}
selectStep(begin: number, step: number) {
this.selectedTurnList.value.clear();
for (const idx of range(0, this.maxTurn)) {
if ((idx - begin) % step == 0) {
this.selectedTurnList.value.add(idx);
}
}
}
selectAll() {
for (let i = 0; i < this.maxTurn; i++) {
this.selectedTurnList.value.add(i);
}
}
getSelectedTurnList(useSort = true): number[] {
let result: number[];
if (this.selectedTurnList.value.size) {
result = Array.from(this.selectedTurnList.value);
}
else if (this.prevSelectedTurnList.value.size) {
result = Array.from(this.prevSelectedTurnList.value);
}
else {
return [0];
}
if (useSort) {
return result.sort((a, b) => a - b);
}
return result;
}
releaseSelectedTurnList() {
if (this.selectedTurnList.value.size > 0) {
this.prevSelectedTurnList.value.clear();
for (const v of this.selectedTurnList.value) {
this.prevSelectedTurnList.value.add(v);
}
this.selectedTurnList.value.clear();
}
}
extractQueryActions(): [number[], TurnObj][] {
const reqTurnList = this.getSelectedTurnList();
const selectedMinTurnIdx = unwrap(Math.min(...reqTurnList));
const buffer = new Map<string, [number[], TurnObj]>();
for (const rawTurnIdx of reqTurnList) {
const turnIdx = rawTurnIdx - selectedMinTurnIdx;
const rawAction = this.reservedCommandList.value[rawTurnIdx]
const actionStr = JSON.stringify([rawAction.action, rawAction.arg]);
if (buffer.has(actionStr)) {
const items = unwrap(buffer.get(actionStr));
items[0].push(turnIdx);
}
else {
buffer.set(actionStr, [[turnIdx], {
action: rawAction.action,
arg: clone(rawAction.arg),
brief: rawAction.brief
}])
}
}
return Array.from(buffer.values());
}
amplifyQueryActions(rawActions: [number[], TurnObj][], reqTurnList: number[]): [number[], TurnObj][] {
if (reqTurnList.length < 1) {
return [];
}
let minQueryIdx = this.maxTurn;
let maxQueryIdx = 0;
for (const [turnList] of rawActions) {
for (const turnIdx of turnList) {
minQueryIdx = Math.min(minQueryIdx, turnIdx);
maxQueryIdx = Math.max(maxQueryIdx, turnIdx);
}
}
const queryLength = maxQueryIdx - minQueryIdx + 1;
const queryTurnList: number[] = [reqTurnList[0]];
for (const reqTurnIdx of reqTurnList) {
const last = queryTurnList[queryTurnList.length - 1];
if (reqTurnIdx < last + queryLength) {
continue;
}
queryTurnList.push(reqTurnIdx);
}
const actions: [number[], TurnObj][] = [];
for (const [baseTurnList, action] of rawActions) {
const subTurnList: number[] = [];
for (const baseTurnIdx of baseTurnList) {
for (const queryTurnIdx of queryTurnList) {
const targetTurn = baseTurnIdx + queryTurnIdx;
if (targetTurn >= this.maxTurn) {
continue;
}
subTurnList.push(baseTurnIdx + queryTurnIdx);
}
}
if (subTurnList.length == 0) {
continue;
}
actions.push([subTurnList, action]);
}
return actions;
}
}
+36 -3
View File
@@ -1,18 +1,51 @@
import type { TurnObj } from '@/defs'; import type { TurnObj } from '@/defs';
import { ref } from 'vue'; import { ref, watch } from 'vue';
export class StoredActionsHelper { export class StoredActionsHelper {
public readonly recentActions = ref<TurnObj[]>([]); public readonly recentActions = ref<TurnObj[]>([]);
public readonly storedActions = ref(new Map<string, [number[], TurnObj][]>()); public readonly storedActions = ref(new Map<string, [number[], TurnObj][]>());
public readonly clipboard = ref<[number[], TurnObj][] | undefined>(undefined);
public readonly activatedCategory = ref<string>("");
public readonly isEditMode = ref(false);
public readonly recentActionsKey: string; public readonly recentActionsKey: string;
public readonly storedActionsKey: string; public readonly storedActionsKey: string;
public readonly clipboardKey: string;
public readonly activatedCategoryKey: string;
public readonly editModeKey: string;
constructor(protected serverNick: string, protected type: 'general' | 'nation', protected mapName: string, protected unitSet: string, protected maxRecent = 10) { constructor(protected serverNick: string, protected type: 'general' | 'nation', protected mapName: string, protected unitSet: string, protected maxRecent = 10) {
this.recentActionsKey = `${serverNick}_${mapName}_${unitSet}_${type}RecentActions`; const typeKey = `${serverNick}_${mapName}_${unitSet}_${type}`;
this.storedActionsKey = `${serverNick}_${mapName}_${unitSet}_${type}StoredActions`; this.recentActionsKey = `${typeKey}RecentActions`;
this.storedActionsKey = `${typeKey}StoredActions`;
this.clipboardKey = `${typeKey}Clipboard`;
this.activatedCategoryKey = `${typeKey}ActivatedCategory`;
this.editModeKey = `${serverNick}_${type}_isEditMode`;
this.loadRecentActions(); this.loadRecentActions();
this.loadStoredActions(); this.loadStoredActions();
const rawClipboard = localStorage.getItem(this.clipboardKey);
if (rawClipboard !== null) {
this.clipboard.value = JSON.parse(rawClipboard);
}
watch(this.clipboard, (newValue) => {
localStorage.setItem(this.clipboardKey, JSON.stringify(newValue));
});
const rawActivatedCategory = localStorage.getItem(this.activatedCategoryKey);
if (rawActivatedCategory !== null) {
this.activatedCategory.value = JSON.parse(rawActivatedCategory);
}
watch(this.activatedCategory, (newValue) => {
localStorage.setItem(this.activatedCategoryKey, JSON.stringify(newValue));
});
this.isEditMode.value = localStorage.getItem(this.editModeKey) === '1';
watch(this.isEditMode, (newValue) => {
localStorage.setItem(this.editModeKey, newValue ? '1' : '0')
})
} }
loadRecentActions() { loadRecentActions() {
+5
View File
@@ -24,6 +24,11 @@ $generalObj = General::createGeneralObjFromDB($session->generalID);
<?= WebUtil::printStaticValues([ <?= WebUtil::printStaticValues([
'maxChiefTurn'=>GameConst::$maxChiefTurn, 'maxChiefTurn'=>GameConst::$maxChiefTurn,
'generalID'=>$generalObj->getID(), 'generalID'=>$generalObj->getID(),
'staticValues'=>[
'serverNick' => DB::prefix(),
'mapName' => GameConst::$mapName,
'unitSet' => GameConst::$unitSet,
]
])?> ])?>
<?= WebUtil::printDist('vue', 'v_chiefCenter', true) ?> <?= WebUtil::printDist('vue', 'v_chiefCenter', true) ?>
</head> </head>