Compare commits

...
101 Commits
Author SHA1 Message Date
Hide_D 188b57ed7a 랜덤 임관 버그 수정 2020-06-05 18:13:21 +09:00
Hide_D c8620390ac 중립 커맨드 2020-06-05 02:25:44 +09:00
Hide_D b3f8ed2335 지도 기반 선택 버그 수정 2020-06-05 01:14:49 +09:00
Hide_D 54bf504eb4 명령 입력턴에 select2 적용 2020-06-05 01:02:33 +09:00
Hide_D c6f3bf856b select2 업그레이드 2020-06-04 23:21:47 +09:00
Hide_D 8b33a7926e 오호 장군 수정 2020-06-04 21:31:26 +09:00
Hide_D a38cb90cbf 천지비급 시나리오를 설명에 맞게 수정 2020-06-03 22:17:22 +09:00
Hide_D 1500e8e54f 서버가 닫힌 경우 리다이렉트하도록 2020-06-03 01:51:31 +09:00
Hide_D 94fd8d5e9d 세력도시 암행부 연동 버그 수정 2020-06-02 01:24:25 +09:00
Hide_D 373e0a2155 버그 수정 시도2 2020-06-02 01:06:00 +09:00
Hide_D 267298f341 사령부 공백이어도 사령턴은 보임 2020-06-02 00:24:44 +09:00
Hide_D 359d46e94d 천지비급 디버그 풀기 2020-06-02 00:08:52 +09:00
Hide_D 11f5540099 composer 반영 2020-06-01 21:14:50 +09:00
Hide_D 680e1afcfd 버그 수정 2020-06-01 02:34:56 +09:00
Hide_D e4322e60cc 환약 사용 기준 추가 2020-06-01 02:31:46 +09:00
Hide_D 82f2eecfe8 내 설정 페이지 동작 방식 일단 수정 2020-06-01 02:17:20 +09:00
Hide_D 3e3c3c559d 소모성 아이템 소비 2020-05-31 23:11:17 +09:00
Hide_D 65f5e8e964 setResultTurn 버그 수정 2020-05-31 17:21:51 +09:00
Hide_D c5fbe93890 버그 수정 2020-05-31 04:43:15 +09:00
Hide_D 307d8b6165 버그 수정 2020-05-31 04:42:11 +09:00
Hide_D bf08eb2f8b 버그 수정 2020-05-31 04:32:46 +09:00
Hide_D a569c1dfaf 버그 수정 2020-05-31 04:25:36 +09:00
Hide_D e48db0d231 장수 목록 json 버그 수정 2020-05-31 04:12:42 +09:00
Hide_D 1a5b5dbb45 격노 1회만 2020-05-31 01:47:44 +09:00
Hide_D 56f21cabe5 격노 발동은 1회만 2020-05-31 01:44:44 +09:00
Hide_D 7ac5afe05b 이벤트 특기 버그 수정 2020-05-30 22:50:48 +09:00
Hide_D b3db97f4a8 이중특기 테스트 2020-05-30 16:31:03 +09:00
Hide_D 6d1a06a9d9 긴급 쌀 시 병량패퇴를 당하지 않기 위해 강제 회피 2020-05-30 04:48:33 +09:00
Hide_D 088643df6c 워프 버그 수정 2020-05-30 04:41:47 +09:00
Hide_D fc00a0a363 의병모집, 소형b 초기 m장, 작위보상금쌀
의병모집 -> 초기 금쌀 1000
작위보상 -> 작위에 따라 금쌀*1000
소형b -> 초기 m장 10 추가
2020-05-30 04:36:42 +09:00
Hide_D 7a48fdd246 멸망시 임관 확률을 변경 가능하도록 설정 2020-05-30 03:18:23 +09:00
Hide_D 89be493882 인재탐색 변경. 영입 불가, 재야 가능 2020-05-30 03:09:48 +09:00
Hide_D 5947abf83d 대인 사살, 점령률 추가 2020-05-30 03:05:03 +09:00
Hide_D 962db6821f 대인살상률, 점령수 준비 2020-05-30 02:29:46 +09:00
Hide_D f6a3df7858 수비 켬끔 다양화 2020-05-30 02:08:16 +09:00
Hide_D 090aaed3f4 숙련 전환 효율 향상 2020-05-30 01:56:31 +09:00
Hide_D 71cb5aa9e4 성벽에 닳는 내정을 1/2 2020-05-29 19:16:24 +09:00
Hide_D 043b29ef33 격노 회피 시도 캔슬 2020-05-28 01:39:14 +09:00
Hide_D d81cf4aec3 소집해제 위치 이동 2020-05-28 01:33:27 +09:00
Hide_D 7cb46eeb82 Merge branch 'devel' of ssh://storage.hided.net:2525/devsam/core into devel 2020-05-26 21:44:22 +09:00
Hide_D c3b4d54414 내정 워프 버그 수정 2020-05-26 21:44:03 +09:00
Hide_D 8b9acf2d3d 실패 메시지 수정 2020-05-26 10:44:55 +09:00
Hide_D 08548181ed 첩보 가격이 저렴한 버그 수정 2020-05-26 00:47:42 +09:00
Hide_D 45f883c98b 징병창 병력 키보드 입력 버그 2020-05-25 23:28:16 +09:00
Hide_D 5f39229e47 치안강화 만땅 채우기 2020-05-24 22:52:56 +09:00
Hide_D 8c5bdc2a4b 사망시 수명 계산 버그 2020-05-24 13:41:52 +09:00
Hide_D 7b7602bce2 사령부 확실히 엔터 2020-05-23 17:21:07 +09:00
Hide_D a145792fac 헌납 비율 수정 2020-05-23 16:35:33 +09:00
Hide_D 667a550f4c 조사 수정 2020-05-23 16:30:10 +09:00
Hide_D 53e1ad8991 헌납 메시지 수정 2020-05-23 16:28:21 +09:00
Hide_D 429c949d1f AI 치안 버그 수정 2020-05-23 16:24:18 +09:00
Hide_D 1548577d65 주민선정을 매우 열심히 합니다. 2020-05-23 15:33:10 +09:00
Hide_D 82e59b297f 증축 버그 수정 2020-05-23 11:12:10 +09:00
Hide_D 1f9c994425 사령부 시간 표기 문제 2020-05-22 00:24:52 +09:00
Hide_D fc0c7a5004 호황, 풍작 색상 변경 2020-05-22 00:17:24 +09:00
Hide_D a2d0309c79 내특 중복 버그 수정 2020-05-21 12:52:00 +09:00
Hide_D 6d01fbb6e8 generalCommand 생성이 preprecessCommand보다 빠른 문제 수정 2020-05-21 12:14:46 +09:00
Hide_D be270df088 요양 입력하면 템치료 무효화 2020-05-21 02:16:20 +09:00
Hide_D 88fd94e1cc 왕조일람 국가 타입 버그 수정 2020-05-20 01:35:11 +09:00
Hide_D e460392368 인사부 임명시 색상 2020-05-20 01:31:26 +09:00
Hide_D 249cda99f4 랜덤임관에 긍정적인 메시지 추가 2020-05-20 01:26:28 +09:00
Hide_D 327fce822a Merge branch 'devel' of ssh://storage.hided.net:2525/devsam/core into devel 2020-05-20 01:11:41 +09:00
Hide_D 58931354a4 NPC 포상룰 변경 2020-05-20 01:11:35 +09:00
Hide_D c8993e9832 암해부 정렬 버그 2020-05-19 16:53:20 +09:00
Hide_D 4ee2e023aa 버그 수정 2020-05-19 10:07:24 +09:00
Hide_D 22fa1b121e 수정시도2 2020-05-19 00:32:52 +09:00
Hide_D cbc6e526c3 수정시도2 2020-05-19 00:32:40 +09:00
Hide_D 96041faefd 수정시도1 2020-05-19 00:30:55 +09:00
Hide_D 894c912e19 수정시도 1 2020-05-19 00:29:24 +09:00
Hide_D 7b406a945f 버그 수정 2020-05-19 00:25:41 +09:00
Hide_D 6ff5cc90f1 버그 수정 2020-05-19 00:18:45 +09:00
Hide_D f66e56f4b5 보궁기귀 전특 중 '통장'에 타 능력치 금지 추가 2020-05-19 00:08:50 +09:00
Hide_D 8f09aab0ea NPC 자원 기준 대폭 변경 2020-05-18 23:49:13 +09:00
Hide_D b248b9ca2c 불가침 하나만 있어도 계략이 안들어가는 버그 수정 2020-05-18 23:25:53 +09:00
Hide_D 5a6a31fefa 정착장려, 주민선정 색상 문제 2020-05-18 23:24:17 +09:00
Hide_D 1e485a3883 onCalcNationalIncome 버그 2020-05-18 23:17:16 +09:00
Hide_D fed3246c84 계략 성공시 대미지 없는 문제 수정 2020-05-18 20:12:57 +09:00
Hide_D daff4a9786 징병시 부상을 무시하는 버그 수정 2020-05-18 19:35:41 +09:00
Hide_D 6e88b0c701 로그에 도시 추가 2020-05-18 14:30:39 +09:00
Hide_D 808f674173 버그 수정? 2020-05-18 09:55:00 +09:00
Hide_D ba377c9aac 등용 UI 버그 수정 2020-05-17 20:07:09 +09:00
Hide_D bb8909f552 등용 UI 버그 수정 2020-05-17 20:05:47 +09:00
Hide_D 5a4d9ffcfc 등용장 버그 수정
등용장 초반에도 보낼 수 있도록,
리스트에서 optgroup 작성 실수
2020-05-17 20:00:06 +09:00
Hide_D 5ed24a98cb npc 정책 UI 수정 2020-05-17 19:48:20 +09:00
Hide_D 6d17675ee7 npc 정책 UI
?가 아니라 본체를 선택해도 보이도록
2020-05-17 19:45:18 +09:00
Hide_D e0b8bfdeae 버그 수정 2020-05-17 18:15:02 +09:00
Hide_D 0db2009e65 NPC 생성시 스케일러 제거 2020-05-17 13:47:28 +09:00
Hide_D 5f016d74a1 버그 수정 2020-05-17 03:03:04 +09:00
Hide_D 02b9832750 npcMax 추가 감소 2020-05-16 21:12:09 +09:00
Hide_D 18a888b9d4 인탐, 의병모집 수정, npcMin, npcTotal 추가 2020-05-16 18:59:10 +09:00
Hide_D 7f20e981d2 오호장군 표기기준 버그 수정 2020-05-16 18:16:52 +09:00
Hide_D d64e08f3c4 부대장후방발령버그 2020-05-16 16:24:45 +09:00
Hide_D 8bb5324896 출병 경로 설정 메시지 버그 수정 2020-05-16 14:14:13 +09:00
Hide_D 8f2ebc6409 인재탐색 연령버그 수정 2020-05-16 12:37:13 +09:00
Hide_D 371318f62f 버그 수정 2020-05-15 21:59:10 +09:00
Hide_D 6e94403dc6 수치 버그 수정 2020-05-15 21:51:29 +09:00
Hide_D c35f6905bb 초토화 배율 변경 2020-05-15 21:50:11 +09:00
Hide_D 4eebbb3e81 초토화에 전 장수 배신 1호 추가, 반환 금액 입력 2020-05-15 21:25:01 +09:00
Hide_D 8ddfc8fb4a 한계징병 2020-05-15 12:36:01 +09:00
Hide_D 14d2661be8 npc 조작 권한 안내 2020-05-15 00:38:26 +09:00
Hide_D ec71bf29b8 애니 집결 수정 2020-05-15 00:30:14 +09:00
220 changed files with 14761 additions and 9578 deletions
+2 -2
View File
@@ -51,10 +51,8 @@ return [
'hwe/b_tournament.php', 'hwe/b_tournament.php',
'hwe/b_troop.php', 'hwe/b_troop.php',
'hwe/c_auction.php', 'hwe/c_auction.php',
'hwe/c_die_immediately.php',
'hwe/c_dipcenter.php', 'hwe/c_dipcenter.php',
'hwe/c_tournament.php', 'hwe/c_tournament.php',
'hwe/c_vacation.php',
'hwe/c_vote.php', 'hwe/c_vote.php',
'hwe/func.php', 'hwe/func.php',
'hwe/func_auction.php', 'hwe/func_auction.php',
@@ -83,6 +81,7 @@ return [
'hwe/j_board_comment_add.php', 'hwe/j_board_comment_add.php',
'hwe/j_board_get_articles.php', 'hwe/j_board_get_articles.php',
'hwe/j_chief_turn.php', 'hwe/j_chief_turn.php',
'hwe/j_die_immediately.php',
'hwe/j_diplomacy_destroy_letter.php', 'hwe/j_diplomacy_destroy_letter.php',
'hwe/j_diplomacy_get_letter.php', 'hwe/j_diplomacy_get_letter.php',
'hwe/j_diplomacy_respond_letter.php', 'hwe/j_diplomacy_respond_letter.php',
@@ -115,6 +114,7 @@ return [
'hwe/j_set_general_command.php', 'hwe/j_set_general_command.php',
'hwe/j_simulate_battle.php', 'hwe/j_simulate_battle.php',
'hwe/j_troop.php', 'hwe/j_troop.php',
'hwe/j_vacation.php',
'hwe/lib.php', 'hwe/lib.php',
'hwe/process_war.php', 'hwe/process_war.php',
'hwe/select_npc.php', 'hwe/select_npc.php',
+23
View File
@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>닫혀 있습니다.</title>
<script>
setTimeout(function(){
window.location = window.location+'/../';
}, 5000);
</script>
<style>
html, body{
background-color:black;
color:yellow;
}
</style>
</head>
<body>
서버가 닫혀있습니다.<br>
잠시 뒤에 입구로 이동합니다.
</body>
</html>
+52 -51
View File
@@ -1,51 +1,52 @@
{ {
"name":"sammo-hid/sammo", "name":"sammo-hid/sammo",
"description":"삼국지 모의전투 HiDCHe", "description":"삼국지 모의전투 HiDCHe",
"license": [ "license": [
"MIT", "MIT",
"GPL-2.0-or-later", "GPL-2.0-or-later",
"proprietary" "proprietary"
], ],
"config": { "config": {
"platform": { "platform": {
"php": "7.3" "php": "7.3"
} }
}, },
"require": { "require": {
"brandonwamboldt/utilphp": "^1.1", "brandonwamboldt/utilphp": "^1.1",
"sergeytsalkov/meekrodb": "^2.3", "sergeytsalkov/meekrodb": "^2.3",
"league/plates": "^3.3", "league/plates": "^3.3",
"guzzlehttp/guzzle": "^6.3", "guzzlehttp/guzzle": "^6.3",
"scssphp/scssphp": "^1.0", "scssphp/scssphp": "^1.0",
"monolog/monolog": "^1.23", "monolog/monolog": "^1.23",
"firephp/firephp-core": "^0.4.0", "firephp/firephp-core": "^0.4.0",
"vlucas/valitron": "^1.4", "vlucas/valitron": "^1.4",
"php-extended/php-tail": "^2.1", "php-extended/php-tail": "^2.1",
"pguardiario/phpuri": "^1.0", "pguardiario/phpuri": "^1.0",
"symfony/lock": "^4.1", "symfony/lock": "^4.1",
"ezyang/htmlpurifier": "^4.10", "ezyang/htmlpurifier": "^4.10",
"xemlock/htmlpurifier-html5": "^0.1.7", "xemlock/htmlpurifier-html5": "^0.1.7",
"catfan/medoo": "^1.5", "catfan/medoo": "^1.5",
"phan/phan": "^2.7" "phan/phan": "^2.7",
}, "erusev/parsedown-extra": "^0.8.1"
"autoload": { },
"psr-4": { "autoload": {
"sammo\\": [ "psr-4": {
"src/sammo" "sammo\\": [
], "src/sammo"
"kakao\\": [ ],
"src/kakao" "kakao\\": [
] "src/kakao"
}, ]
"classmap": [ },
"d_setting/" "classmap": [
], "d_setting/"
"exclude-from-classmap": [ ],
"**/*.orig.php" "exclude-from-classmap": [
], "**/*.orig.php"
"files":[ ],
"f_config/config.php" "files":[
] "f_config/config.php"
} ]
}
}
}
Generated
+93 -77
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "7343763bee946f23e755edecd14d6b2c", "content-hash": "1c2e0182ebdf9bfe795e52a5d7fc6abd",
"packages": [ "packages": [
{ {
"name": "brandonwamboldt/utilphp", "name": "brandonwamboldt/utilphp",
@@ -215,13 +215,100 @@
"Xdebug", "Xdebug",
"performance" "performance"
], ],
"funding": [ "time": "2020-03-01T12:26:26+00:00"
},
{
"name": "erusev/parsedown",
"version": "1.7.4",
"source": {
"type": "git",
"url": "https://github.com/erusev/parsedown.git",
"reference": "cb17b6477dfff935958ba01325f2e8a2bfa6dab3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/erusev/parsedown/zipball/cb17b6477dfff935958ba01325f2e8a2bfa6dab3",
"reference": "cb17b6477dfff935958ba01325f2e8a2bfa6dab3",
"shasum": ""
},
"require": {
"ext-mbstring": "*",
"php": ">=5.3.0"
},
"require-dev": {
"phpunit/phpunit": "^4.8.35"
},
"type": "library",
"autoload": {
"psr-0": {
"Parsedown": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{ {
"url": "https://packagist.com", "name": "Emanuil Rusev",
"type": "custom" "email": "hello@erusev.com",
"homepage": "http://erusev.com"
} }
], ],
"time": "2020-03-01T12:26:26+00:00" "description": "Parser for Markdown.",
"homepage": "http://parsedown.org",
"keywords": [
"markdown",
"parser"
],
"time": "2019-12-30T22:54:17+00:00"
},
{
"name": "erusev/parsedown-extra",
"version": "0.8.1",
"source": {
"type": "git",
"url": "https://github.com/erusev/parsedown-extra.git",
"reference": "91ac3ff98f0cea243bdccc688df43810f044dcef"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/erusev/parsedown-extra/zipball/91ac3ff98f0cea243bdccc688df43810f044dcef",
"reference": "91ac3ff98f0cea243bdccc688df43810f044dcef",
"shasum": ""
},
"require": {
"erusev/parsedown": "^1.7.4"
},
"require-dev": {
"phpunit/phpunit": "^4.8.35"
},
"type": "library",
"autoload": {
"psr-0": {
"ParsedownExtra": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Emanuil Rusev",
"email": "hello@erusev.com",
"homepage": "http://erusev.com"
}
],
"description": "An extension of Parsedown that adds support for Markdown Extra.",
"homepage": "https://github.com/erusev/parsedown-extra",
"keywords": [
"markdown",
"markdown extra",
"parsedown",
"parser"
],
"time": "2019-12-30T23:20:37+00:00"
}, },
{ {
"name": "ezyang/htmlpurifier", "name": "ezyang/htmlpurifier",
@@ -1510,20 +1597,6 @@
], ],
"description": "Symfony Console Component", "description": "Symfony Console Component",
"homepage": "https://symfony.com", "homepage": "https://symfony.com",
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2020-03-30T11:42:42+00:00" "time": "2020-03-30T11:42:42+00:00"
}, },
{ {
@@ -1648,20 +1721,6 @@
"polyfill", "polyfill",
"portable" "portable"
], ],
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2020-02-27T09:26:54+00:00" "time": "2020-02-27T09:26:54+00:00"
}, },
{ {
@@ -1721,20 +1780,6 @@
"portable", "portable",
"shim" "shim"
], ],
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2020-03-09T19:04:49+00:00" "time": "2020-03-09T19:04:49+00:00"
}, },
{ {
@@ -1790,20 +1835,6 @@
"portable", "portable",
"shim" "shim"
], ],
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2020-02-27T09:26:54+00:00" "time": "2020-02-27T09:26:54+00:00"
}, },
{ {
@@ -1862,20 +1893,6 @@
"portable", "portable",
"shim" "shim"
], ],
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2020-02-27T09:26:54+00:00" "time": "2020-02-27T09:26:54+00:00"
}, },
{ {
@@ -2095,6 +2112,5 @@
"platform-dev": [], "platform-dev": [],
"platform-overrides": { "platform-overrides": {
"php": "7.3" "php": "7.3"
}, }
"plugin-api-version": "1.1.0"
} }
+2 -2
View File
@@ -1,3 +1,3 @@
/*! Select2 4.0.5 | https://github.com/select2/select2/blob/master/LICENSE.md */ /*! Select2 4.0.13 | https://github.com/select2/select2/blob/master/LICENSE.md */
(function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var e=jQuery.fn.select2.amd;return e.define("select2/i18n/ko",[],function(){return{errorLoading:function(){return"결과를 불러올 수 없습니다."},inputTooLong:function(e){var t=e.input.length-e.maximum,n="너무 깁니다. "+t+" 글자 지워주세요.";return n},inputTooShort:function(e){var t=e.minimum-e.input.length,n="너무 짧습니다. "+t+" 글자 더 입력해주세요.";return n},loadingMore:function(){return"불러오는 중…"},maximumSelected:function(e){var t="최대 "+e.maximum+"개까지만 선택 가능합니다.";return t},noResults:function(){return"결과가 없습니다."},searching:function(){return"검색 중…"}}}),{define:e.define,require:e.require}})(); !function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var n=jQuery.fn.select2.amd;n.define("select2/i18n/ko",[],function(){return{errorLoading:function(){return"결과를 불러올 수 없습니다."},inputTooLong:function(n){return"너무 깁니다. "+(n.input.length-n.maximum)+" 글자 지워주세요."},inputTooShort:function(n){return"너무 짧습니다. "+(n.minimum-n.input.length)+" 글자 더 입력해주세요."},loadingMore:function(){return"불러오는 중…"},maximumSelected:function(n){return"최대 "+n.maximum+"개까지만 선택 가능합니다."},noResults:function(){return"결과가 없습니다."},searching:function(){return"검색 중…"},removeAllItems:function(){return"모든 항목 삭제"}}}),n.define,n.require}();
+553 -188
View File
@@ -1,188 +1,553 @@
/* select2-bootstrap4 with Darkly */ /* select2-bootstrap4 with Darkly */
.select2-container--bootstrap4 { color: black; }
.select2-container--bootstrap4 {
.select2-container--bootstrap4 .select2-selection { background-color: #fff; border: 1px solid #ced4da; border-radius: 0.25rem; color: #495057; font-size: 1rem; outline: 0; } color: black;
}
.select2-container--bootstrap4 .select2-selection.form-control { border-radius: 0.25rem; }
.select2-container--bootstrap4 .select2-selection {
.select2-container--bootstrap4 .select2-search--dropdown .select2-search__field { background-color: #fff; border: 1px solid #ced4da; border-radius: 0.25rem; color: #495057; font-size: 1rem; } background-color: #fff;
border: 1px solid #ced4da;
.select2-container--bootstrap4 .select2-search__field { outline: 0; } border-radius: 0.25rem;
color: #495057;
.select2-container--bootstrap4 .select2-search__field::-webkit-input-placeholder { color: #6c757d; } font-size: 1rem;
outline: 0;
.select2-container--bootstrap4 .select2-search__field:-moz-placeholder { color: #6c757d; } }
.select2-container--bootstrap4 .select2-search__field::-moz-placeholder { color: #6c757d; opacity: 1; } .select2-container--bootstrap4 .select2-selection.form-control {
border-radius: 0.25rem;
.select2-container--bootstrap4 .select2-search__field:-ms-input-placeholder { color: #6c757d; } }
.select2-container--bootstrap4 .select2-results__option { padding: 0.75rem 0.375rem; font-size: 1rem; } .select2-container--bootstrap4 .select2-search--dropdown .select2-search__field {
background-color: #fff;
.select2-container--bootstrap4 .select2-results__option[role=group] { padding: 0; } border: 1px solid #ced4da;
border-radius: 0.25rem;
.select2-container--bootstrap4 .select2-results__option[aria-disabled=true] { color: #6c757d; cursor: not-allowed; } color: #495057;
font-size: 1rem;
.select2-container--bootstrap4 .select2-results__option[aria-selected=true] { background-color: #f8f9fa; color: #16181b; } }
.select2-container--bootstrap4 .select2-results__option--highlighted[aria-selected] { background-color: #007bff; color: #fff; } .select2-container--bootstrap4 .select2-search__field {
outline: 0;
.select2-container--bootstrap4 .select2-results__option .select2-results__option { padding: 0.75rem 0.375rem; } }
.select2-container--bootstrap4 .select2-results__option .select2-results__option .select2-results__group { padding-left: 0; } .select2-container--bootstrap4 .select2-search__field::-webkit-input-placeholder {
color: #6c757d;
.select2-container--bootstrap4 .select2-results__option .select2-results__option .select2-results__option { margin-left: -0.375rem; padding-left: 0.75rem; } }
.select2-container--bootstrap4 .select2-results__option .select2-results__option .select2-results__option .select2-results__option { margin-left: -0.75rem; padding-left: 1.125rem; } .select2-container--bootstrap4 .select2-search__field:-moz-placeholder {
color: #6c757d;
.select2-container--bootstrap4 .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option { margin-left: -1.125rem; padding-left: 1.5rem; } }
.select2-container--bootstrap4 .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option { margin-left: -1.5rem; padding-left: 1.875rem; } .select2-container--bootstrap4 .select2-search__field::-moz-placeholder {
color: #6c757d;
.select2-container--bootstrap4 .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option { margin-left: -1.875rem; padding-left: 2.25rem; } opacity: 1;
}
.select2-container--bootstrap4 .select2-results__group { color: #6c757d; display: block; padding: 0.75rem 0.375rem; font-size: 75%; line-height: 1; white-space: nowrap; }
.select2-container--bootstrap4 .select2-search__field:-ms-input-placeholder {
.select2-container--bootstrap4.select2-container--focus .select2-selection, .select2-container--bootstrap4.select2-container--open .select2-selection { transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; border-color: #80bdff; } color: #6c757d;
}
@media screen and (prefers-reduced-motion: reduce) { .select2-container--bootstrap4.select2-container--focus .select2-selection, .select2-container--bootstrap4.select2-container--open .select2-selection { transition: none; } }
.select2-container--bootstrap4 .select2-results__option {
.select2-container--bootstrap4.select2-container--open .select2-selection .select2-selection__arrow b { border-color: transparent transparent #6c757d transparent; border-width: 0 0.25rem 0.25rem 0.25rem; } padding: 0.75rem 0.375rem;
font-size: 1rem;
.select2-container--bootstrap4.select2-container--open.select2-container--below .select2-selection { border-bottom-right-radius: 0; border-bottom-left-radius: 0; border-bottom-color: transparent; } }
.select2-container--bootstrap4.select2-container--open.select2-container--above .select2-selection { border-top-left-radius: 0; border-top-right-radius: 0; border-top-color: transparent; } .select2-container--bootstrap4 .select2-results__option[role=group] {
padding: 0;
.select2-container--bootstrap4 .select2-selection__clear { color: #6c757d; cursor: pointer; float: right; font-weight: bold; margin-right: 10px; } }
.select2-container--bootstrap4 .select2-selection__clear:hover { color: #343a40; } .select2-container--bootstrap4 .select2-results__option[aria-disabled=true] {
color: #6c757d;
.select2-container--bootstrap4.select2-container--disabled .select2-selection { border-color: #ced4da; } cursor: not-allowed;
}
.select2-container--bootstrap4.select2-container--disabled .select2-selection, .select2-container--bootstrap4.select2-container--disabled .select2-search__field { cursor: not-allowed; }
.select2-container--bootstrap4 .select2-results__option[aria-selected=true] {
.select2-container--bootstrap4.select2-container--disabled .select2-selection, .select2-container--bootstrap4.select2-container--disabled .select2-selection--multiple .select2-selection__choice { background-color: #e9ecef; } background-color: #f8f9fa;
color: #16181b;
.select2-container--bootstrap4.select2-container--disabled .select2-selection__clear, .select2-container--bootstrap4.select2-container--disabled .select2-selection--multiple .select2-selection__choice__remove { display: none; } }
.select2-container--bootstrap4 .select2-dropdown { border-color: #80bdff; border-width: 1px; overflow-x: hidden; margin-top: -1px; } .select2-container--bootstrap4 .select2-results__option--highlighted[aria-selected] {
background-color: #007bff;
.select2-container--bootstrap4 .select2-dropdown--above { margin-top: 1px; } color: #fff;
}
.select2-container--bootstrap4 .select2-results > .select2-results__options { max-height: 200px; overflow-y: auto; }
.select2-container--bootstrap4 .select2-results__option .select2-results__option {
.select2-container--bootstrap4 .select2-selection--single { height: calc(2.25rem + 2px); line-height: 1; padding: 0.75rem 1.125rem 0.75rem 0.375rem; } padding: 0.75rem 0.375rem;
}
.select2-container--bootstrap4 .select2-selection--single .select2-selection__arrow { position: absolute; bottom: 0; right: 0.375rem; top: 0; width: 0.25rem; }
.select2-container--bootstrap4 .select2-results__option .select2-results__option .select2-results__group {
.select2-container--bootstrap4 .select2-selection--single .select2-selection__arrow b { border-color: #6c757d transparent transparent transparent; border-style: solid; border-width: 0.25rem 0.25rem 0 0.25rem; height: 0; left: 0; margin-left: -0.25rem; margin-top: -0.125rem; position: absolute; top: 50%; width: 0; } padding-left: 0;
}
.select2-container--bootstrap4 .select2-selection--single .select2-selection__rendered { color: #495057; padding: 0; }
.select2-container--bootstrap4 .select2-results__option .select2-results__option .select2-results__option {
.select2-container--bootstrap4 .select2-selection--single .select2-selection__placeholder { color: #6c757d; } margin-left: -0.375rem;
padding-left: 0.75rem;
.select2-container--bootstrap4 .select2-selection--multiple { min-height: calc(2.25rem + 2px); padding: 0; height: auto; } }
.select2-container--bootstrap4 .select2-selection--multiple .select2-selection__rendered { box-sizing: border-box; display: block; line-height: 1; list-style: none; margin: 0; overflow: hidden; padding: 0.75rem 0.375rem 0 0.75rem; width: 100%; text-overflow: ellipsis; white-space: nowrap; } .select2-container--bootstrap4 .select2-results__option .select2-results__option .select2-results__option .select2-results__option {
margin-left: -0.75rem;
.select2-container--bootstrap4 .select2-selection--multiple .select2-selection__placeholder { color: #6c757d; float: left; margin-top: 5px; } padding-left: 1.125rem;
}
.select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice { color: #495057; background: transparent; border: 1px solid #343a40; border-radius: 0.25rem; cursor: default; float: left; margin: -0.25rem 0 0 0.1875rem; padding: 0 0.75rem; }
.select2-container--bootstrap4 .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option {
.select2-container--bootstrap4 .select2-selection--multiple .select2-search--inline .select2-search__field { background: transparent; padding: 0 0.375rem; height: calc(2.25rem + 2px)-2; line-height: 1; margin-top: 0; min-width: 5em; } margin-left: -1.125rem;
padding-left: 1.5rem;
.select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice__remove { color: #6c757d; cursor: pointer; display: inline-block; font-weight: bold; margin-right: 0.375rem; } }
.select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice__remove:hover { color: #343a40; } .select2-container--bootstrap4 .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option {
margin-left: -1.5rem;
.select2-container--bootstrap4 .select2-selection--multiple .select2-selection__clear { margin-top: 0.75rem; } padding-left: 1.875rem;
}
.select2-container--bootstrap4 .select2-selection--single.input-sm, .input-group-sm .select2-container--bootstrap4 .select2-selection--single, .form-group-sm .select2-container--bootstrap4 .select2-selection--single { border-radius: 0.2rem; font-size: 75%; height: calc(1.8125rem + 2px); line-height: 1; padding: 0.5rem 1rem 0.5rem 0.25rem; }
.select2-container--bootstrap4 .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option {
.select2-container--bootstrap4 .select2-selection--single.input-sm .select2-selection__arrow b, .input-group-sm .select2-container--bootstrap4 .select2-selection--single .select2-selection__arrow b, .form-group-sm .select2-container--bootstrap4 .select2-selection--single .select2-selection__arrow b { margin-left: -0.5rem; } margin-left: -1.875rem;
padding-left: 2.25rem;
.select2-container--bootstrap4 .select2-selection--multiple.input-sm, .input-group-sm .select2-container--bootstrap4 .select2-selection--multiple, .form-group-sm .select2-container--bootstrap4 .select2-selection--multiple { min-height: calc(1.8125rem + 2px); border-radius: 0.2rem; } }
.select2-container--bootstrap4 .select2-selection--multiple.input-sm .select2-selection__rendered, .input-group-sm .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__rendered, .form-group-sm .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__rendered { padding: 0.5rem 0.25rem 0 0.5rem; } .select2-container--bootstrap4 .select2-results__group {
color: #6c757d;
.select2-container--bootstrap4 .select2-selection--multiple.input-sm .select2-selection__choice, .input-group-sm .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice, .form-group-sm .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice { font-size: 75%; line-height: 1; margin: 0 0 0 0.125rem; padding: 0 0.5rem; } display: block;
padding: 0.75rem 0.375rem;
.select2-container--bootstrap4 .select2-selection--multiple.input-sm .select2-search--inline .select2-search__field, .input-group-sm .select2-container--bootstrap4 .select2-selection--multiple .select2-search--inline .select2-search__field, .form-group-sm .select2-container--bootstrap4 .select2-selection--multiple .select2-search--inline .select2-search__field { padding: 0 0.25rem; font-size: 75%; height: calc(1.8125rem + 2px)-2; line-height: 1; } font-size: 75%;
line-height: 1;
.select2-container--bootstrap4 .select2-selection--multiple.input-sm .select2-selection__clear, .input-group-sm .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__clear, .form-group-sm .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__clear { margin-top: 0.5rem; } white-space: nowrap;
}
.select2-container--bootstrap4 .select2-selection--single.input-lg, .input-group-lg .select2-container--bootstrap4 .select2-selection--single, .form-group-lg .select2-container--bootstrap4 .select2-selection--single { border-radius: 0.3rem; font-size: 1.25rem; height: calc(2.875rem + 2px); line-height: 1; padding: 1rem 1.4375rem 1rem 0.5rem; }
.select2-container--bootstrap4.select2-container--focus .select2-selection,
.select2-container--bootstrap4 .select2-selection--single.input-lg .select2-selection__arrow, .input-group-lg .select2-container--bootstrap4 .select2-selection--single .select2-selection__arrow, .form-group-lg .select2-container--bootstrap4 .select2-selection--single .select2-selection__arrow { width: 0.3125rem; } .select2-container--bootstrap4.select2-container--open .select2-selection {
transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
.select2-container--bootstrap4 .select2-selection--single.input-lg .select2-selection__arrow b, .input-group-lg .select2-container--bootstrap4 .select2-selection--single .select2-selection__arrow b, .form-group-lg .select2-container--bootstrap4 .select2-selection--single .select2-selection__arrow b { border-width: 0.3125rem 0.3125rem 0 0.3125rem; margin-left: -0.3125rem; margin-left: -1rem; margin-top: -0.15625rem; } border-color: #80bdff;
}
.select2-container--bootstrap4 .select2-selection--multiple.input-lg, .input-group-lg .select2-container--bootstrap4 .select2-selection--multiple, .form-group-lg .select2-container--bootstrap4 .select2-selection--multiple { min-height: calc(2.875rem + 2px); border-radius: 0.3rem; }
@media screen and (prefers-reduced-motion: reduce) {
.select2-container--bootstrap4 .select2-selection--multiple.input-lg .select2-selection__choice, .input-group-lg .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice, .form-group-lg .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice { font-size: 1.25rem; line-height: 1; border-radius: 0.25rem; margin: 0rem 0 0 0.25rem; padding: 0 1rem; } .select2-container--bootstrap4.select2-container--focus .select2-selection,
.select2-container--bootstrap4.select2-container--open .select2-selection {
.select2-container--bootstrap4 .select2-selection--multiple.input-lg .select2-search--inline .select2-search__field, .input-group-lg .select2-container--bootstrap4 .select2-selection--multiple .select2-search--inline .select2-search__field, .form-group-lg .select2-container--bootstrap4 .select2-selection--multiple .select2-search--inline .select2-search__field { padding: 0 0.5rem; font-size: 1.25rem; height: calc(2.875rem + 2px)-2; line-height: 1; } transition: none;
}
.select2-container--bootstrap4 .select2-selection--multiple.input-lg .select2-selection__clear, .input-group-lg .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__clear, .form-group-lg .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__clear { margin-top: 1rem; } }
.select2-container--bootstrap4 .select2-selection.input-lg.select2-container--open .select2-selection--single .select2-selection__arrow b { border-color: transparent transparent #6c757d transparent; border-width: 0 0.3125rem 0.3125rem 0.3125rem; } .select2-container--bootstrap4.select2-container--open .select2-selection .select2-selection__arrow b {
border-color: transparent transparent #6c757d transparent;
.input-group-lg .select2-container--bootstrap4 .select2-selection.select2-container--open .select2-selection--single .select2-selection__arrow b { border-color: transparent transparent #6c757d transparent; border-width: 0 0.3125rem 0.3125rem 0.3125rem; } border-width: 0 0.25rem 0.25rem 0.25rem;
}
.select2-container--bootstrap4[dir="rtl"] .select2-selection--single { padding-left: 1.125rem; padding-right: 0.375rem; }
.select2-container--bootstrap4.select2-container--open.select2-container--below .select2-selection {
.select2-container--bootstrap4[dir="rtl"] .select2-selection--single .select2-selection__rendered { padding-right: 0; padding-left: 0; text-align: right; } border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
.select2-container--bootstrap4[dir="rtl"] .select2-selection--single .select2-selection__clear { float: left; } border-bottom-color: transparent;
}
.select2-container--bootstrap4[dir="rtl"] .select2-selection--single .select2-selection__arrow { left: 0.375rem; right: auto; }
.select2-container--bootstrap4.select2-container--open.select2-container--above .select2-selection {
.select2-container--bootstrap4[dir="rtl"] .select2-selection--single .select2-selection__arrow b { margin-left: 0; } border-top-left-radius: 0;
border-top-right-radius: 0;
.select2-container--bootstrap4[dir="rtl"] .select2-selection--multiple .select2-selection__choice, .select2-container--bootstrap4[dir="rtl"] .select2-selection--multiple .select2-selection__placeholder, .select2-container--bootstrap4[dir="rtl"] .select2-selection--multiple .select2-search--inline { float: right; } border-top-color: transparent;
}
.select2-container--bootstrap4[dir="rtl"] .select2-selection--multiple .select2-selection__choice { margin-left: 0; margin-right: 0.1875rem; }
.select2-container--bootstrap4 .select2-selection__clear {
.select2-container--bootstrap4[dir="rtl"] .select2-selection--multiple .select2-selection__choice__remove { margin-left: 2px; margin-right: auto; } color: #6c757d;
cursor: pointer;
.has-warning .select2-dropdown, .has-warning .select2-selection { border-color: #ffc107; } float: right;
font-weight: bold;
.has-warning .select2-container--focus .select2-selection, .has-warning .select2-container--open .select2-selection { border-color: #d39e00; } margin-right: 10px;
}
.has-warning.select2-drop-active { border-color: #d39e00; }
.select2-container--bootstrap4 .select2-selection__clear:hover {
.has-warning.select2-drop-active.select2-drop.select2-drop-above { border-top-color: #d39e00; } color: #343a40;
}
.has-error .select2-dropdown, .has-error .select2-selection { border-color: #dc3545; }
.select2-container--bootstrap4.select2-container--disabled .select2-selection {
.has-error .select2-container--focus .select2-selection, .has-error .select2-container--open .select2-selection { border-color: #bd2130; } border-color: #ced4da;
}
.has-error.select2-drop-active { border-color: #bd2130; }
.select2-container--bootstrap4.select2-container--disabled .select2-selection,
.has-error.select2-drop-active.select2-drop.select2-drop-above { border-top-color: #bd2130; } .select2-container--bootstrap4.select2-container--disabled .select2-search__field {
cursor: not-allowed;
.has-success .select2-dropdown, .has-success .select2-selection { border-color: #28a745; } }
.has-success .select2-container--focus .select2-selection, .has-success .select2-container--open .select2-selection { border-color: #1e7e34; } .select2-container--bootstrap4.select2-container--disabled .select2-selection,
.select2-container--bootstrap4.select2-container--disabled .select2-selection--multiple .select2-selection__choice {
.has-success.select2-drop-active { border-color: #1e7e34; } background-color: #e9ecef;
}
.has-success.select2-drop-active.select2-drop.select2-drop-above { border-top-color: #1e7e34; }
.select2-container--bootstrap4.select2-container--disabled .select2-selection__clear,
.input-group > .select2-hidden-accessible:first-child + .select2-container--bootstrap4 > .selection > .select2-selection, .input-group > .select2-hidden-accessible:first-child + .select2-container--bootstrap4 > .selection > .select2-selection.form-control { border-top-right-radius: 0; border-bottom-right-radius: 0; } .select2-container--bootstrap4.select2-container--disabled .select2-selection--multiple .select2-selection__choice__remove {
display: none;
.input-group > .select2-hidden-accessible:not(:first-child) + .select2-container--bootstrap4:not(:last-child) > .selection > .select2-selection, .input-group > .select2-hidden-accessible:not(:first-child) + .select2-container--bootstrap4:not(:last-child) > .selection > .select2-selection.form-control { border-radius: 0; } }
.input-group > .select2-hidden-accessible:not(:first-child):not(:last-child) + .select2-container--bootstrap4:last-child > .selection > .select2-selection, .input-group > .select2-hidden-accessible:not(:first-child):not(:last-child) + .select2-container--bootstrap4:last-child > .selection > .select2-selection.form-control { border-top-left-radius: 0; border-bottom-left-radius: 0; } .select2-container--bootstrap4 .select2-dropdown {
border-color: #80bdff;
.input-group > .select2-container--bootstrap4 { display: table; table-layout: fixed; position: relative; z-index: 2; width: 100%; margin-bottom: 0; } border-width: 1px;
overflow-x: hidden;
.input-group > .select2-container--bootstrap4 > .selection > .select2-selection.form-control { float: none; } margin-top: -1px;
}
.input-group > .select2-container--bootstrap4.select2-container--open, .input-group > .select2-container--bootstrap4.select2-container--focus { z-index: 3; }
.select2-container--bootstrap4 .select2-dropdown--above {
.input-group > .select2-container--bootstrap4, .input-group > .select2-container--bootstrap4 .input-group-btn, .input-group > .select2-container--bootstrap4 .input-group-btn .btn { vertical-align: top; } margin-top: 1px;
}
.form-control.select2-hidden-accessible { position: absolute !important; width: 1px !important; }
.select2-container--bootstrap4 .select2-results>.select2-results__options {
@media (min-width: 576px) { .form-inline .select2-container--bootstrap4 { display: inline-block; } } max-height: 200px;
overflow-y: auto;
}
.select2-container--bootstrap4 .select2-selection--single {
height: calc(2.25rem + 2px);
line-height: 1;
padding: 0.75rem 1.125rem 0.75rem 0.375rem;
}
.select2-container--bootstrap4 .select2-selection--single .select2-selection__arrow {
position: absolute;
bottom: 0;
right: 0.375rem;
top: 0;
width: 0.25rem;
}
.select2-container--bootstrap4 .select2-selection--single .select2-selection__arrow b {
border-color: #6c757d transparent transparent transparent;
border-style: solid;
border-width: 0.25rem 0.25rem 0 0.25rem;
height: 0;
left: 0;
margin-left: -0.25rem;
margin-top: -0.125rem;
position: absolute;
top: 50%;
width: 0;
}
.select2-container--bootstrap4 .select2-selection--single .select2-selection__rendered {
color: #495057;
padding: 0;
}
.select2-container--bootstrap4 .select2-selection--single .select2-selection__placeholder {
color: #6c757d;
}
.select2-container--bootstrap4 .select2-selection--multiple {
min-height: calc(2.25rem + 2px);
padding: 0;
height: auto;
}
.select2-container--bootstrap4 .select2-selection--multiple .select2-selection__rendered {
box-sizing: border-box;
display: block;
line-height: 1;
list-style: none;
margin: 0;
overflow: hidden;
padding: 0.75rem 0.375rem 0 0.75rem;
width: 100%;
text-overflow: ellipsis;
white-space: nowrap;
}
.select2-container--bootstrap4 .select2-selection--multiple .select2-selection__placeholder {
color: #6c757d;
float: left;
margin-top: 5px;
}
.select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice {
color: #495057;
background: transparent;
border: 1px solid #343a40;
border-radius: 0.25rem;
cursor: default;
float: left;
margin: -0.25rem 0 0 0.1875rem;
padding: 0 0.75rem;
}
.select2-container--bootstrap4 .select2-selection--multiple .select2-search--inline .select2-search__field {
background: transparent;
padding: 0 0.375rem;
height: calc(2.25rem + 2px)-2;
line-height: 1;
margin-top: 0;
min-width: 5em;
}
.select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice__remove {
color: #6c757d;
cursor: pointer;
display: inline-block;
font-weight: bold;
margin-right: 0.375rem;
}
.select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice__remove:hover {
color: #343a40;
}
.select2-container--bootstrap4 .select2-selection--multiple .select2-selection__clear {
margin-top: 0.75rem;
}
.select2-container--bootstrap4 .select2-selection--single.input-sm,
.input-group-sm .select2-container--bootstrap4 .select2-selection--single,
.form-group-sm .select2-container--bootstrap4 .select2-selection--single {
border-radius: 0.2rem;
font-size: 75%;
height: calc(1.8125rem + 2px);
line-height: 1;
padding: 0.5rem 1rem 0.5rem 0.25rem;
}
.select2-container--bootstrap4 .select2-selection--single.input-sm .select2-selection__arrow b,
.input-group-sm .select2-container--bootstrap4 .select2-selection--single .select2-selection__arrow b,
.form-group-sm .select2-container--bootstrap4 .select2-selection--single .select2-selection__arrow b {
margin-left: -0.5rem;
}
.select2-container--bootstrap4 .select2-selection--multiple.input-sm,
.input-group-sm .select2-container--bootstrap4 .select2-selection--multiple,
.form-group-sm .select2-container--bootstrap4 .select2-selection--multiple {
min-height: calc(1.8125rem + 2px);
border-radius: 0.2rem;
}
.select2-container--bootstrap4 .select2-selection--multiple.input-sm .select2-selection__rendered,
.input-group-sm .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__rendered,
.form-group-sm .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__rendered {
padding: 0.5rem 0.25rem 0 0.5rem;
}
.select2-container--bootstrap4 .select2-selection--multiple.input-sm .select2-selection__choice,
.input-group-sm .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice,
.form-group-sm .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice {
font-size: 75%;
line-height: 1;
margin: 0 0 0 0.125rem;
padding: 0 0.5rem;
}
.select2-container--bootstrap4 .select2-selection--multiple.input-sm .select2-search--inline .select2-search__field,
.input-group-sm .select2-container--bootstrap4 .select2-selection--multiple .select2-search--inline .select2-search__field,
.form-group-sm .select2-container--bootstrap4 .select2-selection--multiple .select2-search--inline .select2-search__field {
padding: 0 0.25rem;
font-size: 75%;
height: calc(1.8125rem + 2px)-2;
line-height: 1;
}
.select2-container--bootstrap4 .select2-selection--multiple.input-sm .select2-selection__clear,
.input-group-sm .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__clear,
.form-group-sm .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__clear {
margin-top: 0.5rem;
}
.select2-container--bootstrap4 .select2-selection--single.input-lg,
.input-group-lg .select2-container--bootstrap4 .select2-selection--single,
.form-group-lg .select2-container--bootstrap4 .select2-selection--single {
border-radius: 0.3rem;
font-size: 1.25rem;
height: calc(2.875rem + 2px);
line-height: 1;
padding: 1rem 1.4375rem 1rem 0.5rem;
}
.select2-container--bootstrap4 .select2-selection--single.input-lg .select2-selection__arrow,
.input-group-lg .select2-container--bootstrap4 .select2-selection--single .select2-selection__arrow,
.form-group-lg .select2-container--bootstrap4 .select2-selection--single .select2-selection__arrow {
width: 0.3125rem;
}
.select2-container--bootstrap4 .select2-selection--single.input-lg .select2-selection__arrow b,
.input-group-lg .select2-container--bootstrap4 .select2-selection--single .select2-selection__arrow b,
.form-group-lg .select2-container--bootstrap4 .select2-selection--single .select2-selection__arrow b {
border-width: 0.3125rem 0.3125rem 0 0.3125rem;
margin-left: -0.3125rem;
margin-left: -1rem;
margin-top: -0.15625rem;
}
.select2-container--bootstrap4 .select2-selection--multiple.input-lg,
.input-group-lg .select2-container--bootstrap4 .select2-selection--multiple,
.form-group-lg .select2-container--bootstrap4 .select2-selection--multiple {
min-height: calc(2.875rem + 2px);
border-radius: 0.3rem;
}
.select2-container--bootstrap4 .select2-selection--multiple.input-lg .select2-selection__choice,
.input-group-lg .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice,
.form-group-lg .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice {
font-size: 1.25rem;
line-height: 1;
border-radius: 0.25rem;
margin: 0rem 0 0 0.25rem;
padding: 0 1rem;
}
.select2-container--bootstrap4 .select2-selection--multiple.input-lg .select2-search--inline .select2-search__field,
.input-group-lg .select2-container--bootstrap4 .select2-selection--multiple .select2-search--inline .select2-search__field,
.form-group-lg .select2-container--bootstrap4 .select2-selection--multiple .select2-search--inline .select2-search__field {
padding: 0 0.5rem;
font-size: 1.25rem;
height: calc(2.875rem + 2px)-2;
line-height: 1;
}
.select2-container--bootstrap4 .select2-selection--multiple.input-lg .select2-selection__clear,
.input-group-lg .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__clear,
.form-group-lg .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__clear {
margin-top: 1rem;
}
.select2-container--bootstrap4 .select2-selection.input-lg.select2-container--open .select2-selection--single .select2-selection__arrow b {
border-color: transparent transparent #6c757d transparent;
border-width: 0 0.3125rem 0.3125rem 0.3125rem;
}
.input-group-lg .select2-container--bootstrap4 .select2-selection.select2-container--open .select2-selection--single .select2-selection__arrow b {
border-color: transparent transparent #6c757d transparent;
border-width: 0 0.3125rem 0.3125rem 0.3125rem;
}
.select2-container--bootstrap4[dir="rtl"] .select2-selection--single {
padding-left: 1.125rem;
padding-right: 0.375rem;
}
.select2-container--bootstrap4[dir="rtl"] .select2-selection--single .select2-selection__rendered {
padding-right: 0;
padding-left: 0;
text-align: right;
}
.select2-container--bootstrap4[dir="rtl"] .select2-selection--single .select2-selection__clear {
float: left;
}
.select2-container--bootstrap4[dir="rtl"] .select2-selection--single .select2-selection__arrow {
left: 0.375rem;
right: auto;
}
.select2-container--bootstrap4[dir="rtl"] .select2-selection--single .select2-selection__arrow b {
margin-left: 0;
}
.select2-container--bootstrap4[dir="rtl"] .select2-selection--multiple .select2-selection__choice,
.select2-container--bootstrap4[dir="rtl"] .select2-selection--multiple .select2-selection__placeholder,
.select2-container--bootstrap4[dir="rtl"] .select2-selection--multiple .select2-search--inline {
float: right;
}
.select2-container--bootstrap4[dir="rtl"] .select2-selection--multiple .select2-selection__choice {
margin-left: 0;
margin-right: 0.1875rem;
}
.select2-container--bootstrap4[dir="rtl"] .select2-selection--multiple .select2-selection__choice__remove {
margin-left: 2px;
margin-right: auto;
}
.has-warning .select2-dropdown,
.has-warning .select2-selection {
border-color: #ffc107;
}
.has-warning .select2-container--focus .select2-selection,
.has-warning .select2-container--open .select2-selection {
border-color: #d39e00;
}
.has-warning.select2-drop-active {
border-color: #d39e00;
}
.has-warning.select2-drop-active.select2-drop.select2-drop-above {
border-top-color: #d39e00;
}
.has-error .select2-dropdown,
.has-error .select2-selection {
border-color: #dc3545;
}
.has-error .select2-container--focus .select2-selection,
.has-error .select2-container--open .select2-selection {
border-color: #bd2130;
}
.has-error.select2-drop-active {
border-color: #bd2130;
}
.has-error.select2-drop-active.select2-drop.select2-drop-above {
border-top-color: #bd2130;
}
.has-success .select2-dropdown,
.has-success .select2-selection {
border-color: #28a745;
}
.has-success .select2-container--focus .select2-selection,
.has-success .select2-container--open .select2-selection {
border-color: #1e7e34;
}
.has-success.select2-drop-active {
border-color: #1e7e34;
}
.has-success.select2-drop-active.select2-drop.select2-drop-above {
border-top-color: #1e7e34;
}
.input-group>.select2-hidden-accessible:first-child+.select2-container--bootstrap4>.selection>.select2-selection,
.input-group>.select2-hidden-accessible:first-child+.select2-container--bootstrap4>.selection>.select2-selection.form-control {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.input-group>.select2-hidden-accessible:not(:first-child)+.select2-container--bootstrap4:not(:last-child)>.selection>.select2-selection,
.input-group>.select2-hidden-accessible:not(:first-child)+.select2-container--bootstrap4:not(:last-child)>.selection>.select2-selection.form-control {
border-radius: 0;
}
.input-group>.select2-hidden-accessible:not(:first-child):not(:last-child)+.select2-container--bootstrap4:last-child>.selection>.select2-selection,
.input-group>.select2-hidden-accessible:not(:first-child):not(:last-child)+.select2-container--bootstrap4:last-child>.selection>.select2-selection.form-control {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.input-group>.select2-container--bootstrap4 {
display: table;
table-layout: fixed;
position: relative;
z-index: 2;
width: 100%;
margin-bottom: 0;
}
.input-group>.select2-container--bootstrap4>.selection>.select2-selection.form-control {
float: none;
}
.input-group>.select2-container--bootstrap4.select2-container--open,
.input-group>.select2-container--bootstrap4.select2-container--focus {
z-index: 3;
}
.input-group>.select2-container--bootstrap4,
.input-group>.select2-container--bootstrap4 .input-group-btn,
.input-group>.select2-container--bootstrap4 .input-group-btn .btn {
vertical-align: top;
}
.form-control.select2-hidden-accessible {
position: absolute !important;
width: 1px !important;
}
@media (min-width: 576px) {
.form-inline .select2-container--bootstrap4 {
display: inline-block;
}
}
+8 -11
View File
@@ -118,12 +118,14 @@
.select2-hidden-accessible { .select2-hidden-accessible {
border: 0 !important; border: 0 !important;
clip: rect(0 0 0 0) !important; clip: rect(0 0 0 0) !important;
-webkit-clip-path: inset(50%) !important;
clip-path: inset(50%) !important;
height: 1px !important; height: 1px !important;
margin: -1px !important;
overflow: hidden !important; overflow: hidden !important;
padding: 0 !important; padding: 0 !important;
position: absolute !important; position: absolute !important;
width: 1px !important; } width: 1px !important;
white-space: nowrap !important; }
.select2-container--default .select2-selection--single { .select2-container--default .select2-selection--single {
background-color: #fff; background-color: #fff;
@@ -186,16 +188,13 @@
width: 100%; } width: 100%; }
.select2-container--default .select2-selection--multiple .select2-selection__rendered li { .select2-container--default .select2-selection--multiple .select2-selection__rendered li {
list-style: none; } list-style: none; }
.select2-container--default .select2-selection--multiple .select2-selection__placeholder {
color: #999;
margin-top: 5px;
float: left; }
.select2-container--default .select2-selection--multiple .select2-selection__clear { .select2-container--default .select2-selection--multiple .select2-selection__clear {
cursor: pointer; cursor: pointer;
float: right; float: right;
font-weight: bold; font-weight: bold;
margin-top: 5px; margin-top: 5px;
margin-right: 10px; } margin-right: 10px;
padding: 1px; }
.select2-container--default .select2-selection--multiple .select2-selection__choice { .select2-container--default .select2-selection--multiple .select2-selection__choice {
background-color: #e4e4e4; background-color: #e4e4e4;
border: 1px solid #aaa; border: 1px solid #aaa;
@@ -214,7 +213,7 @@
.select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover { .select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover {
color: #333; } color: #333; }
.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice, .select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__placeholder, .select2-container--default[dir="rtl"] .select2-selection--multiple .select2-search--inline { .select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice, .select2-container--default[dir="rtl"] .select2-selection--multiple .select2-search--inline {
float: right; } float: right; }
.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice { .select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice {
@@ -420,9 +419,7 @@
color: #555; } color: #555; }
.select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice { .select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice {
float: right; } float: right;
.select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice {
margin-left: 5px; margin-left: 5px;
margin-right: auto; } margin-right: auto; }
+583 -220
View File
@@ -1,11 +1,11 @@
/*! /*!
* Select2 4.0.5 * Select2 4.0.13
* https://select2.github.io * https://select2.github.io
* *
* Released under the MIT license * Released under the MIT license
* https://github.com/select2/select2/blob/master/LICENSE.md * https://github.com/select2/select2/blob/master/LICENSE.md
*/ */
(function (factory) { ;(function (factory) {
if (typeof define === 'function' && define.amd) { if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module. // AMD. Register as an anonymous module.
define(['jquery'], factory); define(['jquery'], factory);
@@ -574,10 +574,10 @@ S2.define('select2/utils',[
DecoratedClass.prototype = new ctr(); DecoratedClass.prototype = new ctr();
for (var m = 0; m < superMethods.length; m++) { for (var m = 0; m < superMethods.length; m++) {
var superMethod = superMethods[m]; var superMethod = superMethods[m];
DecoratedClass.prototype[superMethod] = DecoratedClass.prototype[superMethod] =
SuperClass.prototype[superMethod]; SuperClass.prototype[superMethod];
} }
var calledMethod = function (methodName) { var calledMethod = function (methodName) {
@@ -772,6 +772,70 @@ S2.define('select2/utils',[
$element.append($nodes); $element.append($nodes);
}; };
// Cache objects in Utils.__cache instead of $.data (see #4346)
Utils.__cache = {};
var id = 0;
Utils.GetUniqueElementId = function (element) {
// Get a unique element Id. If element has no id,
// creates a new unique number, stores it in the id
// attribute and returns the new id.
// If an id already exists, it simply returns it.
var select2Id = element.getAttribute('data-select2-id');
if (select2Id == null) {
// If element has id, use it.
if (element.id) {
select2Id = element.id;
element.setAttribute('data-select2-id', select2Id);
} else {
element.setAttribute('data-select2-id', ++id);
select2Id = id.toString();
}
}
return select2Id;
};
Utils.StoreData = function (element, name, value) {
// Stores an item in the cache for a specified element.
// name is the cache key.
var id = Utils.GetUniqueElementId(element);
if (!Utils.__cache[id]) {
Utils.__cache[id] = {};
}
Utils.__cache[id][name] = value;
};
Utils.GetData = function (element, name) {
// Retrieves a value from the cache by its key (name)
// name is optional. If no name specified, return
// all cache items for the specified element.
// and for a specified element.
var id = Utils.GetUniqueElementId(element);
if (name) {
if (Utils.__cache[id]) {
if (Utils.__cache[id][name] != null) {
return Utils.__cache[id][name];
}
return $(element).data(name); // Fallback to HTML5 data attribs.
}
return $(element).data(name); // Fallback to HTML5 data attribs.
} else {
return Utils.__cache[id];
}
};
Utils.RemoveData = function (element) {
// Removes all cached items for a specified element.
var id = Utils.GetUniqueElementId(element);
if (Utils.__cache[id] != null) {
delete Utils.__cache[id];
}
element.removeAttribute('data-select2-id');
};
return Utils; return Utils;
}); });
@@ -791,7 +855,7 @@ S2.define('select2/results',[
Results.prototype.render = function () { Results.prototype.render = function () {
var $results = $( var $results = $(
'<ul class="select2-results__options" role="tree"></ul>' '<ul class="select2-results__options" role="listbox"></ul>'
); );
if (this.options.get('multiple')) { if (this.options.get('multiple')) {
@@ -814,7 +878,7 @@ S2.define('select2/results',[
this.hideLoading(); this.hideLoading();
var $message = $( var $message = $(
'<li role="treeitem" aria-live="assertive"' + '<li role="alert" aria-live="assertive"' +
' class="select2-results__option"></li>' ' class="select2-results__option"></li>'
); );
@@ -907,7 +971,7 @@ S2.define('select2/results',[
$options.each(function () { $options.each(function () {
var $option = $(this); var $option = $(this);
var item = $.data(this, 'data'); var item = Utils.GetData(this, 'data');
// id needs to be converted to a string when comparing // id needs to be converted to a string when comparing
var id = '' + item.id; var id = '' + item.id;
@@ -948,11 +1012,16 @@ S2.define('select2/results',[
option.className = 'select2-results__option'; option.className = 'select2-results__option';
var attrs = { var attrs = {
'role': 'treeitem', 'role': 'option',
'aria-selected': 'false' 'aria-selected': 'false'
}; };
if (data.disabled) { var matches = window.Element.prototype.matches ||
window.Element.prototype.msMatchesSelector ||
window.Element.prototype.webkitMatchesSelector;
if ((data.element != null && matches.call(data.element, ':disabled')) ||
(data.element == null && data.disabled)) {
delete attrs['aria-selected']; delete attrs['aria-selected'];
attrs['aria-disabled'] = 'true'; attrs['aria-disabled'] = 'true';
} }
@@ -1012,7 +1081,7 @@ S2.define('select2/results',[
this.template(data, option); this.template(data, option);
} }
$.data(option, 'data', data); Utils.StoreData(option, 'data', data);
return option; return option;
}; };
@@ -1053,7 +1122,10 @@ S2.define('select2/results',[
} }
self.setClasses(); self.setClasses();
self.highlightFirstItem();
if (self.options.get('scrollAfterSelect')) {
self.highlightFirstItem();
}
}); });
container.on('unselect', function () { container.on('unselect', function () {
@@ -1062,7 +1134,10 @@ S2.define('select2/results',[
} }
self.setClasses(); self.setClasses();
self.highlightFirstItem();
if (self.options.get('scrollAfterSelect')) {
self.highlightFirstItem();
}
}); });
container.on('open', function () { container.on('open', function () {
@@ -1098,7 +1173,7 @@ S2.define('select2/results',[
return; return;
} }
var data = $highlighted.data('data'); var data = Utils.GetData($highlighted[0], 'data');
if ($highlighted.attr('aria-selected') == 'true') { if ($highlighted.attr('aria-selected') == 'true') {
self.trigger('close', {}); self.trigger('close', {});
@@ -1116,8 +1191,9 @@ S2.define('select2/results',[
var currentIndex = $options.index($highlighted); var currentIndex = $options.index($highlighted);
// If we are already at te top, don't move further // If we are already at the top, don't move further
if (currentIndex === 0) { // If no options, currentIndex will be -1
if (currentIndex <= 0) {
return; return;
} }
@@ -1210,7 +1286,7 @@ S2.define('select2/results',[
function (evt) { function (evt) {
var $this = $(this); var $this = $(this);
var data = $this.data('data'); var data = Utils.GetData(this, 'data');
if ($this.attr('aria-selected') === 'true') { if ($this.attr('aria-selected') === 'true') {
if (self.options.get('multiple')) { if (self.options.get('multiple')) {
@@ -1233,7 +1309,7 @@ S2.define('select2/results',[
this.$results.on('mouseenter', '.select2-results__option[aria-selected]', this.$results.on('mouseenter', '.select2-results__option[aria-selected]',
function (evt) { function (evt) {
var data = $(this).data('data'); var data = Utils.GetData(this, 'data');
self.getHighlightedResults() self.getHighlightedResults()
.removeClass('select2-results__option--highlighted'); .removeClass('select2-results__option--highlighted');
@@ -1348,14 +1424,15 @@ S2.define('select2/selection/base',[
this._tabindex = 0; this._tabindex = 0;
if (this.$element.data('old-tabindex') != null) { if (Utils.GetData(this.$element[0], 'old-tabindex') != null) {
this._tabindex = this.$element.data('old-tabindex'); this._tabindex = Utils.GetData(this.$element[0], 'old-tabindex');
} else if (this.$element.attr('tabindex') != null) { } else if (this.$element.attr('tabindex') != null) {
this._tabindex = this.$element.attr('tabindex'); this._tabindex = this.$element.attr('tabindex');
} }
$selection.attr('title', this.$element.attr('title')); $selection.attr('title', this.$element.attr('title'));
$selection.attr('tabindex', this._tabindex); $selection.attr('tabindex', this._tabindex);
$selection.attr('aria-disabled', 'false');
this.$selection = $selection; this.$selection = $selection;
@@ -1365,7 +1442,6 @@ S2.define('select2/selection/base',[
BaseSelection.prototype.bind = function (container, $container) { BaseSelection.prototype.bind = function (container, $container) {
var self = this; var self = this;
var id = container.id + '-container';
var resultsId = container.id + '-results'; var resultsId = container.id + '-results';
this.container = container; this.container = container;
@@ -1408,17 +1484,19 @@ S2.define('select2/selection/base',[
self.$selection.removeAttr('aria-activedescendant'); self.$selection.removeAttr('aria-activedescendant');
self.$selection.removeAttr('aria-owns'); self.$selection.removeAttr('aria-owns');
self.$selection.focus(); self.$selection.trigger('focus');
self._detachCloseHandler(container); self._detachCloseHandler(container);
}); });
container.on('enable', function () { container.on('enable', function () {
self.$selection.attr('tabindex', self._tabindex); self.$selection.attr('tabindex', self._tabindex);
self.$selection.attr('aria-disabled', 'false');
}); });
container.on('disable', function () { container.on('disable', function () {
self.$selection.attr('tabindex', '-1'); self.$selection.attr('tabindex', '-1');
self.$selection.attr('aria-disabled', 'true');
}); });
}; };
@@ -1441,7 +1519,6 @@ S2.define('select2/selection/base',[
}; };
BaseSelection.prototype._attachCloseHandler = function (container) { BaseSelection.prototype._attachCloseHandler = function (container) {
var self = this;
$(document.body).on('mousedown.select2.' + container.id, function (e) { $(document.body).on('mousedown.select2.' + container.id, function (e) {
var $target = $(e.target); var $target = $(e.target);
@@ -1451,13 +1528,11 @@ S2.define('select2/selection/base',[
var $all = $('.select2.select2-container--open'); var $all = $('.select2.select2-container--open');
$all.each(function () { $all.each(function () {
var $this = $(this);
if (this == $select[0]) { if (this == $select[0]) {
return; return;
} }
var $element = $this.data('element'); var $element = Utils.GetData(this, 'element');
$element.select2('close'); $element.select2('close');
}); });
@@ -1481,6 +1556,27 @@ S2.define('select2/selection/base',[
throw new Error('The `update` method must be defined in child classes.'); throw new Error('The `update` method must be defined in child classes.');
}; };
/**
* Helper method to abstract the "enabled" (not "disabled") state of this
* object.
*
* @return {true} if the instance is not disabled.
* @return {false} if the instance is disabled.
*/
BaseSelection.prototype.isEnabled = function () {
return !this.isDisabled();
};
/**
* Helper method to abstract the "disabled" state of this object.
*
* @return {true} if the disabled option is true.
* @return {false} if the disabled option is false.
*/
BaseSelection.prototype.isDisabled = function () {
return this.options.get('disabled');
};
return BaseSelection; return BaseSelection;
}); });
@@ -1518,7 +1614,10 @@ S2.define('select2/selection/single',[
var id = container.id + '-container'; var id = container.id + '-container';
this.$selection.find('.select2-selection__rendered').attr('id', id); this.$selection.find('.select2-selection__rendered')
.attr('id', id)
.attr('role', 'textbox')
.attr('aria-readonly', 'true');
this.$selection.attr('aria-labelledby', id); this.$selection.attr('aria-labelledby', id);
this.$selection.on('mousedown', function (evt) { this.$selection.on('mousedown', function (evt) {
@@ -1542,17 +1641,15 @@ S2.define('select2/selection/single',[
container.on('focus', function (evt) { container.on('focus', function (evt) {
if (!container.isOpen()) { if (!container.isOpen()) {
self.$selection.focus(); self.$selection.trigger('focus');
} }
}); });
container.on('selection:update', function (params) {
self.update(params.data);
});
}; };
SingleSelection.prototype.clear = function () { SingleSelection.prototype.clear = function () {
this.$selection.find('.select2-selection__rendered').empty(); var $rendered = this.$selection.find('.select2-selection__rendered');
$rendered.empty();
$rendered.removeAttr('title'); // clear tooltip on empty
}; };
SingleSelection.prototype.display = function (data, container) { SingleSelection.prototype.display = function (data, container) {
@@ -1578,7 +1675,14 @@ S2.define('select2/selection/single',[
var formatted = this.display(selection, $rendered); var formatted = this.display(selection, $rendered);
$rendered.empty().append(formatted); $rendered.empty().append(formatted);
$rendered.prop('title', selection.title || selection.text);
var title = selection.title || selection.text;
if (title) {
$rendered.attr('title', title);
} else {
$rendered.removeAttr('title');
}
}; };
return SingleSelection; return SingleSelection;
@@ -1623,14 +1727,14 @@ S2.define('select2/selection/multiple',[
'.select2-selection__choice__remove', '.select2-selection__choice__remove',
function (evt) { function (evt) {
// Ignore the event if it is disabled // Ignore the event if it is disabled
if (self.options.get('disabled')) { if (self.isDisabled()) {
return; return;
} }
var $remove = $(this); var $remove = $(this);
var $selection = $remove.parent(); var $selection = $remove.parent();
var data = $selection.data('data'); var data = Utils.GetData($selection[0], 'data');
self.trigger('unselect', { self.trigger('unselect', {
originalEvent: evt, originalEvent: evt,
@@ -1641,7 +1745,9 @@ S2.define('select2/selection/multiple',[
}; };
MultipleSelection.prototype.clear = function () { MultipleSelection.prototype.clear = function () {
this.$selection.find('.select2-selection__rendered').empty(); var $rendered = this.$selection.find('.select2-selection__rendered');
$rendered.empty();
$rendered.removeAttr('title');
}; };
MultipleSelection.prototype.display = function (data, container) { MultipleSelection.prototype.display = function (data, container) {
@@ -1679,9 +1785,14 @@ S2.define('select2/selection/multiple',[
var formatted = this.display(selection, $selection); var formatted = this.display(selection, $selection);
$selection.append(formatted); $selection.append(formatted);
$selection.prop('title', selection.title || selection.text);
$selection.data('data', selection); var title = selection.title || selection.text;
if (title) {
$selection.attr('title', title);
}
Utils.StoreData($selection[0], 'data', selection);
$selections.push($selection); $selections.push($selection);
} }
@@ -1746,8 +1857,9 @@ S2.define('select2/selection/placeholder',[
S2.define('select2/selection/allowClear',[ S2.define('select2/selection/allowClear',[
'jquery', 'jquery',
'../keys' '../keys',
], function ($, KEYS) { '../utils'
], function ($, KEYS, Utils) {
function AllowClear () { } function AllowClear () { }
AllowClear.prototype.bind = function (decorated, container, $container) { AllowClear.prototype.bind = function (decorated, container, $container) {
@@ -1776,7 +1888,7 @@ S2.define('select2/selection/allowClear',[
AllowClear.prototype._handleClear = function (_, evt) { AllowClear.prototype._handleClear = function (_, evt) {
// Ignore the event if it is disabled // Ignore the event if it is disabled
if (this.options.get('disabled')) { if (this.isDisabled()) {
return; return;
} }
@@ -1789,10 +1901,22 @@ S2.define('select2/selection/allowClear',[
evt.stopPropagation(); evt.stopPropagation();
var data = $clear.data('data'); var data = Utils.GetData($clear[0], 'data');
var previousVal = this.$element.val();
this.$element.val(this.placeholder.id);
var unselectData = {
data: data
};
this.trigger('clear', unselectData);
if (unselectData.prevented) {
this.$element.val(previousVal);
return;
}
for (var d = 0; d < data.length; d++) { for (var d = 0; d < data.length; d++) {
var unselectData = { unselectData = {
data: data[d] data: data[d]
}; };
@@ -1802,11 +1926,12 @@ S2.define('select2/selection/allowClear',[
// If the event was prevented, don't clear it out. // If the event was prevented, don't clear it out.
if (unselectData.prevented) { if (unselectData.prevented) {
this.$element.val(previousVal);
return; return;
} }
} }
this.$element.val(this.placeholder.id).trigger('change'); this.$element.trigger('input').trigger('change');
this.trigger('toggle', {}); this.trigger('toggle', {});
}; };
@@ -1829,12 +1954,14 @@ S2.define('select2/selection/allowClear',[
return; return;
} }
var removeAll = this.options.get('translations').get('removeAllItems');
var $remove = $( var $remove = $(
'<span class="select2-selection__clear">' + '<span class="select2-selection__clear" title="' + removeAll() +'">' +
'&times;' + '&times;' +
'</span>' '</span>'
); );
$remove.data('data', data); Utils.StoreData($remove[0], 'data', data);
this.$selection.find('.select2-selection__rendered').prepend($remove); this.$selection.find('.select2-selection__rendered').prepend($remove);
}; };
@@ -1856,7 +1983,7 @@ S2.define('select2/selection/search',[
'<li class="select2-search select2-search--inline">' + '<li class="select2-search select2-search--inline">' +
'<input class="select2-search__field" type="search" tabindex="-1"' + '<input class="select2-search__field" type="search" tabindex="-1"' +
' autocomplete="off" autocorrect="off" autocapitalize="none"' + ' autocomplete="off" autocorrect="off" autocapitalize="none"' +
' spellcheck="false" role="textbox" aria-autocomplete="list" />' + ' spellcheck="false" role="searchbox" aria-autocomplete="list" />' +
'</li>' '</li>'
); );
@@ -1873,14 +2000,18 @@ S2.define('select2/selection/search',[
Search.prototype.bind = function (decorated, container, $container) { Search.prototype.bind = function (decorated, container, $container) {
var self = this; var self = this;
var resultsId = container.id + '-results';
decorated.call(this, container, $container); decorated.call(this, container, $container);
container.on('open', function () { container.on('open', function () {
self.$search.attr('aria-controls', resultsId);
self.$search.trigger('focus'); self.$search.trigger('focus');
}); });
container.on('close', function () { container.on('close', function () {
self.$search.val(''); self.$search.val('');
self.$search.removeAttr('aria-controls');
self.$search.removeAttr('aria-activedescendant'); self.$search.removeAttr('aria-activedescendant');
self.$search.trigger('focus'); self.$search.trigger('focus');
}); });
@@ -1900,7 +2031,11 @@ S2.define('select2/selection/search',[
}); });
container.on('results:focus', function (params) { container.on('results:focus', function (params) {
self.$search.attr('aria-activedescendant', params.id); if (params.data._resultId) {
self.$search.attr('aria-activedescendant', params.data._resultId);
} else {
self.$search.removeAttr('aria-activedescendant');
}
}); });
this.$selection.on('focusin', '.select2-search--inline', function (evt) { this.$selection.on('focusin', '.select2-search--inline', function (evt) {
@@ -1925,7 +2060,7 @@ S2.define('select2/selection/search',[
.prev('.select2-selection__choice'); .prev('.select2-selection__choice');
if ($previousChoice.length > 0) { if ($previousChoice.length > 0) {
var item = $previousChoice.data('data'); var item = Utils.GetData($previousChoice[0], 'data');
self.searchRemoveChoice(item); self.searchRemoveChoice(item);
@@ -1934,6 +2069,12 @@ S2.define('select2/selection/search',[
} }
}); });
this.$selection.on('click', '.select2-search--inline', function (evt) {
if (self.$search.val()) {
evt.stopPropagation();
}
});
// Try to detect the IE version should the `documentMode` property that // Try to detect the IE version should the `documentMode` property that
// is stored on the document. This is only implemented in IE and is // is stored on the document. This is only implemented in IE and is
// slightly cleaner than doing a user agent check. // slightly cleaner than doing a user agent check.
@@ -2019,7 +2160,7 @@ S2.define('select2/selection/search',[
this.resizeSearch(); this.resizeSearch();
if (searchHadFocus) { if (searchHadFocus) {
this.$search.focus(); this.$search.trigger('focus');
} }
}; };
@@ -2052,7 +2193,7 @@ S2.define('select2/selection/search',[
var width = ''; var width = '';
if (this.$search.attr('placeholder') !== '') { if (this.$search.attr('placeholder') !== '') {
width = this.$selection.find('.select2-selection__rendered').innerWidth(); width = this.$selection.find('.select2-selection__rendered').width();
} else { } else {
var minimumWidth = this.$search.val().length + 1; var minimumWidth = this.$search.val().length + 1;
@@ -2076,10 +2217,13 @@ S2.define('select2/selection/eventRelay',[
'open', 'opening', 'open', 'opening',
'close', 'closing', 'close', 'closing',
'select', 'selecting', 'select', 'selecting',
'unselect', 'unselecting' 'unselect', 'unselecting',
'clear', 'clearing'
]; ];
var preventableEvents = ['opening', 'closing', 'selecting', 'unselecting']; var preventableEvents = [
'opening', 'closing', 'selecting', 'unselecting', 'clearing'
];
decorated.call(this, container, $container); decorated.call(this, container, $container);
@@ -2412,6 +2556,7 @@ S2.define('select2/diacritics',[
'\u019F': 'O', '\u019F': 'O',
'\uA74A': 'O', '\uA74A': 'O',
'\uA74C': 'O', '\uA74C': 'O',
'\u0152': 'OE',
'\u01A2': 'OI', '\u01A2': 'OI',
'\uA74E': 'OO', '\uA74E': 'OO',
'\u0222': 'OU', '\u0222': 'OU',
@@ -2821,6 +2966,7 @@ S2.define('select2/diacritics',[
'\uA74B': 'o', '\uA74B': 'o',
'\uA74D': 'o', '\uA74D': 'o',
'\u0275': 'o', '\u0275': 'o',
'\u0153': 'oe',
'\u01A3': 'oi', '\u01A3': 'oi',
'\u0223': 'ou', '\u0223': 'ou',
'\uA74F': 'oo', '\uA74F': 'oo',
@@ -2989,8 +3135,9 @@ S2.define('select2/diacritics',[
'\u03CD': '\u03C5', '\u03CD': '\u03C5',
'\u03CB': '\u03C5', '\u03CB': '\u03C5',
'\u03B0': '\u03C5', '\u03B0': '\u03C5',
'\u03C9': '\u03C9', '\u03CE': '\u03C9',
'\u03C2': '\u03C3' '\u03C2': '\u03C3',
'\u2019': '\''
}; };
return diacritics; return diacritics;
@@ -3075,7 +3222,7 @@ S2.define('select2/data/select',[
if ($(data.element).is('option')) { if ($(data.element).is('option')) {
data.element.selected = true; data.element.selected = true;
this.$element.trigger('change'); this.$element.trigger('input').trigger('change');
return; return;
} }
@@ -3096,13 +3243,13 @@ S2.define('select2/data/select',[
} }
self.$element.val(val); self.$element.val(val);
self.$element.trigger('change'); self.$element.trigger('input').trigger('change');
}); });
} else { } else {
var val = data.id; var val = data.id;
this.$element.val(val); this.$element.val(val);
this.$element.trigger('change'); this.$element.trigger('input').trigger('change');
} }
}; };
@@ -3118,7 +3265,7 @@ S2.define('select2/data/select',[
if ($(data.element).is('option')) { if ($(data.element).is('option')) {
data.element.selected = false; data.element.selected = false;
this.$element.trigger('change'); this.$element.trigger('input').trigger('change');
return; return;
} }
@@ -3136,7 +3283,7 @@ S2.define('select2/data/select',[
self.$element.val(val); self.$element.val(val);
self.$element.trigger('change'); self.$element.trigger('input').trigger('change');
}); });
}; };
@@ -3158,7 +3305,7 @@ S2.define('select2/data/select',[
// Remove anything added to child elements // Remove anything added to child elements
this.$element.find('*').each(function () { this.$element.find('*').each(function () {
// Remove any custom data set by Select2 // Remove any custom data set by Select2
$.removeData(this, 'data'); Utils.RemoveData(this);
}); });
}; };
@@ -3231,7 +3378,7 @@ S2.define('select2/data/select',[
normalizedData.element = option; normalizedData.element = option;
// Override the option's data with the combined data // Override the option's data with the combined data
$.data(option, 'data', normalizedData); Utils.StoreData(option, 'data', normalizedData);
return $option; return $option;
}; };
@@ -3239,7 +3386,7 @@ S2.define('select2/data/select',[
SelectAdapter.prototype.item = function ($option) { SelectAdapter.prototype.item = function ($option) {
var data = {}; var data = {};
data = $.data($option[0], 'data'); data = Utils.GetData($option[0], 'data');
if (data != null) { if (data != null) {
return data; return data;
@@ -3277,13 +3424,13 @@ S2.define('select2/data/select',[
data = this._normalizeItem(data); data = this._normalizeItem(data);
data.element = $option[0]; data.element = $option[0];
$.data($option[0], 'data', data); Utils.StoreData($option[0], 'data', data);
return data; return data;
}; };
SelectAdapter.prototype._normalizeItem = function (item) { SelectAdapter.prototype._normalizeItem = function (item) {
if (!$.isPlainObject(item)) { if (item !== Object(item)) {
item = { item = {
id: item, id: item,
text: item text: item
@@ -3329,15 +3476,19 @@ S2.define('select2/data/array',[
'jquery' 'jquery'
], function (SelectAdapter, Utils, $) { ], function (SelectAdapter, Utils, $) {
function ArrayAdapter ($element, options) { function ArrayAdapter ($element, options) {
var data = options.get('data') || []; this._dataToConvert = options.get('data') || [];
ArrayAdapter.__super__.constructor.call(this, $element, options); ArrayAdapter.__super__.constructor.call(this, $element, options);
this.addOptions(this.convertToOptions(data));
} }
Utils.Extend(ArrayAdapter, SelectAdapter); Utils.Extend(ArrayAdapter, SelectAdapter);
ArrayAdapter.prototype.bind = function (container, $container) {
ArrayAdapter.__super__.bind.call(this, container, $container);
this.addOptions(this.convertToOptions(this._dataToConvert));
};
ArrayAdapter.prototype.select = function (data) { ArrayAdapter.prototype.select = function (data) {
var $option = this.$element.find('option').filter(function (i, elm) { var $option = this.$element.find('option').filter(function (i, elm) {
return elm.value == data.id.toString(); return elm.value == data.id.toString();
@@ -3487,7 +3638,8 @@ S2.define('select2/data/ajax',[
}, function () { }, function () {
// Attempt to detect if a request was aborted // Attempt to detect if a request was aborted
// Only works if the transport exposes a status property // Only works if the transport exposes a status property
if ($request.status && $request.status === '0') { if ('status' in $request &&
($request.status === 0 || $request.status === '0')) {
return; return;
} }
@@ -3626,8 +3778,6 @@ S2.define('select2/data/tags',[
}; };
Tags.prototype._removeOldTags = function (_) { Tags.prototype._removeOldTags = function (_) {
var tag = this._lastTag;
var $options = this.$element.find('option[data-select2-tag]'); var $options = this.$element.find('option[data-select2-tag]');
$options.each(function () { $options.each(function () {
@@ -3702,7 +3852,7 @@ S2.define('select2/data/tokenizer',[
// Replace the search term if we have the search box // Replace the search term if we have the search box
if (this.$search.length) { if (this.$search.length) {
this.$search.val(tokenData.term); this.$search.val(tokenData.term);
this.$search.focus(); this.$search.trigger('focus');
} }
params.term = tokenData.term; params.term = tokenData.term;
@@ -3831,10 +3981,30 @@ S2.define('select2/data/maximumSelectionLength',[
decorated.call(this, $e, options); decorated.call(this, $e, options);
} }
MaximumSelectionLength.prototype.bind =
function (decorated, container, $container) {
var self = this;
decorated.call(this, container, $container);
container.on('select', function () {
self._checkIfMaximumSelected();
});
};
MaximumSelectionLength.prototype.query = MaximumSelectionLength.prototype.query =
function (decorated, params, callback) { function (decorated, params, callback) {
var self = this; var self = this;
this._checkIfMaximumSelected(function () {
decorated.call(self, params, callback);
});
};
MaximumSelectionLength.prototype._checkIfMaximumSelected =
function (_, successCallback) {
var self = this;
this.current(function (currentData) { this.current(function (currentData) {
var count = currentData != null ? currentData.length : 0; var count = currentData != null ? currentData.length : 0;
if (self.maximumSelectionLength > 0 && if (self.maximumSelectionLength > 0 &&
@@ -3847,7 +4017,10 @@ S2.define('select2/data/maximumSelectionLength',[
}); });
return; return;
} }
decorated.call(self, params, callback);
if (successCallback) {
successCallback();
}
}); });
}; };
@@ -3886,7 +4059,7 @@ S2.define('select2/dropdown',[
}; };
Dropdown.prototype.position = function ($dropdown, $container) { Dropdown.prototype.position = function ($dropdown, $container) {
// Should be implmented in subclasses // Should be implemented in subclasses
}; };
Dropdown.prototype.destroy = function () { Dropdown.prototype.destroy = function () {
@@ -3910,7 +4083,7 @@ S2.define('select2/dropdown/search',[
'<span class="select2-search select2-search--dropdown">' + '<span class="select2-search select2-search--dropdown">' +
'<input class="select2-search__field" type="search" tabindex="-1"' + '<input class="select2-search__field" type="search" tabindex="-1"' +
' autocomplete="off" autocorrect="off" autocapitalize="none"' + ' autocomplete="off" autocorrect="off" autocapitalize="none"' +
' spellcheck="false" role="textbox" />' + ' spellcheck="false" role="searchbox" aria-autocomplete="list" />' +
'</span>' '</span>'
); );
@@ -3925,6 +4098,8 @@ S2.define('select2/dropdown/search',[
Search.prototype.bind = function (decorated, container, $container) { Search.prototype.bind = function (decorated, container, $container) {
var self = this; var self = this;
var resultsId = container.id + '-results';
decorated.call(this, container, $container); decorated.call(this, container, $container);
this.$search.on('keydown', function (evt) { this.$search.on('keydown', function (evt) {
@@ -3947,23 +4122,27 @@ S2.define('select2/dropdown/search',[
container.on('open', function () { container.on('open', function () {
self.$search.attr('tabindex', 0); self.$search.attr('tabindex', 0);
self.$search.attr('aria-controls', resultsId);
self.$search.focus(); self.$search.trigger('focus');
window.setTimeout(function () { window.setTimeout(function () {
self.$search.focus(); self.$search.trigger('focus');
}, 0); }, 0);
}); });
container.on('close', function () { container.on('close', function () {
self.$search.attr('tabindex', -1); self.$search.attr('tabindex', -1);
self.$search.removeAttr('aria-controls');
self.$search.removeAttr('aria-activedescendant');
self.$search.val(''); self.$search.val('');
self.$search.trigger('blur');
}); });
container.on('focus', function () { container.on('focus', function () {
if (!container.isOpen()) { if (!container.isOpen()) {
self.$search.focus(); self.$search.trigger('focus');
} }
}); });
@@ -3978,6 +4157,14 @@ S2.define('select2/dropdown/search',[
} }
} }
}); });
container.on('results:focus', function (params) {
if (params.data._resultId) {
self.$search.attr('aria-activedescendant', params.data._resultId);
} else {
self.$search.removeAttr('aria-activedescendant');
}
});
}; };
Search.prototype.handleSearch = function (evt) { Search.prototype.handleSearch = function (evt) {
@@ -4062,6 +4249,7 @@ S2.define('select2/dropdown/infiniteScroll',[
if (this.showLoadingMore(data)) { if (this.showLoadingMore(data)) {
this.$results.append(this.$loadingMore); this.$results.append(this.$loadingMore);
this.loadMoreIfNeeded();
} }
}; };
@@ -4080,25 +4268,27 @@ S2.define('select2/dropdown/infiniteScroll',[
self.loading = true; self.loading = true;
}); });
this.$results.on('scroll', function () { this.$results.on('scroll', this.loadMoreIfNeeded.bind(this));
var isLoadMoreVisible = $.contains( };
document.documentElement,
self.$loadingMore[0]
);
if (self.loading || !isLoadMoreVisible) { InfiniteScroll.prototype.loadMoreIfNeeded = function () {
return; var isLoadMoreVisible = $.contains(
} document.documentElement,
this.$loadingMore[0]
);
var currentOffset = self.$results.offset().top + if (this.loading || !isLoadMoreVisible) {
self.$results.outerHeight(false); return;
var loadingMoreOffset = self.$loadingMore.offset().top + }
self.$loadingMore.outerHeight(false);
if (currentOffset + 50 >= loadingMoreOffset) { var currentOffset = this.$results.offset().top +
self.loadMore(); this.$results.outerHeight(false);
} var loadingMoreOffset = this.$loadingMore.offset().top +
}); this.$loadingMore.outerHeight(false);
if (currentOffset + 50 >= loadingMoreOffset) {
this.loadMore();
}
}; };
InfiniteScroll.prototype.loadMore = function () { InfiniteScroll.prototype.loadMore = function () {
@@ -4119,7 +4309,7 @@ S2.define('select2/dropdown/infiniteScroll',[
var $option = $( var $option = $(
'<li ' + '<li ' +
'class="select2-results__option select2-results__option--load-more"' + 'class="select2-results__option select2-results__option--load-more"' +
'role="treeitem" aria-disabled="true"></li>' 'role="option" aria-disabled="true"></li>'
); );
var message = this.options.get('translations').get('loadingMore'); var message = this.options.get('translations').get('loadingMore');
@@ -4137,7 +4327,7 @@ S2.define('select2/dropdown/attachBody',[
'../utils' '../utils'
], function ($, Utils) { ], function ($, Utils) {
function AttachBody (decorated, $element, options) { function AttachBody (decorated, $element, options) {
this.$dropdownParent = options.get('dropdownParent') || $(document.body); this.$dropdownParent = $(options.get('dropdownParent') || document.body);
decorated.call(this, $element, options); decorated.call(this, $element, options);
} }
@@ -4145,27 +4335,14 @@ S2.define('select2/dropdown/attachBody',[
AttachBody.prototype.bind = function (decorated, container, $container) { AttachBody.prototype.bind = function (decorated, container, $container) {
var self = this; var self = this;
var setupResultsEvents = false;
decorated.call(this, container, $container); decorated.call(this, container, $container);
container.on('open', function () { container.on('open', function () {
self._showDropdown(); self._showDropdown();
self._attachPositioningHandler(container); self._attachPositioningHandler(container);
if (!setupResultsEvents) { // Must bind after the results handlers to ensure correct sizing
setupResultsEvents = true; self._bindContainerResultHandlers(container);
container.on('results:all', function () {
self._positionDropdown();
self._resizeDropdown();
});
container.on('results:append', function () {
self._positionDropdown();
self._resizeDropdown();
});
}
}); });
container.on('close', function () { container.on('close', function () {
@@ -4214,6 +4391,44 @@ S2.define('select2/dropdown/attachBody',[
this.$dropdownContainer.detach(); this.$dropdownContainer.detach();
}; };
AttachBody.prototype._bindContainerResultHandlers =
function (decorated, container) {
// These should only be bound once
if (this._containerResultsHandlersBound) {
return;
}
var self = this;
container.on('results:all', function () {
self._positionDropdown();
self._resizeDropdown();
});
container.on('results:append', function () {
self._positionDropdown();
self._resizeDropdown();
});
container.on('results:message', function () {
self._positionDropdown();
self._resizeDropdown();
});
container.on('select', function () {
self._positionDropdown();
self._resizeDropdown();
});
container.on('unselect', function () {
self._positionDropdown();
self._resizeDropdown();
});
this._containerResultsHandlersBound = true;
};
AttachBody.prototype._attachPositioningHandler = AttachBody.prototype._attachPositioningHandler =
function (decorated, container) { function (decorated, container) {
var self = this; var self = this;
@@ -4224,14 +4439,14 @@ S2.define('select2/dropdown/attachBody',[
var $watchers = this.$container.parents().filter(Utils.hasScroll); var $watchers = this.$container.parents().filter(Utils.hasScroll);
$watchers.each(function () { $watchers.each(function () {
$(this).data('select2-scroll-position', { Utils.StoreData(this, 'select2-scroll-position', {
x: $(this).scrollLeft(), x: $(this).scrollLeft(),
y: $(this).scrollTop() y: $(this).scrollTop()
}); });
}); });
$watchers.on(scrollEvent, function (ev) { $watchers.on(scrollEvent, function (ev) {
var position = $(this).data('select2-scroll-position'); var position = Utils.GetData(this, 'select2-scroll-position');
$(this).scrollTop(position.y); $(this).scrollTop(position.y);
}); });
@@ -4290,16 +4505,26 @@ S2.define('select2/dropdown/attachBody',[
top: container.bottom top: container.bottom
}; };
// Determine what the parent element is to use for calciulating the offset // Determine what the parent element is to use for calculating the offset
var $offsetParent = this.$dropdownParent; var $offsetParent = this.$dropdownParent;
// For statically positoned elements, we need to get the element // For statically positioned elements, we need to get the element
// that is determining the offset // that is determining the offset
if ($offsetParent.css('position') === 'static') { if ($offsetParent.css('position') === 'static') {
$offsetParent = $offsetParent.offsetParent(); $offsetParent = $offsetParent.offsetParent();
} }
var parentOffset = $offsetParent.offset(); var parentOffset = {
top: 0,
left: 0
};
if (
$.contains(document.body, $offsetParent[0]) ||
$offsetParent[0].isConnected
) {
parentOffset = $offsetParent.offset();
}
css.top -= parentOffset.top; css.top -= parentOffset.top;
css.left -= parentOffset.left; css.left -= parentOffset.left;
@@ -4396,8 +4621,8 @@ S2.define('select2/dropdown/minimumResultsForSearch',[
}); });
S2.define('select2/dropdown/selectOnClose',[ S2.define('select2/dropdown/selectOnClose',[
'../utils'
], function () { ], function (Utils) {
function SelectOnClose () { } function SelectOnClose () { }
SelectOnClose.prototype.bind = function (decorated, container, $container) { SelectOnClose.prototype.bind = function (decorated, container, $container) {
@@ -4428,7 +4653,7 @@ S2.define('select2/dropdown/selectOnClose',[
return; return;
} }
var data = $highlightedResults.data('data'); var data = Utils.GetData($highlightedResults[0], 'data');
// Don't re-select already selected resulte // Don't re-select already selected resulte
if ( if (
@@ -4469,7 +4694,7 @@ S2.define('select2/dropdown/closeOnSelect',[
var originalEvent = evt.originalEvent; var originalEvent = evt.originalEvent;
// Don't close if the control key is being held // Don't close if the control key is being held
if (originalEvent && originalEvent.ctrlKey) { if (originalEvent && (originalEvent.ctrlKey || originalEvent.metaKey)) {
return; return;
} }
@@ -4523,6 +4748,9 @@ S2.define('select2/i18n/en',[],function () {
}, },
searching: function () { searching: function () {
return 'Searching…'; return 'Searching…';
},
removeAllItems: function () {
return 'Remove all items';
} }
}; };
}); });
@@ -4761,66 +4989,29 @@ S2.define('select2/defaults',[
); );
} }
if (typeof options.language === 'string') { // If the defaults were not previously applied from an element, it is
// Check if the language is specified with a region // possible for the language option to have not been resolved
if (options.language.indexOf('-') > 0) { options.language = this._resolveLanguage(options.language);
// Extract the region information if it is included
var languageParts = options.language.split('-');
var baseLanguage = languageParts[0];
options.language = [options.language, baseLanguage]; // Always fall back to English since it will always be complete
} else { options.language.push('en');
options.language = [options.language];
var uniqueLanguages = [];
for (var l = 0; l < options.language.length; l++) {
var language = options.language[l];
if (uniqueLanguages.indexOf(language) === -1) {
uniqueLanguages.push(language);
} }
} }
if ($.isArray(options.language)) { options.language = uniqueLanguages;
var languages = new Translation();
options.language.push('en');
var languageNames = options.language; options.translations = this._processTranslations(
options.language,
for (var l = 0; l < languageNames.length; l++) { options.debug
var name = languageNames[l]; );
var language = {};
try {
// Try to load it with the original name
language = Translation.loadPath(name);
} catch (e) {
try {
// If we couldn't load it, check if it wasn't the full path
name = this.defaults.amdLanguageBase + name;
language = Translation.loadPath(name);
} catch (ex) {
// The translation could not be loaded at all. Sometimes this is
// because of a configuration problem, other times this can be
// because of how Select2 helps load all possible translation files.
if (options.debug && window.console && console.warn) {
console.warn(
'Select2: The language file for "' + name + '" could not be ' +
'automatically loaded. A fallback will be used instead.'
);
}
continue;
}
}
languages.extend(language);
}
options.translations = languages;
} else {
var baseTranslation = Translation.loadPath(
this.defaults.amdLanguageBase + 'en'
);
var customTranslation = new Translation(options.language);
customTranslation.extend(baseTranslation);
options.translations = customTranslation;
}
return options; return options;
}; };
@@ -4887,13 +5078,14 @@ S2.define('select2/defaults',[
debug: false, debug: false,
dropdownAutoWidth: false, dropdownAutoWidth: false,
escapeMarkup: Utils.escapeMarkup, escapeMarkup: Utils.escapeMarkup,
language: EnglishTranslation, language: {},
matcher: matcher, matcher: matcher,
minimumInputLength: 0, minimumInputLength: 0,
maximumInputLength: 0, maximumInputLength: 0,
maximumSelectionLength: 0, maximumSelectionLength: 0,
minimumResultsForSearch: 0, minimumResultsForSearch: 0,
selectOnClose: false, selectOnClose: false,
scrollAfterSelect: false,
sorter: function (data) { sorter: function (data) {
return data; return data;
}, },
@@ -4908,6 +5100,103 @@ S2.define('select2/defaults',[
}; };
}; };
Defaults.prototype.applyFromElement = function (options, $element) {
var optionLanguage = options.language;
var defaultLanguage = this.defaults.language;
var elementLanguage = $element.prop('lang');
var parentLanguage = $element.closest('[lang]').prop('lang');
var languages = Array.prototype.concat.call(
this._resolveLanguage(elementLanguage),
this._resolveLanguage(optionLanguage),
this._resolveLanguage(defaultLanguage),
this._resolveLanguage(parentLanguage)
);
options.language = languages;
return options;
};
Defaults.prototype._resolveLanguage = function (language) {
if (!language) {
return [];
}
if ($.isEmptyObject(language)) {
return [];
}
if ($.isPlainObject(language)) {
return [language];
}
var languages;
if (!$.isArray(language)) {
languages = [language];
} else {
languages = language;
}
var resolvedLanguages = [];
for (var l = 0; l < languages.length; l++) {
resolvedLanguages.push(languages[l]);
if (typeof languages[l] === 'string' && languages[l].indexOf('-') > 0) {
// Extract the region information if it is included
var languageParts = languages[l].split('-');
var baseLanguage = languageParts[0];
resolvedLanguages.push(baseLanguage);
}
}
return resolvedLanguages;
};
Defaults.prototype._processTranslations = function (languages, debug) {
var translations = new Translation();
for (var l = 0; l < languages.length; l++) {
var languageData = new Translation();
var language = languages[l];
if (typeof language === 'string') {
try {
// Try to load it with the original name
languageData = Translation.loadPath(language);
} catch (e) {
try {
// If we couldn't load it, check if it wasn't the full path
language = this.defaults.amdLanguageBase + language;
languageData = Translation.loadPath(language);
} catch (ex) {
// The translation could not be loaded at all. Sometimes this is
// because of a configuration problem, other times this can be
// because of how Select2 helps load all possible translation files
if (debug && window.console && console.warn) {
console.warn(
'Select2: The language file for "' + language + '" could ' +
'not be automatically loaded. A fallback will be used instead.'
);
}
}
}
} else if ($.isPlainObject(language)) {
languageData = new Translation(language);
} else {
languageData = language;
}
translations.extend(languageData);
}
return translations;
};
Defaults.prototype.set = function (key, value) { Defaults.prototype.set = function (key, value) {
var camelKey = $.camelCase(key); var camelKey = $.camelCase(key);
@@ -4916,7 +5205,7 @@ S2.define('select2/defaults',[
var convertedData = Utils._convertData(data); var convertedData = Utils._convertData(data);
$.extend(this.defaults, convertedData); $.extend(true, this.defaults, convertedData);
}; };
var defaults = new Defaults(); var defaults = new Defaults();
@@ -4937,6 +5226,10 @@ S2.define('select2/options',[
this.fromElement($element); this.fromElement($element);
} }
if ($element != null) {
this.options = Defaults.applyFromElement(this.options, $element);
}
this.options = Defaults.apply(this.options); this.options = Defaults.apply(this.options);
if ($element && $element.is('input')) { if ($element && $element.is('input')) {
@@ -4960,14 +5253,6 @@ S2.define('select2/options',[
this.options.disabled = $e.prop('disabled'); this.options.disabled = $e.prop('disabled');
} }
if (this.options.language == null) {
if ($e.prop('lang')) {
this.options.language = $e.prop('lang').toLowerCase();
} else if ($e.closest('[lang]').prop('lang')) {
this.options.language = $e.closest('[lang]').prop('lang');
}
}
if (this.options.dir == null) { if (this.options.dir == null) {
if ($e.prop('dir')) { if ($e.prop('dir')) {
this.options.dir = $e.prop('dir'); this.options.dir = $e.prop('dir');
@@ -4981,7 +5266,7 @@ S2.define('select2/options',[
$e.prop('disabled', this.options.disabled); $e.prop('disabled', this.options.disabled);
$e.prop('multiple', this.options.multiple); $e.prop('multiple', this.options.multiple);
if ($e.data('select2Tags')) { if (Utils.GetData($e[0], 'select2Tags')) {
if (this.options.debug && window.console && console.warn) { if (this.options.debug && window.console && console.warn) {
console.warn( console.warn(
'Select2: The `data-select2-tags` attribute has been changed to ' + 'Select2: The `data-select2-tags` attribute has been changed to ' +
@@ -4990,11 +5275,11 @@ S2.define('select2/options',[
); );
} }
$e.data('data', $e.data('select2Tags')); Utils.StoreData($e[0], 'data', Utils.GetData($e[0], 'select2Tags'));
$e.data('tags', true); Utils.StoreData($e[0], 'tags', true);
} }
if ($e.data('ajaxUrl')) { if (Utils.GetData($e[0], 'ajaxUrl')) {
if (this.options.debug && window.console && console.warn) { if (this.options.debug && window.console && console.warn) {
console.warn( console.warn(
'Select2: The `data-ajax-url` attribute has been changed to ' + 'Select2: The `data-ajax-url` attribute has been changed to ' +
@@ -5003,21 +5288,45 @@ S2.define('select2/options',[
); );
} }
$e.attr('ajax--url', $e.data('ajaxUrl')); $e.attr('ajax--url', Utils.GetData($e[0], 'ajaxUrl'));
$e.data('ajax--url', $e.data('ajaxUrl')); Utils.StoreData($e[0], 'ajax-Url', Utils.GetData($e[0], 'ajaxUrl'));
} }
var dataset = {}; var dataset = {};
function upperCaseLetter(_, letter) {
return letter.toUpperCase();
}
// Pre-load all of the attributes which are prefixed with `data-`
for (var attr = 0; attr < $e[0].attributes.length; attr++) {
var attributeName = $e[0].attributes[attr].name;
var prefix = 'data-';
if (attributeName.substr(0, prefix.length) == prefix) {
// Get the contents of the attribute after `data-`
var dataName = attributeName.substring(prefix.length);
// Get the data contents from the consistent source
// This is more than likely the jQuery data helper
var dataValue = Utils.GetData($e[0], dataName);
// camelCase the attribute name to match the spec
var camelDataName = dataName.replace(/-([a-z])/g, upperCaseLetter);
// Store the data attribute contents into the dataset since
dataset[camelDataName] = dataValue;
}
}
// Prefer the element's `dataset` attribute if it exists // Prefer the element's `dataset` attribute if it exists
// jQuery 1.x does not correctly handle data attributes with multiple dashes // jQuery 1.x does not correctly handle data attributes with multiple dashes
if ($.fn.jquery && $.fn.jquery.substr(0, 2) == '1.' && $e[0].dataset) { if ($.fn.jquery && $.fn.jquery.substr(0, 2) == '1.' && $e[0].dataset) {
dataset = $.extend(true, {}, $e[0].dataset, $e.data()); dataset = $.extend(true, {}, $e[0].dataset, dataset);
} else {
dataset = $e.data();
} }
var data = $.extend(true, {}, dataset); // Prefer our internal data cache if it exists
var data = $.extend(true, {}, Utils.GetData($e[0]), dataset);
data = Utils._convertData(data); data = Utils._convertData(data);
@@ -5054,8 +5363,8 @@ S2.define('select2/core',[
'./keys' './keys'
], function ($, Options, Utils, KEYS) { ], function ($, Options, Utils, KEYS) {
var Select2 = function ($element, options) { var Select2 = function ($element, options) {
if ($element.data('select2') != null) { if (Utils.GetData($element[0], 'select2') != null) {
$element.data('select2').destroy(); Utils.GetData($element[0], 'select2').destroy();
} }
this.$element = $element; this.$element = $element;
@@ -5071,7 +5380,7 @@ S2.define('select2/core',[
// Set up the tabindex // Set up the tabindex
var tabindex = $element.attr('tabindex') || 0; var tabindex = $element.attr('tabindex') || 0;
$element.data('old-tabindex', tabindex); Utils.StoreData($element[0], 'old-tabindex', tabindex);
$element.attr('tabindex', '-1'); $element.attr('tabindex', '-1');
// Set up containers and adapters // Set up containers and adapters
@@ -5132,6 +5441,9 @@ S2.define('select2/core',[
// Synchronize any monitored attributes // Synchronize any monitored attributes
this._syncAttributes(); this._syncAttributes();
Utils.StoreData($element[0], 'select2', this);
// Ensure backwards compatibility with $element.data('select2').
$element.data('select2', this); $element.data('select2', this);
}; };
@@ -5208,6 +5520,12 @@ S2.define('select2/core',[
return null; return null;
} }
if (method == 'computedstyle') {
var computedStyle = window.getComputedStyle($element[0]);
return computedStyle.width;
}
return method; return method;
}; };
@@ -5248,8 +5566,8 @@ S2.define('select2/core',[
if (observer != null) { if (observer != null) {
this._observer = new observer(function (mutations) { this._observer = new observer(function (mutations) {
$.each(mutations, self._syncA); self._syncA();
$.each(mutations, self._syncS); self._syncS(null, mutations);
}); });
this._observer.observe(this.$element[0], { this._observer.observe(this.$element[0], {
attributes: true, attributes: true,
@@ -5371,7 +5689,7 @@ S2.define('select2/core',[
if (self.isOpen()) { if (self.isOpen()) {
if (key === KEYS.ESC || key === KEYS.TAB || if (key === KEYS.ESC || key === KEYS.TAB ||
(key === KEYS.UP && evt.altKey)) { (key === KEYS.UP && evt.altKey)) {
self.close(); self.close(evt);
evt.preventDefault(); evt.preventDefault();
} else if (key === KEYS.ENTER) { } else if (key === KEYS.ENTER) {
@@ -5405,7 +5723,7 @@ S2.define('select2/core',[
Select2.prototype._syncAttributes = function () { Select2.prototype._syncAttributes = function () {
this.options.set('disabled', this.$element.prop('disabled')); this.options.set('disabled', this.$element.prop('disabled'));
if (this.options.get('disabled')) { if (this.isDisabled()) {
if (this.isOpen()) { if (this.isOpen()) {
this.close(); this.close();
} }
@@ -5416,7 +5734,7 @@ S2.define('select2/core',[
} }
}; };
Select2.prototype._syncSubtree = function (evt, mutations) { Select2.prototype._isChangeMutation = function (evt, mutations) {
var changed = false; var changed = false;
var self = this; var self = this;
@@ -5444,7 +5762,22 @@ S2.define('select2/core',[
} }
} else if (mutations.removedNodes && mutations.removedNodes.length > 0) { } else if (mutations.removedNodes && mutations.removedNodes.length > 0) {
changed = true; changed = true;
} else if ($.isArray(mutations)) {
$.each(mutations, function(evt, mutation) {
if (self._isChangeMutation(evt, mutation)) {
// We've found a change mutation.
// Let's escape from the loop and continue
changed = true;
return false;
}
});
} }
return changed;
};
Select2.prototype._syncSubtree = function (evt, mutations) {
var changed = this._isChangeMutation(evt, mutations);
var self = this;
// Only re-pull the data if we think there is a change // Only re-pull the data if we think there is a change
if (changed) { if (changed) {
@@ -5466,7 +5799,8 @@ S2.define('select2/core',[
'open': 'opening', 'open': 'opening',
'close': 'closing', 'close': 'closing',
'select': 'selecting', 'select': 'selecting',
'unselect': 'unselecting' 'unselect': 'unselecting',
'clear': 'clearing'
}; };
if (args === undefined) { if (args === undefined) {
@@ -5494,7 +5828,7 @@ S2.define('select2/core',[
}; };
Select2.prototype.toggleDropdown = function () { Select2.prototype.toggleDropdown = function () {
if (this.options.get('disabled')) { if (this.isDisabled()) {
return; return;
} }
@@ -5510,15 +5844,40 @@ S2.define('select2/core',[
return; return;
} }
if (this.isDisabled()) {
return;
}
this.trigger('query', {}); this.trigger('query', {});
}; };
Select2.prototype.close = function () { Select2.prototype.close = function (evt) {
if (!this.isOpen()) { if (!this.isOpen()) {
return; return;
} }
this.trigger('close', {}); this.trigger('close', { originalEvent : evt });
};
/**
* Helper method to abstract the "enabled" (not "disabled") state of this
* object.
*
* @return {true} if the instance is not disabled.
* @return {false} if the instance is disabled.
*/
Select2.prototype.isEnabled = function () {
return !this.isDisabled();
};
/**
* Helper method to abstract the "disabled" state of this object.
*
* @return {true} if the disabled option is true.
* @return {false} if the disabled option is false.
*/
Select2.prototype.isDisabled = function () {
return this.options.get('disabled');
}; };
Select2.prototype.isOpen = function () { Select2.prototype.isOpen = function () {
@@ -5595,7 +5954,7 @@ S2.define('select2/core',[
}); });
} }
this.$element.val(newVal).trigger('change'); this.$element.val(newVal).trigger('input').trigger('change');
}; };
Select2.prototype.destroy = function () { Select2.prototype.destroy = function () {
@@ -5621,10 +5980,12 @@ S2.define('select2/core',[
this._syncS = null; this._syncS = null;
this.$element.off('.select2'); this.$element.off('.select2');
this.$element.attr('tabindex', this.$element.data('old-tabindex')); this.$element.attr('tabindex',
Utils.GetData(this.$element[0], 'old-tabindex'));
this.$element.removeClass('select2-hidden-accessible'); this.$element.removeClass('select2-hidden-accessible');
this.$element.attr('aria-hidden', 'false'); this.$element.attr('aria-hidden', 'false');
Utils.RemoveData(this.$element[0]);
this.$element.removeData('select2'); this.$element.removeData('select2');
this.dataAdapter.destroy(); this.dataAdapter.destroy();
@@ -5652,7 +6013,7 @@ S2.define('select2/core',[
this.$container.addClass('select2-container--' + this.options.get('theme')); this.$container.addClass('select2-container--' + this.options.get('theme'));
$container.data('element', this.$element); Utils.StoreData($container[0], 'element', this.$element);
return $container; return $container;
}; };
@@ -5862,8 +6223,9 @@ S2.define('select2/compat/initSelection',[
}); });
S2.define('select2/compat/inputData',[ S2.define('select2/compat/inputData',[
'jquery' 'jquery',
], function ($) { '../utils'
], function ($, Utils) {
function InputData (decorated, $element, options) { function InputData (decorated, $element, options) {
this._currentData = []; this._currentData = [];
this._valueSeparator = options.get('valueSeparator') || ','; this._valueSeparator = options.get('valueSeparator') || ',';
@@ -5927,13 +6289,13 @@ S2.define('select2/compat/inputData',[
}); });
this.$element.val(data.id); this.$element.val(data.id);
this.$element.trigger('change'); this.$element.trigger('input').trigger('change');
} else { } else {
var value = this.$element.val(); var value = this.$element.val();
value += this._valueSeparator + data.id; value += this._valueSeparator + data.id;
this.$element.val(value); this.$element.val(value);
this.$element.trigger('change'); this.$element.trigger('input').trigger('change');
} }
}; };
@@ -5956,7 +6318,7 @@ S2.define('select2/compat/inputData',[
} }
self.$element.val(values.join(self._valueSeparator)); self.$element.val(values.join(self._valueSeparator));
self.$element.trigger('change'); self.$element.trigger('input').trigger('change');
}); });
}; };
@@ -5980,7 +6342,7 @@ S2.define('select2/compat/inputData',[
InputData.prototype.addOptions = function (_, $options) { InputData.prototype.addOptions = function (_, $options) {
var options = $.map($options, function ($option) { var options = $.map($options, function ($option) {
return $.data($option[0], 'data'); return Utils.GetData($option[0], 'data');
}); });
this._currentData.push.apply(this._currentData, options); this._currentData.push.apply(this._currentData, options);
@@ -6383,8 +6745,9 @@ S2.define('jquery.select2',[
'jquery-mousewheel', 'jquery-mousewheel',
'./select2/core', './select2/core',
'./select2/defaults' './select2/defaults',
], function ($, _, Select2, Defaults) { './select2/utils'
], function ($, _, Select2, Defaults, Utils) {
if ($.fn.select2 == null) { if ($.fn.select2 == null) {
// All methods that should return the element // All methods that should return the element
var thisMethods = ['open', 'close', 'destroy']; var thisMethods = ['open', 'close', 'destroy'];
@@ -6405,7 +6768,7 @@ S2.define('jquery.select2',[
var args = Array.prototype.slice.call(arguments, 1); var args = Array.prototype.slice.call(arguments, 1);
this.each(function () { this.each(function () {
var instance = $(this).data('select2'); var instance = Utils.GetData(this, 'select2');
if (instance == null && window.console && console.error) { if (instance == null && window.console && console.error) {
console.error( console.error(
+2 -1
View File
File diff suppressed because one or more lines are too long
+576 -214
View File
@@ -1,11 +1,11 @@
/*! /*!
* Select2 4.0.5 * Select2 4.0.13
* https://select2.github.io * https://select2.github.io
* *
* Released under the MIT license * Released under the MIT license
* https://github.com/select2/select2/blob/master/LICENSE.md * https://github.com/select2/select2/blob/master/LICENSE.md
*/ */
(function (factory) { ;(function (factory) {
if (typeof define === 'function' && define.amd) { if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module. // AMD. Register as an anonymous module.
define(['jquery'], factory); define(['jquery'], factory);
@@ -574,10 +574,10 @@ S2.define('select2/utils',[
DecoratedClass.prototype = new ctr(); DecoratedClass.prototype = new ctr();
for (var m = 0; m < superMethods.length; m++) { for (var m = 0; m < superMethods.length; m++) {
var superMethod = superMethods[m]; var superMethod = superMethods[m];
DecoratedClass.prototype[superMethod] = DecoratedClass.prototype[superMethod] =
SuperClass.prototype[superMethod]; SuperClass.prototype[superMethod];
} }
var calledMethod = function (methodName) { var calledMethod = function (methodName) {
@@ -772,6 +772,70 @@ S2.define('select2/utils',[
$element.append($nodes); $element.append($nodes);
}; };
// Cache objects in Utils.__cache instead of $.data (see #4346)
Utils.__cache = {};
var id = 0;
Utils.GetUniqueElementId = function (element) {
// Get a unique element Id. If element has no id,
// creates a new unique number, stores it in the id
// attribute and returns the new id.
// If an id already exists, it simply returns it.
var select2Id = element.getAttribute('data-select2-id');
if (select2Id == null) {
// If element has id, use it.
if (element.id) {
select2Id = element.id;
element.setAttribute('data-select2-id', select2Id);
} else {
element.setAttribute('data-select2-id', ++id);
select2Id = id.toString();
}
}
return select2Id;
};
Utils.StoreData = function (element, name, value) {
// Stores an item in the cache for a specified element.
// name is the cache key.
var id = Utils.GetUniqueElementId(element);
if (!Utils.__cache[id]) {
Utils.__cache[id] = {};
}
Utils.__cache[id][name] = value;
};
Utils.GetData = function (element, name) {
// Retrieves a value from the cache by its key (name)
// name is optional. If no name specified, return
// all cache items for the specified element.
// and for a specified element.
var id = Utils.GetUniqueElementId(element);
if (name) {
if (Utils.__cache[id]) {
if (Utils.__cache[id][name] != null) {
return Utils.__cache[id][name];
}
return $(element).data(name); // Fallback to HTML5 data attribs.
}
return $(element).data(name); // Fallback to HTML5 data attribs.
} else {
return Utils.__cache[id];
}
};
Utils.RemoveData = function (element) {
// Removes all cached items for a specified element.
var id = Utils.GetUniqueElementId(element);
if (Utils.__cache[id] != null) {
delete Utils.__cache[id];
}
element.removeAttribute('data-select2-id');
};
return Utils; return Utils;
}); });
@@ -791,7 +855,7 @@ S2.define('select2/results',[
Results.prototype.render = function () { Results.prototype.render = function () {
var $results = $( var $results = $(
'<ul class="select2-results__options" role="tree"></ul>' '<ul class="select2-results__options" role="listbox"></ul>'
); );
if (this.options.get('multiple')) { if (this.options.get('multiple')) {
@@ -814,7 +878,7 @@ S2.define('select2/results',[
this.hideLoading(); this.hideLoading();
var $message = $( var $message = $(
'<li role="treeitem" aria-live="assertive"' + '<li role="alert" aria-live="assertive"' +
' class="select2-results__option"></li>' ' class="select2-results__option"></li>'
); );
@@ -907,7 +971,7 @@ S2.define('select2/results',[
$options.each(function () { $options.each(function () {
var $option = $(this); var $option = $(this);
var item = $.data(this, 'data'); var item = Utils.GetData(this, 'data');
// id needs to be converted to a string when comparing // id needs to be converted to a string when comparing
var id = '' + item.id; var id = '' + item.id;
@@ -948,11 +1012,16 @@ S2.define('select2/results',[
option.className = 'select2-results__option'; option.className = 'select2-results__option';
var attrs = { var attrs = {
'role': 'treeitem', 'role': 'option',
'aria-selected': 'false' 'aria-selected': 'false'
}; };
if (data.disabled) { var matches = window.Element.prototype.matches ||
window.Element.prototype.msMatchesSelector ||
window.Element.prototype.webkitMatchesSelector;
if ((data.element != null && matches.call(data.element, ':disabled')) ||
(data.element == null && data.disabled)) {
delete attrs['aria-selected']; delete attrs['aria-selected'];
attrs['aria-disabled'] = 'true'; attrs['aria-disabled'] = 'true';
} }
@@ -1012,7 +1081,7 @@ S2.define('select2/results',[
this.template(data, option); this.template(data, option);
} }
$.data(option, 'data', data); Utils.StoreData(option, 'data', data);
return option; return option;
}; };
@@ -1053,7 +1122,10 @@ S2.define('select2/results',[
} }
self.setClasses(); self.setClasses();
self.highlightFirstItem();
if (self.options.get('scrollAfterSelect')) {
self.highlightFirstItem();
}
}); });
container.on('unselect', function () { container.on('unselect', function () {
@@ -1062,7 +1134,10 @@ S2.define('select2/results',[
} }
self.setClasses(); self.setClasses();
self.highlightFirstItem();
if (self.options.get('scrollAfterSelect')) {
self.highlightFirstItem();
}
}); });
container.on('open', function () { container.on('open', function () {
@@ -1098,7 +1173,7 @@ S2.define('select2/results',[
return; return;
} }
var data = $highlighted.data('data'); var data = Utils.GetData($highlighted[0], 'data');
if ($highlighted.attr('aria-selected') == 'true') { if ($highlighted.attr('aria-selected') == 'true') {
self.trigger('close', {}); self.trigger('close', {});
@@ -1116,8 +1191,9 @@ S2.define('select2/results',[
var currentIndex = $options.index($highlighted); var currentIndex = $options.index($highlighted);
// If we are already at te top, don't move further // If we are already at the top, don't move further
if (currentIndex === 0) { // If no options, currentIndex will be -1
if (currentIndex <= 0) {
return; return;
} }
@@ -1210,7 +1286,7 @@ S2.define('select2/results',[
function (evt) { function (evt) {
var $this = $(this); var $this = $(this);
var data = $this.data('data'); var data = Utils.GetData(this, 'data');
if ($this.attr('aria-selected') === 'true') { if ($this.attr('aria-selected') === 'true') {
if (self.options.get('multiple')) { if (self.options.get('multiple')) {
@@ -1233,7 +1309,7 @@ S2.define('select2/results',[
this.$results.on('mouseenter', '.select2-results__option[aria-selected]', this.$results.on('mouseenter', '.select2-results__option[aria-selected]',
function (evt) { function (evt) {
var data = $(this).data('data'); var data = Utils.GetData(this, 'data');
self.getHighlightedResults() self.getHighlightedResults()
.removeClass('select2-results__option--highlighted'); .removeClass('select2-results__option--highlighted');
@@ -1348,14 +1424,15 @@ S2.define('select2/selection/base',[
this._tabindex = 0; this._tabindex = 0;
if (this.$element.data('old-tabindex') != null) { if (Utils.GetData(this.$element[0], 'old-tabindex') != null) {
this._tabindex = this.$element.data('old-tabindex'); this._tabindex = Utils.GetData(this.$element[0], 'old-tabindex');
} else if (this.$element.attr('tabindex') != null) { } else if (this.$element.attr('tabindex') != null) {
this._tabindex = this.$element.attr('tabindex'); this._tabindex = this.$element.attr('tabindex');
} }
$selection.attr('title', this.$element.attr('title')); $selection.attr('title', this.$element.attr('title'));
$selection.attr('tabindex', this._tabindex); $selection.attr('tabindex', this._tabindex);
$selection.attr('aria-disabled', 'false');
this.$selection = $selection; this.$selection = $selection;
@@ -1365,7 +1442,6 @@ S2.define('select2/selection/base',[
BaseSelection.prototype.bind = function (container, $container) { BaseSelection.prototype.bind = function (container, $container) {
var self = this; var self = this;
var id = container.id + '-container';
var resultsId = container.id + '-results'; var resultsId = container.id + '-results';
this.container = container; this.container = container;
@@ -1408,17 +1484,19 @@ S2.define('select2/selection/base',[
self.$selection.removeAttr('aria-activedescendant'); self.$selection.removeAttr('aria-activedescendant');
self.$selection.removeAttr('aria-owns'); self.$selection.removeAttr('aria-owns');
self.$selection.focus(); self.$selection.trigger('focus');
self._detachCloseHandler(container); self._detachCloseHandler(container);
}); });
container.on('enable', function () { container.on('enable', function () {
self.$selection.attr('tabindex', self._tabindex); self.$selection.attr('tabindex', self._tabindex);
self.$selection.attr('aria-disabled', 'false');
}); });
container.on('disable', function () { container.on('disable', function () {
self.$selection.attr('tabindex', '-1'); self.$selection.attr('tabindex', '-1');
self.$selection.attr('aria-disabled', 'true');
}); });
}; };
@@ -1441,7 +1519,6 @@ S2.define('select2/selection/base',[
}; };
BaseSelection.prototype._attachCloseHandler = function (container) { BaseSelection.prototype._attachCloseHandler = function (container) {
var self = this;
$(document.body).on('mousedown.select2.' + container.id, function (e) { $(document.body).on('mousedown.select2.' + container.id, function (e) {
var $target = $(e.target); var $target = $(e.target);
@@ -1451,13 +1528,11 @@ S2.define('select2/selection/base',[
var $all = $('.select2.select2-container--open'); var $all = $('.select2.select2-container--open');
$all.each(function () { $all.each(function () {
var $this = $(this);
if (this == $select[0]) { if (this == $select[0]) {
return; return;
} }
var $element = $this.data('element'); var $element = Utils.GetData(this, 'element');
$element.select2('close'); $element.select2('close');
}); });
@@ -1481,6 +1556,27 @@ S2.define('select2/selection/base',[
throw new Error('The `update` method must be defined in child classes.'); throw new Error('The `update` method must be defined in child classes.');
}; };
/**
* Helper method to abstract the "enabled" (not "disabled") state of this
* object.
*
* @return {true} if the instance is not disabled.
* @return {false} if the instance is disabled.
*/
BaseSelection.prototype.isEnabled = function () {
return !this.isDisabled();
};
/**
* Helper method to abstract the "disabled" state of this object.
*
* @return {true} if the disabled option is true.
* @return {false} if the disabled option is false.
*/
BaseSelection.prototype.isDisabled = function () {
return this.options.get('disabled');
};
return BaseSelection; return BaseSelection;
}); });
@@ -1518,7 +1614,10 @@ S2.define('select2/selection/single',[
var id = container.id + '-container'; var id = container.id + '-container';
this.$selection.find('.select2-selection__rendered').attr('id', id); this.$selection.find('.select2-selection__rendered')
.attr('id', id)
.attr('role', 'textbox')
.attr('aria-readonly', 'true');
this.$selection.attr('aria-labelledby', id); this.$selection.attr('aria-labelledby', id);
this.$selection.on('mousedown', function (evt) { this.$selection.on('mousedown', function (evt) {
@@ -1542,17 +1641,15 @@ S2.define('select2/selection/single',[
container.on('focus', function (evt) { container.on('focus', function (evt) {
if (!container.isOpen()) { if (!container.isOpen()) {
self.$selection.focus(); self.$selection.trigger('focus');
} }
}); });
container.on('selection:update', function (params) {
self.update(params.data);
});
}; };
SingleSelection.prototype.clear = function () { SingleSelection.prototype.clear = function () {
this.$selection.find('.select2-selection__rendered').empty(); var $rendered = this.$selection.find('.select2-selection__rendered');
$rendered.empty();
$rendered.removeAttr('title'); // clear tooltip on empty
}; };
SingleSelection.prototype.display = function (data, container) { SingleSelection.prototype.display = function (data, container) {
@@ -1578,7 +1675,14 @@ S2.define('select2/selection/single',[
var formatted = this.display(selection, $rendered); var formatted = this.display(selection, $rendered);
$rendered.empty().append(formatted); $rendered.empty().append(formatted);
$rendered.prop('title', selection.title || selection.text);
var title = selection.title || selection.text;
if (title) {
$rendered.attr('title', title);
} else {
$rendered.removeAttr('title');
}
}; };
return SingleSelection; return SingleSelection;
@@ -1623,14 +1727,14 @@ S2.define('select2/selection/multiple',[
'.select2-selection__choice__remove', '.select2-selection__choice__remove',
function (evt) { function (evt) {
// Ignore the event if it is disabled // Ignore the event if it is disabled
if (self.options.get('disabled')) { if (self.isDisabled()) {
return; return;
} }
var $remove = $(this); var $remove = $(this);
var $selection = $remove.parent(); var $selection = $remove.parent();
var data = $selection.data('data'); var data = Utils.GetData($selection[0], 'data');
self.trigger('unselect', { self.trigger('unselect', {
originalEvent: evt, originalEvent: evt,
@@ -1641,7 +1745,9 @@ S2.define('select2/selection/multiple',[
}; };
MultipleSelection.prototype.clear = function () { MultipleSelection.prototype.clear = function () {
this.$selection.find('.select2-selection__rendered').empty(); var $rendered = this.$selection.find('.select2-selection__rendered');
$rendered.empty();
$rendered.removeAttr('title');
}; };
MultipleSelection.prototype.display = function (data, container) { MultipleSelection.prototype.display = function (data, container) {
@@ -1679,9 +1785,14 @@ S2.define('select2/selection/multiple',[
var formatted = this.display(selection, $selection); var formatted = this.display(selection, $selection);
$selection.append(formatted); $selection.append(formatted);
$selection.prop('title', selection.title || selection.text);
$selection.data('data', selection); var title = selection.title || selection.text;
if (title) {
$selection.attr('title', title);
}
Utils.StoreData($selection[0], 'data', selection);
$selections.push($selection); $selections.push($selection);
} }
@@ -1746,8 +1857,9 @@ S2.define('select2/selection/placeholder',[
S2.define('select2/selection/allowClear',[ S2.define('select2/selection/allowClear',[
'jquery', 'jquery',
'../keys' '../keys',
], function ($, KEYS) { '../utils'
], function ($, KEYS, Utils) {
function AllowClear () { } function AllowClear () { }
AllowClear.prototype.bind = function (decorated, container, $container) { AllowClear.prototype.bind = function (decorated, container, $container) {
@@ -1776,7 +1888,7 @@ S2.define('select2/selection/allowClear',[
AllowClear.prototype._handleClear = function (_, evt) { AllowClear.prototype._handleClear = function (_, evt) {
// Ignore the event if it is disabled // Ignore the event if it is disabled
if (this.options.get('disabled')) { if (this.isDisabled()) {
return; return;
} }
@@ -1789,10 +1901,22 @@ S2.define('select2/selection/allowClear',[
evt.stopPropagation(); evt.stopPropagation();
var data = $clear.data('data'); var data = Utils.GetData($clear[0], 'data');
var previousVal = this.$element.val();
this.$element.val(this.placeholder.id);
var unselectData = {
data: data
};
this.trigger('clear', unselectData);
if (unselectData.prevented) {
this.$element.val(previousVal);
return;
}
for (var d = 0; d < data.length; d++) { for (var d = 0; d < data.length; d++) {
var unselectData = { unselectData = {
data: data[d] data: data[d]
}; };
@@ -1802,11 +1926,12 @@ S2.define('select2/selection/allowClear',[
// If the event was prevented, don't clear it out. // If the event was prevented, don't clear it out.
if (unselectData.prevented) { if (unselectData.prevented) {
this.$element.val(previousVal);
return; return;
} }
} }
this.$element.val(this.placeholder.id).trigger('change'); this.$element.trigger('input').trigger('change');
this.trigger('toggle', {}); this.trigger('toggle', {});
}; };
@@ -1829,12 +1954,14 @@ S2.define('select2/selection/allowClear',[
return; return;
} }
var removeAll = this.options.get('translations').get('removeAllItems');
var $remove = $( var $remove = $(
'<span class="select2-selection__clear">' + '<span class="select2-selection__clear" title="' + removeAll() +'">' +
'&times;' + '&times;' +
'</span>' '</span>'
); );
$remove.data('data', data); Utils.StoreData($remove[0], 'data', data);
this.$selection.find('.select2-selection__rendered').prepend($remove); this.$selection.find('.select2-selection__rendered').prepend($remove);
}; };
@@ -1856,7 +1983,7 @@ S2.define('select2/selection/search',[
'<li class="select2-search select2-search--inline">' + '<li class="select2-search select2-search--inline">' +
'<input class="select2-search__field" type="search" tabindex="-1"' + '<input class="select2-search__field" type="search" tabindex="-1"' +
' autocomplete="off" autocorrect="off" autocapitalize="none"' + ' autocomplete="off" autocorrect="off" autocapitalize="none"' +
' spellcheck="false" role="textbox" aria-autocomplete="list" />' + ' spellcheck="false" role="searchbox" aria-autocomplete="list" />' +
'</li>' '</li>'
); );
@@ -1873,14 +2000,18 @@ S2.define('select2/selection/search',[
Search.prototype.bind = function (decorated, container, $container) { Search.prototype.bind = function (decorated, container, $container) {
var self = this; var self = this;
var resultsId = container.id + '-results';
decorated.call(this, container, $container); decorated.call(this, container, $container);
container.on('open', function () { container.on('open', function () {
self.$search.attr('aria-controls', resultsId);
self.$search.trigger('focus'); self.$search.trigger('focus');
}); });
container.on('close', function () { container.on('close', function () {
self.$search.val(''); self.$search.val('');
self.$search.removeAttr('aria-controls');
self.$search.removeAttr('aria-activedescendant'); self.$search.removeAttr('aria-activedescendant');
self.$search.trigger('focus'); self.$search.trigger('focus');
}); });
@@ -1900,7 +2031,11 @@ S2.define('select2/selection/search',[
}); });
container.on('results:focus', function (params) { container.on('results:focus', function (params) {
self.$search.attr('aria-activedescendant', params.id); if (params.data._resultId) {
self.$search.attr('aria-activedescendant', params.data._resultId);
} else {
self.$search.removeAttr('aria-activedescendant');
}
}); });
this.$selection.on('focusin', '.select2-search--inline', function (evt) { this.$selection.on('focusin', '.select2-search--inline', function (evt) {
@@ -1925,7 +2060,7 @@ S2.define('select2/selection/search',[
.prev('.select2-selection__choice'); .prev('.select2-selection__choice');
if ($previousChoice.length > 0) { if ($previousChoice.length > 0) {
var item = $previousChoice.data('data'); var item = Utils.GetData($previousChoice[0], 'data');
self.searchRemoveChoice(item); self.searchRemoveChoice(item);
@@ -1934,6 +2069,12 @@ S2.define('select2/selection/search',[
} }
}); });
this.$selection.on('click', '.select2-search--inline', function (evt) {
if (self.$search.val()) {
evt.stopPropagation();
}
});
// Try to detect the IE version should the `documentMode` property that // Try to detect the IE version should the `documentMode` property that
// is stored on the document. This is only implemented in IE and is // is stored on the document. This is only implemented in IE and is
// slightly cleaner than doing a user agent check. // slightly cleaner than doing a user agent check.
@@ -2019,7 +2160,7 @@ S2.define('select2/selection/search',[
this.resizeSearch(); this.resizeSearch();
if (searchHadFocus) { if (searchHadFocus) {
this.$search.focus(); this.$search.trigger('focus');
} }
}; };
@@ -2052,7 +2193,7 @@ S2.define('select2/selection/search',[
var width = ''; var width = '';
if (this.$search.attr('placeholder') !== '') { if (this.$search.attr('placeholder') !== '') {
width = this.$selection.find('.select2-selection__rendered').innerWidth(); width = this.$selection.find('.select2-selection__rendered').width();
} else { } else {
var minimumWidth = this.$search.val().length + 1; var minimumWidth = this.$search.val().length + 1;
@@ -2076,10 +2217,13 @@ S2.define('select2/selection/eventRelay',[
'open', 'opening', 'open', 'opening',
'close', 'closing', 'close', 'closing',
'select', 'selecting', 'select', 'selecting',
'unselect', 'unselecting' 'unselect', 'unselecting',
'clear', 'clearing'
]; ];
var preventableEvents = ['opening', 'closing', 'selecting', 'unselecting']; var preventableEvents = [
'opening', 'closing', 'selecting', 'unselecting', 'clearing'
];
decorated.call(this, container, $container); decorated.call(this, container, $container);
@@ -2412,6 +2556,7 @@ S2.define('select2/diacritics',[
'\u019F': 'O', '\u019F': 'O',
'\uA74A': 'O', '\uA74A': 'O',
'\uA74C': 'O', '\uA74C': 'O',
'\u0152': 'OE',
'\u01A2': 'OI', '\u01A2': 'OI',
'\uA74E': 'OO', '\uA74E': 'OO',
'\u0222': 'OU', '\u0222': 'OU',
@@ -2821,6 +2966,7 @@ S2.define('select2/diacritics',[
'\uA74B': 'o', '\uA74B': 'o',
'\uA74D': 'o', '\uA74D': 'o',
'\u0275': 'o', '\u0275': 'o',
'\u0153': 'oe',
'\u01A3': 'oi', '\u01A3': 'oi',
'\u0223': 'ou', '\u0223': 'ou',
'\uA74F': 'oo', '\uA74F': 'oo',
@@ -2989,8 +3135,9 @@ S2.define('select2/diacritics',[
'\u03CD': '\u03C5', '\u03CD': '\u03C5',
'\u03CB': '\u03C5', '\u03CB': '\u03C5',
'\u03B0': '\u03C5', '\u03B0': '\u03C5',
'\u03C9': '\u03C9', '\u03CE': '\u03C9',
'\u03C2': '\u03C3' '\u03C2': '\u03C3',
'\u2019': '\''
}; };
return diacritics; return diacritics;
@@ -3075,7 +3222,7 @@ S2.define('select2/data/select',[
if ($(data.element).is('option')) { if ($(data.element).is('option')) {
data.element.selected = true; data.element.selected = true;
this.$element.trigger('change'); this.$element.trigger('input').trigger('change');
return; return;
} }
@@ -3096,13 +3243,13 @@ S2.define('select2/data/select',[
} }
self.$element.val(val); self.$element.val(val);
self.$element.trigger('change'); self.$element.trigger('input').trigger('change');
}); });
} else { } else {
var val = data.id; var val = data.id;
this.$element.val(val); this.$element.val(val);
this.$element.trigger('change'); this.$element.trigger('input').trigger('change');
} }
}; };
@@ -3118,7 +3265,7 @@ S2.define('select2/data/select',[
if ($(data.element).is('option')) { if ($(data.element).is('option')) {
data.element.selected = false; data.element.selected = false;
this.$element.trigger('change'); this.$element.trigger('input').trigger('change');
return; return;
} }
@@ -3136,7 +3283,7 @@ S2.define('select2/data/select',[
self.$element.val(val); self.$element.val(val);
self.$element.trigger('change'); self.$element.trigger('input').trigger('change');
}); });
}; };
@@ -3158,7 +3305,7 @@ S2.define('select2/data/select',[
// Remove anything added to child elements // Remove anything added to child elements
this.$element.find('*').each(function () { this.$element.find('*').each(function () {
// Remove any custom data set by Select2 // Remove any custom data set by Select2
$.removeData(this, 'data'); Utils.RemoveData(this);
}); });
}; };
@@ -3231,7 +3378,7 @@ S2.define('select2/data/select',[
normalizedData.element = option; normalizedData.element = option;
// Override the option's data with the combined data // Override the option's data with the combined data
$.data(option, 'data', normalizedData); Utils.StoreData(option, 'data', normalizedData);
return $option; return $option;
}; };
@@ -3239,7 +3386,7 @@ S2.define('select2/data/select',[
SelectAdapter.prototype.item = function ($option) { SelectAdapter.prototype.item = function ($option) {
var data = {}; var data = {};
data = $.data($option[0], 'data'); data = Utils.GetData($option[0], 'data');
if (data != null) { if (data != null) {
return data; return data;
@@ -3277,13 +3424,13 @@ S2.define('select2/data/select',[
data = this._normalizeItem(data); data = this._normalizeItem(data);
data.element = $option[0]; data.element = $option[0];
$.data($option[0], 'data', data); Utils.StoreData($option[0], 'data', data);
return data; return data;
}; };
SelectAdapter.prototype._normalizeItem = function (item) { SelectAdapter.prototype._normalizeItem = function (item) {
if (!$.isPlainObject(item)) { if (item !== Object(item)) {
item = { item = {
id: item, id: item,
text: item text: item
@@ -3329,15 +3476,19 @@ S2.define('select2/data/array',[
'jquery' 'jquery'
], function (SelectAdapter, Utils, $) { ], function (SelectAdapter, Utils, $) {
function ArrayAdapter ($element, options) { function ArrayAdapter ($element, options) {
var data = options.get('data') || []; this._dataToConvert = options.get('data') || [];
ArrayAdapter.__super__.constructor.call(this, $element, options); ArrayAdapter.__super__.constructor.call(this, $element, options);
this.addOptions(this.convertToOptions(data));
} }
Utils.Extend(ArrayAdapter, SelectAdapter); Utils.Extend(ArrayAdapter, SelectAdapter);
ArrayAdapter.prototype.bind = function (container, $container) {
ArrayAdapter.__super__.bind.call(this, container, $container);
this.addOptions(this.convertToOptions(this._dataToConvert));
};
ArrayAdapter.prototype.select = function (data) { ArrayAdapter.prototype.select = function (data) {
var $option = this.$element.find('option').filter(function (i, elm) { var $option = this.$element.find('option').filter(function (i, elm) {
return elm.value == data.id.toString(); return elm.value == data.id.toString();
@@ -3487,7 +3638,8 @@ S2.define('select2/data/ajax',[
}, function () { }, function () {
// Attempt to detect if a request was aborted // Attempt to detect if a request was aborted
// Only works if the transport exposes a status property // Only works if the transport exposes a status property
if ($request.status && $request.status === '0') { if ('status' in $request &&
($request.status === 0 || $request.status === '0')) {
return; return;
} }
@@ -3626,8 +3778,6 @@ S2.define('select2/data/tags',[
}; };
Tags.prototype._removeOldTags = function (_) { Tags.prototype._removeOldTags = function (_) {
var tag = this._lastTag;
var $options = this.$element.find('option[data-select2-tag]'); var $options = this.$element.find('option[data-select2-tag]');
$options.each(function () { $options.each(function () {
@@ -3702,7 +3852,7 @@ S2.define('select2/data/tokenizer',[
// Replace the search term if we have the search box // Replace the search term if we have the search box
if (this.$search.length) { if (this.$search.length) {
this.$search.val(tokenData.term); this.$search.val(tokenData.term);
this.$search.focus(); this.$search.trigger('focus');
} }
params.term = tokenData.term; params.term = tokenData.term;
@@ -3831,10 +3981,30 @@ S2.define('select2/data/maximumSelectionLength',[
decorated.call(this, $e, options); decorated.call(this, $e, options);
} }
MaximumSelectionLength.prototype.bind =
function (decorated, container, $container) {
var self = this;
decorated.call(this, container, $container);
container.on('select', function () {
self._checkIfMaximumSelected();
});
};
MaximumSelectionLength.prototype.query = MaximumSelectionLength.prototype.query =
function (decorated, params, callback) { function (decorated, params, callback) {
var self = this; var self = this;
this._checkIfMaximumSelected(function () {
decorated.call(self, params, callback);
});
};
MaximumSelectionLength.prototype._checkIfMaximumSelected =
function (_, successCallback) {
var self = this;
this.current(function (currentData) { this.current(function (currentData) {
var count = currentData != null ? currentData.length : 0; var count = currentData != null ? currentData.length : 0;
if (self.maximumSelectionLength > 0 && if (self.maximumSelectionLength > 0 &&
@@ -3847,7 +4017,10 @@ S2.define('select2/data/maximumSelectionLength',[
}); });
return; return;
} }
decorated.call(self, params, callback);
if (successCallback) {
successCallback();
}
}); });
}; };
@@ -3886,7 +4059,7 @@ S2.define('select2/dropdown',[
}; };
Dropdown.prototype.position = function ($dropdown, $container) { Dropdown.prototype.position = function ($dropdown, $container) {
// Should be implmented in subclasses // Should be implemented in subclasses
}; };
Dropdown.prototype.destroy = function () { Dropdown.prototype.destroy = function () {
@@ -3910,7 +4083,7 @@ S2.define('select2/dropdown/search',[
'<span class="select2-search select2-search--dropdown">' + '<span class="select2-search select2-search--dropdown">' +
'<input class="select2-search__field" type="search" tabindex="-1"' + '<input class="select2-search__field" type="search" tabindex="-1"' +
' autocomplete="off" autocorrect="off" autocapitalize="none"' + ' autocomplete="off" autocorrect="off" autocapitalize="none"' +
' spellcheck="false" role="textbox" />' + ' spellcheck="false" role="searchbox" aria-autocomplete="list" />' +
'</span>' '</span>'
); );
@@ -3925,6 +4098,8 @@ S2.define('select2/dropdown/search',[
Search.prototype.bind = function (decorated, container, $container) { Search.prototype.bind = function (decorated, container, $container) {
var self = this; var self = this;
var resultsId = container.id + '-results';
decorated.call(this, container, $container); decorated.call(this, container, $container);
this.$search.on('keydown', function (evt) { this.$search.on('keydown', function (evt) {
@@ -3947,23 +4122,27 @@ S2.define('select2/dropdown/search',[
container.on('open', function () { container.on('open', function () {
self.$search.attr('tabindex', 0); self.$search.attr('tabindex', 0);
self.$search.attr('aria-controls', resultsId);
self.$search.focus(); self.$search.trigger('focus');
window.setTimeout(function () { window.setTimeout(function () {
self.$search.focus(); self.$search.trigger('focus');
}, 0); }, 0);
}); });
container.on('close', function () { container.on('close', function () {
self.$search.attr('tabindex', -1); self.$search.attr('tabindex', -1);
self.$search.removeAttr('aria-controls');
self.$search.removeAttr('aria-activedescendant');
self.$search.val(''); self.$search.val('');
self.$search.trigger('blur');
}); });
container.on('focus', function () { container.on('focus', function () {
if (!container.isOpen()) { if (!container.isOpen()) {
self.$search.focus(); self.$search.trigger('focus');
} }
}); });
@@ -3978,6 +4157,14 @@ S2.define('select2/dropdown/search',[
} }
} }
}); });
container.on('results:focus', function (params) {
if (params.data._resultId) {
self.$search.attr('aria-activedescendant', params.data._resultId);
} else {
self.$search.removeAttr('aria-activedescendant');
}
});
}; };
Search.prototype.handleSearch = function (evt) { Search.prototype.handleSearch = function (evt) {
@@ -4062,6 +4249,7 @@ S2.define('select2/dropdown/infiniteScroll',[
if (this.showLoadingMore(data)) { if (this.showLoadingMore(data)) {
this.$results.append(this.$loadingMore); this.$results.append(this.$loadingMore);
this.loadMoreIfNeeded();
} }
}; };
@@ -4080,25 +4268,27 @@ S2.define('select2/dropdown/infiniteScroll',[
self.loading = true; self.loading = true;
}); });
this.$results.on('scroll', function () { this.$results.on('scroll', this.loadMoreIfNeeded.bind(this));
var isLoadMoreVisible = $.contains( };
document.documentElement,
self.$loadingMore[0]
);
if (self.loading || !isLoadMoreVisible) { InfiniteScroll.prototype.loadMoreIfNeeded = function () {
return; var isLoadMoreVisible = $.contains(
} document.documentElement,
this.$loadingMore[0]
);
var currentOffset = self.$results.offset().top + if (this.loading || !isLoadMoreVisible) {
self.$results.outerHeight(false); return;
var loadingMoreOffset = self.$loadingMore.offset().top + }
self.$loadingMore.outerHeight(false);
if (currentOffset + 50 >= loadingMoreOffset) { var currentOffset = this.$results.offset().top +
self.loadMore(); this.$results.outerHeight(false);
} var loadingMoreOffset = this.$loadingMore.offset().top +
}); this.$loadingMore.outerHeight(false);
if (currentOffset + 50 >= loadingMoreOffset) {
this.loadMore();
}
}; };
InfiniteScroll.prototype.loadMore = function () { InfiniteScroll.prototype.loadMore = function () {
@@ -4119,7 +4309,7 @@ S2.define('select2/dropdown/infiniteScroll',[
var $option = $( var $option = $(
'<li ' + '<li ' +
'class="select2-results__option select2-results__option--load-more"' + 'class="select2-results__option select2-results__option--load-more"' +
'role="treeitem" aria-disabled="true"></li>' 'role="option" aria-disabled="true"></li>'
); );
var message = this.options.get('translations').get('loadingMore'); var message = this.options.get('translations').get('loadingMore');
@@ -4137,7 +4327,7 @@ S2.define('select2/dropdown/attachBody',[
'../utils' '../utils'
], function ($, Utils) { ], function ($, Utils) {
function AttachBody (decorated, $element, options) { function AttachBody (decorated, $element, options) {
this.$dropdownParent = options.get('dropdownParent') || $(document.body); this.$dropdownParent = $(options.get('dropdownParent') || document.body);
decorated.call(this, $element, options); decorated.call(this, $element, options);
} }
@@ -4145,27 +4335,14 @@ S2.define('select2/dropdown/attachBody',[
AttachBody.prototype.bind = function (decorated, container, $container) { AttachBody.prototype.bind = function (decorated, container, $container) {
var self = this; var self = this;
var setupResultsEvents = false;
decorated.call(this, container, $container); decorated.call(this, container, $container);
container.on('open', function () { container.on('open', function () {
self._showDropdown(); self._showDropdown();
self._attachPositioningHandler(container); self._attachPositioningHandler(container);
if (!setupResultsEvents) { // Must bind after the results handlers to ensure correct sizing
setupResultsEvents = true; self._bindContainerResultHandlers(container);
container.on('results:all', function () {
self._positionDropdown();
self._resizeDropdown();
});
container.on('results:append', function () {
self._positionDropdown();
self._resizeDropdown();
});
}
}); });
container.on('close', function () { container.on('close', function () {
@@ -4214,6 +4391,44 @@ S2.define('select2/dropdown/attachBody',[
this.$dropdownContainer.detach(); this.$dropdownContainer.detach();
}; };
AttachBody.prototype._bindContainerResultHandlers =
function (decorated, container) {
// These should only be bound once
if (this._containerResultsHandlersBound) {
return;
}
var self = this;
container.on('results:all', function () {
self._positionDropdown();
self._resizeDropdown();
});
container.on('results:append', function () {
self._positionDropdown();
self._resizeDropdown();
});
container.on('results:message', function () {
self._positionDropdown();
self._resizeDropdown();
});
container.on('select', function () {
self._positionDropdown();
self._resizeDropdown();
});
container.on('unselect', function () {
self._positionDropdown();
self._resizeDropdown();
});
this._containerResultsHandlersBound = true;
};
AttachBody.prototype._attachPositioningHandler = AttachBody.prototype._attachPositioningHandler =
function (decorated, container) { function (decorated, container) {
var self = this; var self = this;
@@ -4224,14 +4439,14 @@ S2.define('select2/dropdown/attachBody',[
var $watchers = this.$container.parents().filter(Utils.hasScroll); var $watchers = this.$container.parents().filter(Utils.hasScroll);
$watchers.each(function () { $watchers.each(function () {
$(this).data('select2-scroll-position', { Utils.StoreData(this, 'select2-scroll-position', {
x: $(this).scrollLeft(), x: $(this).scrollLeft(),
y: $(this).scrollTop() y: $(this).scrollTop()
}); });
}); });
$watchers.on(scrollEvent, function (ev) { $watchers.on(scrollEvent, function (ev) {
var position = $(this).data('select2-scroll-position'); var position = Utils.GetData(this, 'select2-scroll-position');
$(this).scrollTop(position.y); $(this).scrollTop(position.y);
}); });
@@ -4290,16 +4505,26 @@ S2.define('select2/dropdown/attachBody',[
top: container.bottom top: container.bottom
}; };
// Determine what the parent element is to use for calciulating the offset // Determine what the parent element is to use for calculating the offset
var $offsetParent = this.$dropdownParent; var $offsetParent = this.$dropdownParent;
// For statically positoned elements, we need to get the element // For statically positioned elements, we need to get the element
// that is determining the offset // that is determining the offset
if ($offsetParent.css('position') === 'static') { if ($offsetParent.css('position') === 'static') {
$offsetParent = $offsetParent.offsetParent(); $offsetParent = $offsetParent.offsetParent();
} }
var parentOffset = $offsetParent.offset(); var parentOffset = {
top: 0,
left: 0
};
if (
$.contains(document.body, $offsetParent[0]) ||
$offsetParent[0].isConnected
) {
parentOffset = $offsetParent.offset();
}
css.top -= parentOffset.top; css.top -= parentOffset.top;
css.left -= parentOffset.left; css.left -= parentOffset.left;
@@ -4396,8 +4621,8 @@ S2.define('select2/dropdown/minimumResultsForSearch',[
}); });
S2.define('select2/dropdown/selectOnClose',[ S2.define('select2/dropdown/selectOnClose',[
'../utils'
], function () { ], function (Utils) {
function SelectOnClose () { } function SelectOnClose () { }
SelectOnClose.prototype.bind = function (decorated, container, $container) { SelectOnClose.prototype.bind = function (decorated, container, $container) {
@@ -4428,7 +4653,7 @@ S2.define('select2/dropdown/selectOnClose',[
return; return;
} }
var data = $highlightedResults.data('data'); var data = Utils.GetData($highlightedResults[0], 'data');
// Don't re-select already selected resulte // Don't re-select already selected resulte
if ( if (
@@ -4469,7 +4694,7 @@ S2.define('select2/dropdown/closeOnSelect',[
var originalEvent = evt.originalEvent; var originalEvent = evt.originalEvent;
// Don't close if the control key is being held // Don't close if the control key is being held
if (originalEvent && originalEvent.ctrlKey) { if (originalEvent && (originalEvent.ctrlKey || originalEvent.metaKey)) {
return; return;
} }
@@ -4523,6 +4748,9 @@ S2.define('select2/i18n/en',[],function () {
}, },
searching: function () { searching: function () {
return 'Searching…'; return 'Searching…';
},
removeAllItems: function () {
return 'Remove all items';
} }
}; };
}); });
@@ -4761,66 +4989,29 @@ S2.define('select2/defaults',[
); );
} }
if (typeof options.language === 'string') { // If the defaults were not previously applied from an element, it is
// Check if the language is specified with a region // possible for the language option to have not been resolved
if (options.language.indexOf('-') > 0) { options.language = this._resolveLanguage(options.language);
// Extract the region information if it is included
var languageParts = options.language.split('-');
var baseLanguage = languageParts[0];
options.language = [options.language, baseLanguage]; // Always fall back to English since it will always be complete
} else { options.language.push('en');
options.language = [options.language];
var uniqueLanguages = [];
for (var l = 0; l < options.language.length; l++) {
var language = options.language[l];
if (uniqueLanguages.indexOf(language) === -1) {
uniqueLanguages.push(language);
} }
} }
if ($.isArray(options.language)) { options.language = uniqueLanguages;
var languages = new Translation();
options.language.push('en');
var languageNames = options.language; options.translations = this._processTranslations(
options.language,
for (var l = 0; l < languageNames.length; l++) { options.debug
var name = languageNames[l]; );
var language = {};
try {
// Try to load it with the original name
language = Translation.loadPath(name);
} catch (e) {
try {
// If we couldn't load it, check if it wasn't the full path
name = this.defaults.amdLanguageBase + name;
language = Translation.loadPath(name);
} catch (ex) {
// The translation could not be loaded at all. Sometimes this is
// because of a configuration problem, other times this can be
// because of how Select2 helps load all possible translation files.
if (options.debug && window.console && console.warn) {
console.warn(
'Select2: The language file for "' + name + '" could not be ' +
'automatically loaded. A fallback will be used instead.'
);
}
continue;
}
}
languages.extend(language);
}
options.translations = languages;
} else {
var baseTranslation = Translation.loadPath(
this.defaults.amdLanguageBase + 'en'
);
var customTranslation = new Translation(options.language);
customTranslation.extend(baseTranslation);
options.translations = customTranslation;
}
return options; return options;
}; };
@@ -4887,13 +5078,14 @@ S2.define('select2/defaults',[
debug: false, debug: false,
dropdownAutoWidth: false, dropdownAutoWidth: false,
escapeMarkup: Utils.escapeMarkup, escapeMarkup: Utils.escapeMarkup,
language: EnglishTranslation, language: {},
matcher: matcher, matcher: matcher,
minimumInputLength: 0, minimumInputLength: 0,
maximumInputLength: 0, maximumInputLength: 0,
maximumSelectionLength: 0, maximumSelectionLength: 0,
minimumResultsForSearch: 0, minimumResultsForSearch: 0,
selectOnClose: false, selectOnClose: false,
scrollAfterSelect: false,
sorter: function (data) { sorter: function (data) {
return data; return data;
}, },
@@ -4908,6 +5100,103 @@ S2.define('select2/defaults',[
}; };
}; };
Defaults.prototype.applyFromElement = function (options, $element) {
var optionLanguage = options.language;
var defaultLanguage = this.defaults.language;
var elementLanguage = $element.prop('lang');
var parentLanguage = $element.closest('[lang]').prop('lang');
var languages = Array.prototype.concat.call(
this._resolveLanguage(elementLanguage),
this._resolveLanguage(optionLanguage),
this._resolveLanguage(defaultLanguage),
this._resolveLanguage(parentLanguage)
);
options.language = languages;
return options;
};
Defaults.prototype._resolveLanguage = function (language) {
if (!language) {
return [];
}
if ($.isEmptyObject(language)) {
return [];
}
if ($.isPlainObject(language)) {
return [language];
}
var languages;
if (!$.isArray(language)) {
languages = [language];
} else {
languages = language;
}
var resolvedLanguages = [];
for (var l = 0; l < languages.length; l++) {
resolvedLanguages.push(languages[l]);
if (typeof languages[l] === 'string' && languages[l].indexOf('-') > 0) {
// Extract the region information if it is included
var languageParts = languages[l].split('-');
var baseLanguage = languageParts[0];
resolvedLanguages.push(baseLanguage);
}
}
return resolvedLanguages;
};
Defaults.prototype._processTranslations = function (languages, debug) {
var translations = new Translation();
for (var l = 0; l < languages.length; l++) {
var languageData = new Translation();
var language = languages[l];
if (typeof language === 'string') {
try {
// Try to load it with the original name
languageData = Translation.loadPath(language);
} catch (e) {
try {
// If we couldn't load it, check if it wasn't the full path
language = this.defaults.amdLanguageBase + language;
languageData = Translation.loadPath(language);
} catch (ex) {
// The translation could not be loaded at all. Sometimes this is
// because of a configuration problem, other times this can be
// because of how Select2 helps load all possible translation files
if (debug && window.console && console.warn) {
console.warn(
'Select2: The language file for "' + language + '" could ' +
'not be automatically loaded. A fallback will be used instead.'
);
}
}
}
} else if ($.isPlainObject(language)) {
languageData = new Translation(language);
} else {
languageData = language;
}
translations.extend(languageData);
}
return translations;
};
Defaults.prototype.set = function (key, value) { Defaults.prototype.set = function (key, value) {
var camelKey = $.camelCase(key); var camelKey = $.camelCase(key);
@@ -4916,7 +5205,7 @@ S2.define('select2/defaults',[
var convertedData = Utils._convertData(data); var convertedData = Utils._convertData(data);
$.extend(this.defaults, convertedData); $.extend(true, this.defaults, convertedData);
}; };
var defaults = new Defaults(); var defaults = new Defaults();
@@ -4937,6 +5226,10 @@ S2.define('select2/options',[
this.fromElement($element); this.fromElement($element);
} }
if ($element != null) {
this.options = Defaults.applyFromElement(this.options, $element);
}
this.options = Defaults.apply(this.options); this.options = Defaults.apply(this.options);
if ($element && $element.is('input')) { if ($element && $element.is('input')) {
@@ -4960,14 +5253,6 @@ S2.define('select2/options',[
this.options.disabled = $e.prop('disabled'); this.options.disabled = $e.prop('disabled');
} }
if (this.options.language == null) {
if ($e.prop('lang')) {
this.options.language = $e.prop('lang').toLowerCase();
} else if ($e.closest('[lang]').prop('lang')) {
this.options.language = $e.closest('[lang]').prop('lang');
}
}
if (this.options.dir == null) { if (this.options.dir == null) {
if ($e.prop('dir')) { if ($e.prop('dir')) {
this.options.dir = $e.prop('dir'); this.options.dir = $e.prop('dir');
@@ -4981,7 +5266,7 @@ S2.define('select2/options',[
$e.prop('disabled', this.options.disabled); $e.prop('disabled', this.options.disabled);
$e.prop('multiple', this.options.multiple); $e.prop('multiple', this.options.multiple);
if ($e.data('select2Tags')) { if (Utils.GetData($e[0], 'select2Tags')) {
if (this.options.debug && window.console && console.warn) { if (this.options.debug && window.console && console.warn) {
console.warn( console.warn(
'Select2: The `data-select2-tags` attribute has been changed to ' + 'Select2: The `data-select2-tags` attribute has been changed to ' +
@@ -4990,11 +5275,11 @@ S2.define('select2/options',[
); );
} }
$e.data('data', $e.data('select2Tags')); Utils.StoreData($e[0], 'data', Utils.GetData($e[0], 'select2Tags'));
$e.data('tags', true); Utils.StoreData($e[0], 'tags', true);
} }
if ($e.data('ajaxUrl')) { if (Utils.GetData($e[0], 'ajaxUrl')) {
if (this.options.debug && window.console && console.warn) { if (this.options.debug && window.console && console.warn) {
console.warn( console.warn(
'Select2: The `data-ajax-url` attribute has been changed to ' + 'Select2: The `data-ajax-url` attribute has been changed to ' +
@@ -5003,21 +5288,45 @@ S2.define('select2/options',[
); );
} }
$e.attr('ajax--url', $e.data('ajaxUrl')); $e.attr('ajax--url', Utils.GetData($e[0], 'ajaxUrl'));
$e.data('ajax--url', $e.data('ajaxUrl')); Utils.StoreData($e[0], 'ajax-Url', Utils.GetData($e[0], 'ajaxUrl'));
} }
var dataset = {}; var dataset = {};
function upperCaseLetter(_, letter) {
return letter.toUpperCase();
}
// Pre-load all of the attributes which are prefixed with `data-`
for (var attr = 0; attr < $e[0].attributes.length; attr++) {
var attributeName = $e[0].attributes[attr].name;
var prefix = 'data-';
if (attributeName.substr(0, prefix.length) == prefix) {
// Get the contents of the attribute after `data-`
var dataName = attributeName.substring(prefix.length);
// Get the data contents from the consistent source
// This is more than likely the jQuery data helper
var dataValue = Utils.GetData($e[0], dataName);
// camelCase the attribute name to match the spec
var camelDataName = dataName.replace(/-([a-z])/g, upperCaseLetter);
// Store the data attribute contents into the dataset since
dataset[camelDataName] = dataValue;
}
}
// Prefer the element's `dataset` attribute if it exists // Prefer the element's `dataset` attribute if it exists
// jQuery 1.x does not correctly handle data attributes with multiple dashes // jQuery 1.x does not correctly handle data attributes with multiple dashes
if ($.fn.jquery && $.fn.jquery.substr(0, 2) == '1.' && $e[0].dataset) { if ($.fn.jquery && $.fn.jquery.substr(0, 2) == '1.' && $e[0].dataset) {
dataset = $.extend(true, {}, $e[0].dataset, $e.data()); dataset = $.extend(true, {}, $e[0].dataset, dataset);
} else {
dataset = $e.data();
} }
var data = $.extend(true, {}, dataset); // Prefer our internal data cache if it exists
var data = $.extend(true, {}, Utils.GetData($e[0]), dataset);
data = Utils._convertData(data); data = Utils._convertData(data);
@@ -5054,8 +5363,8 @@ S2.define('select2/core',[
'./keys' './keys'
], function ($, Options, Utils, KEYS) { ], function ($, Options, Utils, KEYS) {
var Select2 = function ($element, options) { var Select2 = function ($element, options) {
if ($element.data('select2') != null) { if (Utils.GetData($element[0], 'select2') != null) {
$element.data('select2').destroy(); Utils.GetData($element[0], 'select2').destroy();
} }
this.$element = $element; this.$element = $element;
@@ -5071,7 +5380,7 @@ S2.define('select2/core',[
// Set up the tabindex // Set up the tabindex
var tabindex = $element.attr('tabindex') || 0; var tabindex = $element.attr('tabindex') || 0;
$element.data('old-tabindex', tabindex); Utils.StoreData($element[0], 'old-tabindex', tabindex);
$element.attr('tabindex', '-1'); $element.attr('tabindex', '-1');
// Set up containers and adapters // Set up containers and adapters
@@ -5132,6 +5441,9 @@ S2.define('select2/core',[
// Synchronize any monitored attributes // Synchronize any monitored attributes
this._syncAttributes(); this._syncAttributes();
Utils.StoreData($element[0], 'select2', this);
// Ensure backwards compatibility with $element.data('select2').
$element.data('select2', this); $element.data('select2', this);
}; };
@@ -5208,6 +5520,12 @@ S2.define('select2/core',[
return null; return null;
} }
if (method == 'computedstyle') {
var computedStyle = window.getComputedStyle($element[0]);
return computedStyle.width;
}
return method; return method;
}; };
@@ -5248,8 +5566,8 @@ S2.define('select2/core',[
if (observer != null) { if (observer != null) {
this._observer = new observer(function (mutations) { this._observer = new observer(function (mutations) {
$.each(mutations, self._syncA); self._syncA();
$.each(mutations, self._syncS); self._syncS(null, mutations);
}); });
this._observer.observe(this.$element[0], { this._observer.observe(this.$element[0], {
attributes: true, attributes: true,
@@ -5371,7 +5689,7 @@ S2.define('select2/core',[
if (self.isOpen()) { if (self.isOpen()) {
if (key === KEYS.ESC || key === KEYS.TAB || if (key === KEYS.ESC || key === KEYS.TAB ||
(key === KEYS.UP && evt.altKey)) { (key === KEYS.UP && evt.altKey)) {
self.close(); self.close(evt);
evt.preventDefault(); evt.preventDefault();
} else if (key === KEYS.ENTER) { } else if (key === KEYS.ENTER) {
@@ -5405,7 +5723,7 @@ S2.define('select2/core',[
Select2.prototype._syncAttributes = function () { Select2.prototype._syncAttributes = function () {
this.options.set('disabled', this.$element.prop('disabled')); this.options.set('disabled', this.$element.prop('disabled'));
if (this.options.get('disabled')) { if (this.isDisabled()) {
if (this.isOpen()) { if (this.isOpen()) {
this.close(); this.close();
} }
@@ -5416,7 +5734,7 @@ S2.define('select2/core',[
} }
}; };
Select2.prototype._syncSubtree = function (evt, mutations) { Select2.prototype._isChangeMutation = function (evt, mutations) {
var changed = false; var changed = false;
var self = this; var self = this;
@@ -5444,7 +5762,22 @@ S2.define('select2/core',[
} }
} else if (mutations.removedNodes && mutations.removedNodes.length > 0) { } else if (mutations.removedNodes && mutations.removedNodes.length > 0) {
changed = true; changed = true;
} else if ($.isArray(mutations)) {
$.each(mutations, function(evt, mutation) {
if (self._isChangeMutation(evt, mutation)) {
// We've found a change mutation.
// Let's escape from the loop and continue
changed = true;
return false;
}
});
} }
return changed;
};
Select2.prototype._syncSubtree = function (evt, mutations) {
var changed = this._isChangeMutation(evt, mutations);
var self = this;
// Only re-pull the data if we think there is a change // Only re-pull the data if we think there is a change
if (changed) { if (changed) {
@@ -5466,7 +5799,8 @@ S2.define('select2/core',[
'open': 'opening', 'open': 'opening',
'close': 'closing', 'close': 'closing',
'select': 'selecting', 'select': 'selecting',
'unselect': 'unselecting' 'unselect': 'unselecting',
'clear': 'clearing'
}; };
if (args === undefined) { if (args === undefined) {
@@ -5494,7 +5828,7 @@ S2.define('select2/core',[
}; };
Select2.prototype.toggleDropdown = function () { Select2.prototype.toggleDropdown = function () {
if (this.options.get('disabled')) { if (this.isDisabled()) {
return; return;
} }
@@ -5510,15 +5844,40 @@ S2.define('select2/core',[
return; return;
} }
if (this.isDisabled()) {
return;
}
this.trigger('query', {}); this.trigger('query', {});
}; };
Select2.prototype.close = function () { Select2.prototype.close = function (evt) {
if (!this.isOpen()) { if (!this.isOpen()) {
return; return;
} }
this.trigger('close', {}); this.trigger('close', { originalEvent : evt });
};
/**
* Helper method to abstract the "enabled" (not "disabled") state of this
* object.
*
* @return {true} if the instance is not disabled.
* @return {false} if the instance is disabled.
*/
Select2.prototype.isEnabled = function () {
return !this.isDisabled();
};
/**
* Helper method to abstract the "disabled" state of this object.
*
* @return {true} if the disabled option is true.
* @return {false} if the disabled option is false.
*/
Select2.prototype.isDisabled = function () {
return this.options.get('disabled');
}; };
Select2.prototype.isOpen = function () { Select2.prototype.isOpen = function () {
@@ -5595,7 +5954,7 @@ S2.define('select2/core',[
}); });
} }
this.$element.val(newVal).trigger('change'); this.$element.val(newVal).trigger('input').trigger('change');
}; };
Select2.prototype.destroy = function () { Select2.prototype.destroy = function () {
@@ -5621,10 +5980,12 @@ S2.define('select2/core',[
this._syncS = null; this._syncS = null;
this.$element.off('.select2'); this.$element.off('.select2');
this.$element.attr('tabindex', this.$element.data('old-tabindex')); this.$element.attr('tabindex',
Utils.GetData(this.$element[0], 'old-tabindex'));
this.$element.removeClass('select2-hidden-accessible'); this.$element.removeClass('select2-hidden-accessible');
this.$element.attr('aria-hidden', 'false'); this.$element.attr('aria-hidden', 'false');
Utils.RemoveData(this.$element[0]);
this.$element.removeData('select2'); this.$element.removeData('select2');
this.dataAdapter.destroy(); this.dataAdapter.destroy();
@@ -5652,7 +6013,7 @@ S2.define('select2/core',[
this.$container.addClass('select2-container--' + this.options.get('theme')); this.$container.addClass('select2-container--' + this.options.get('theme'));
$container.data('element', this.$element); Utils.StoreData($container[0], 'element', this.$element);
return $container; return $container;
}; };
@@ -5672,8 +6033,9 @@ S2.define('jquery.select2',[
'jquery-mousewheel', 'jquery-mousewheel',
'./select2/core', './select2/core',
'./select2/defaults' './select2/defaults',
], function ($, _, Select2, Defaults) { './select2/utils'
], function ($, _, Select2, Defaults, Utils) {
if ($.fn.select2 == null) { if ($.fn.select2 == null) {
// All methods that should return the element // All methods that should return the element
var thisMethods = ['open', 'close', 'destroy']; var thisMethods = ['open', 'close', 'destroy'];
@@ -5694,7 +6056,7 @@ S2.define('jquery.select2',[
var args = Array.prototype.slice.call(arguments, 1); var args = Array.prototype.slice.call(arguments, 1);
this.each(function () { this.each(function () {
var instance = $(this).data('select2'); var instance = Utils.GetData(this, 'select2');
if (instance == null && window.console && console.error) { if (instance == null && window.console && console.error) {
console.error( console.error(
+1 -1
View File
File diff suppressed because one or more lines are too long
+2 -1
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -38,7 +38,7 @@ $admin = getAdmin();
</tr> </tr>
<tr> <tr>
<td width=110 align=right>시작시간변경</td> <td width=110 align=right>시작시간변경</td>
<td width=285><input type=text size=20 maxlength=20 style=color:white;background-color:black;text-align:right; name=starttime value='<?=$admin['starttime']?>'><input type=submit name=btn value=변경1></td> <td width=285><input type=text size=20 maxlength=20 style=color:white;background-color:black;text-align:right; name=starttime value='<?=substr($admin['starttime'], 0, 19)?>'><input type=submit name=btn value=변경1></td>
<td width=110 align=right>현재도시훈사</td> <td width=110 align=right>현재도시훈사</td>
<td width=285><?=$admin['city_rate']?></td> <td width=285><?=$admin['city_rate']?></td>
</tr> </tr>
+11
View File
@@ -91,6 +91,7 @@ $types = [
} }
return $v; return $v;
}], }],
["점 령", "int", function($v){$v['value'] = $v['occupied']; return $v; }],
["사 살", "int", function($v){$v['value'] = $v['killcrew']; return $v; }], ["사 살", "int", function($v){$v['value'] = $v['killcrew']; return $v; }],
["살 상 률", "percent", function($v){ ["살 상 률", "percent", function($v){
if($v['warnum'] < 10){ if($v['warnum'] < 10){
@@ -101,6 +102,16 @@ $types = [
} }
return $v; return $v;
}], }],
["대 인 사 살", "int", function($v){$v['value'] = $v['killcrew_person']; return $v; }],
["대 인 살 상 률", "percent", function($v){
if($v['warnum'] < 10){
$v['value'] = 0;
}
else{
$v['value'] = $v['killcrew_person'] / max(1, $v['deathcrew_person']);
}
return $v;
}],
["보 병 숙 련 도", "int", function($v){$v['value'] = $v['dex1']; return $v; }], ["보 병 숙 련 도", "int", function($v){$v['value'] = $v['dex1']; return $v; }],
["궁 병 숙 련 도", "int", function($v){$v['value'] = $v['dex2']; return $v; }], ["궁 병 숙 련 도", "int", function($v){$v['value'] = $v['dex2']; return $v; }],
["기 병 숙 련 도", "int", function($v){$v['value'] = $v['dex3']; return $v; }], ["기 병 숙 련 도", "int", function($v){$v['value'] = $v['dex3']; return $v; }],
+3
View File
@@ -90,8 +90,11 @@ $types = [
'warnum'=>['전 투 횟 수', 'int'], 'warnum'=>['전 투 횟 수', 'int'],
'killnum'=>['승 리', 'int'], 'killnum'=>['승 리', 'int'],
'winrate'=>['승 률', 'percent'], 'winrate'=>['승 률', 'percent'],
'occupied'=>['점 령', 'int'],
'killcrew'=>['사 살', 'int'], 'killcrew'=>['사 살', 'int'],
'killrate'=>['살 상 률', 'percent'], 'killrate'=>['살 상 률', 'percent'],
'killcrew_person'=>['대 인 사 살', 'int'],
'killrate_person'=>['대 인 살 상 률', 'percent'],
'dex1'=>['보 병 숙 련 도', 'int'], 'dex1'=>['보 병 숙 련 도', 'int'],
'dex2'=>['궁 병 숙 련 도', 'int'], 'dex2'=>['궁 병 숙 련 도', 'int'],
'dex3'=>['기 병 숙 련 도', 'int'], 'dex3'=>['기 병 숙 련 도', 'int'],
+1 -1
View File
@@ -72,7 +72,7 @@ var maxChiefTurn = <?=GameConst::$maxChiefTurn?>;
></div ></div
><div ><div
><?=chiefCommandTable($generalObj) ><?=chiefCommandTable($generalObj)
?><input type='button' id='setCommand' style='visibility:hidden;background-color:<?=GameConst::$basecolor2?>;color:white;font-size:13px;' value='실 행' ?><br><input type='button' id='setCommand' style='visibility:hidden;background-color:<?=GameConst::$basecolor2?>;color:white;font-size:13px;' value='실 행'
></div ></div
></div ></div
></div ></div
+1 -1
View File
@@ -93,7 +93,7 @@ switch ($type) {
case 5: $orderSQL = "order by crew desc"; break; case 5: $orderSQL = "order by crew desc"; break;
case 6: $orderSQL = "order by killturn"; break; case 6: $orderSQL = "order by killturn"; break;
case 7: $orderSQL = "order by turntime"; break; case 7: $orderSQL = "order by turntime"; break;
case 8: $orderSQL = "order by troop_leader desc"; break; case 8: $orderSQL = "order by troop desc"; break;
} }
$generals = $db->query( $generals = $db->query(
+527 -527
View File
@@ -1,527 +1,527 @@
<?php <?php
namespace sammo; namespace sammo;
include "lib.php"; include "lib.php";
include "func.php"; include "func.php";
//로그인 검사 //로그인 검사
$session = Session::requireGameLogin()->setReadOnly(); $session = Session::requireGameLogin()->setReadOnly();
$userID = Session::getUserID(); $userID = Session::getUserID();
$db = DB::db(); $db = DB::db();
increaseRefresh("인사부", 1); increaseRefresh("인사부", 1);
//훼섭 추방을 위해 갱신 //훼섭 추방을 위해 갱신
TurnExecutionHelper::executeAllCommand(); TurnExecutionHelper::executeAllCommand();
$me = $db->queryFirstRow('SELECT no,nation,officer_level from general where owner=%i', $userID); $me = $db->queryFirstRow('SELECT no,nation,officer_level from general where owner=%i', $userID);
$nationID = $me['nation']; $nationID = $me['nation'];
$meLevel = $me['officer_level']; $meLevel = $me['officer_level'];
if($meLevel == 0) { if($meLevel == 0) {
echo "재야입니다."; echo "재야입니다.";
exit(); exit();
} }
$nation = $db->queryFirstRow('SELECT nation,name,level,color,chief_set from nation where nation=%i', $nationID); //국가정보 $nation = $db->queryFirstRow('SELECT nation,name,level,color,chief_set from nation where nation=%i', $nationID); //국가정보
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=1024" /> <meta name="viewport" content="width=1024" />
<title><?=UniqueConst::$serverName?>: 인사부</title> <title><?=UniqueConst::$serverName?>: 인사부</title>
<?=WebUtil::printJS('../e_lib/jquery-3.3.1.min.js')?> <?=WebUtil::printJS('../e_lib/jquery-3.3.1.min.js')?>
<?=WebUtil::printJS('../e_lib/bootstrap.bundle.min.js')?> <?=WebUtil::printJS('../e_lib/bootstrap.bundle.min.js')?>
<?=WebUtil::printJS('../e_lib/select2/select2.full.min.js')?> <?=WebUtil::printJS('../e_lib/select2/select2.full.min.js')?>
<?=WebUtil::printJS('js/common.js')?> <?=WebUtil::printJS('js/common.js')?>
<?=WebUtil::printJS('js/bossInfo.js')?> <?=WebUtil::printJS('js/bossInfo.js')?>
<?=WebUtil::printCSS('../e_lib/bootstrap.min.css')?> <?=WebUtil::printCSS('../e_lib/bootstrap.min.css')?>
<?=WebUtil::printCSS('../e_lib/select2/select2.min.css')?> <?=WebUtil::printCSS('../e_lib/select2/select2.min.css')?>
<?=WebUtil::printCSS('../e_lib/select2/select2-bootstrap4.css')?> <?=WebUtil::printCSS('../e_lib/select2/select2-bootstrap4.css')?>
<?=WebUtil::printCSS('../d_shared/common.css')?> <?=WebUtil::printCSS('../d_shared/common.css')?>
<?=WebUtil::printCSS('css/common.css')?> <?=WebUtil::printCSS('css/common.css')?>
<script type="text/javascript"> <script type="text/javascript">
var chiefStatMin = <?=GameConst::$chiefStatMin?>; var chiefStatMin = <?=GameConst::$chiefStatMin?>;
var myLevel = <?=$meLevel?>; var myLevel = <?=$meLevel?>;
</script> </script>
<?php <?php
$ambassadors = $db->query('SELECT no, name, officer_level, penalty, permission FROM general WHERE permission = \'ambassador\' AND nation = %i', $nationID); $ambassadors = $db->query('SELECT no, name, officer_level, penalty, permission FROM general WHERE permission = \'ambassador\' AND nation = %i', $nationID);
$auditors = $db->query('SELECT no, name, officer_level, penalty, permission FROM general WHERE permission = \'auditor\' AND nation = %i', $nationID); $auditors = $db->query('SELECT no, name, officer_level, penalty, permission FROM general WHERE permission = \'auditor\' AND nation = %i', $nationID);
$candidateAmbassadors = []; $candidateAmbassadors = [];
$candidateAuditors = []; $candidateAuditors = [];
foreach($ambassadors as $ambassador){ foreach($ambassadors as $ambassador){
$candidateAmbassadors[] = $ambassador; $candidateAmbassadors[] = $ambassador;
} }
foreach($auditors as $auditor){ foreach($auditors as $auditor){
$candidateAuditors[] = $auditor; $candidateAuditors[] = $auditor;
} }
foreach($db->query('SELECT no, name, nation, officer_level, penalty, permission FROM general WHERE nation = %i AND permission = \'normal\' AND officer_level != 12', $nationID) as $candidate){ foreach($db->query('SELECT no, name, nation, officer_level, penalty, permission FROM general WHERE nation = %i AND permission = \'normal\' AND officer_level != 12', $nationID) as $candidate){
$maxPermission = checkSecretMaxPermission($candidate); $maxPermission = checkSecretMaxPermission($candidate);
if($maxPermission == 4){ if($maxPermission == 4){
$candidateAmbassadors[] = $candidate; $candidateAmbassadors[] = $candidate;
} }
if($maxPermission >= 3){ if($maxPermission >= 3){
$candidateAuditors[] = $candidate; $candidateAuditors[] = $candidate;
} }
} }
?> ?>
<script> <script>
var candidateAmbassadors = <?=Json::encode(array_map(function($value){ var candidateAmbassadors = <?=Json::encode(array_map(function($value){
return [ return [
'id'=>$value['no'], 'id'=>$value['no'],
'text'=>$value['name'], 'text'=>$value['name'],
"selected"=>($value['permission']!='normal') "selected"=>($value['permission']!='normal')
]; ];
}, $candidateAmbassadors))?>; }, $candidateAmbassadors))?>;
var candidateAuditors = <?=Json::encode(array_map(function($value){ var candidateAuditors = <?=Json::encode(array_map(function($value){
return [ return [
'id'=>$value['no'], 'id'=>$value['no'],
'text'=>$value['name'], 'text'=>$value['name'],
"selected"=>($value['permission']!='normal') "selected"=>($value['permission']!='normal')
]; ];
}, $candidateAuditors))?>; }, $candidateAuditors))?>;
</script> </script>
</head> </head>
<body> <body>
<table align=center width=1000 class='tb_layout bg0'> <table align=center width=1000 class='tb_layout bg0'>
<tr><td>인 사 부<br><?=backButton()?></td></tr> <tr><td>인 사 부<br><?=backButton()?></td></tr>
</table> </table>
<br> <br>
<?php <?php
$lv = getNationChiefLevel($nation['level']); $lv = getNationChiefLevel($nation['level']);
if($meLevel >= 5) { $btn = "button"; } if($meLevel >= 5) { $btn = "button"; }
else { $btn = "hidden"; } else { $btn = "hidden"; }
$level = Util::convertArrayToDict( $level = Util::convertArrayToDict(
$db->query( $db->query(
'SELECT name,officer_level,city,picture,imgsvr,belong from general where nation=%i and officer_level>=%i order by officer_level desc', 'SELECT name,officer_level,city,picture,imgsvr,belong from general where nation=%i and officer_level>=%i order by officer_level desc',
$nationID, $lv $nationID, $lv
), ),
'officer_level' 'officer_level'
); );
$tigers = $db->query('SELECT value, name $tigers = $db->query('SELECT value, name
FROM rank_data LEFT JOIN general ON rank_data.general_id = general.no FROM rank_data LEFT JOIN general ON rank_data.general_id = general.no
WHERE rank_data.nation_id = %i AND rank_data.type = "warnum" AND value > 0 ORDER BY value DESC LIMIT 5', WHERE rank_data.nation_id = %i AND rank_data.type = "killnum" AND value > 0 ORDER BY value DESC LIMIT 5',
$nationID $nationID
);// 오호장군 );// 오호장군
$tigerstr = join(', ', array_map(function($arr){ $tigerstr = join(', ', array_map(function($arr){
$number = number_format($arr['value']); $number = number_format($arr['value']);
return "{$arr['name']}【{$number}】"; return "{$arr['name']}【{$number}】";
}, $tigers)); }, $tigers));
$eagles = $db->query('SELECT value, name $eagles = $db->query('SELECT value, name
FROM rank_data LEFT JOIN general ON rank_data.general_id = general.no FROM rank_data LEFT JOIN general ON rank_data.general_id = general.no
WHERE rank_data.nation_id = %i AND rank_data.type = "firenum" AND value > 0 ORDER BY value DESC LIMIT 7', WHERE rank_data.nation_id = %i AND rank_data.type = "firenum" AND value > 0 ORDER BY value DESC LIMIT 7',
$nationID $nationID
);// 건안칠자 );// 건안칠자
$eaglestr = join(', ', array_map(function($arr){ $eaglestr = join(', ', array_map(function($arr){
$number = number_format($arr['value']); $number = number_format($arr['value']);
return "{$arr['name']}【{$number}】"; return "{$arr['name']}【{$number}】";
}, $eagles)); }, $eagles));
?> ?>
<table align=center width=1000 class='tb_layout bg0'> <table align=center width=1000 class='tb_layout bg0'>
<tr> <tr>
<td align=center style='color:<?=newColor($nation['color'])?>; background-color:<?=$nation['color']?>' colspan=6> <td align=center style='color:<?=newColor($nation['color'])?>; background-color:<?=$nation['color']?>' colspan=6>
<font size=5>【 <?=$nation['name']?> 】</font> <font size=5>【 <?=$nation['name']?> 】</font>
</td> </td>
</tr> </tr>
<?php <?php
for($i=12; $i >= $lv; $i-=2) { for($i=12; $i >= $lv; $i-=2) {
$i1 = $i; $i2 = $i - 1; $i1 = $i; $i2 = $i - 1;
$imageTemp1 = GetImageURL($level[$i1]['imgsvr']??0); $imageTemp1 = GetImageURL($level[$i1]['imgsvr']??0);
$imageTemp2 = GetImageURL($level[$i2]['imgsvr']??0); $imageTemp2 = GetImageURL($level[$i2]['imgsvr']??0);
?> ?>
<tr> <tr>
<td width=98 align=center id=bg1><font size=4><?=getOfficerLevelText($i1, $nation['level'])?></font></td> <td width=98 align=center id=bg1><font size=4><?=getOfficerLevelText($i1, $nation['level'])?></font></td>
<td width=64 class='generalIcon' height=64 style='background:no-repeat center url("<?=$imageTemp1?>/<?=$level[$i1]['picture']??'default.jpg'?>");background-size:64px;'></td> <td width=64 class='generalIcon' height=64 style='background:no-repeat center url("<?=$imageTemp1?>/<?=$level[$i1]['picture']??'default.jpg'?>");background-size:64px;'></td>
<td width=332><font size=4><?=$level[$i1]['name']??'-'?>(<?=$level[$i1]['belong']??'-'?>년)</font></td> <td width=332><font size=4><?=$level[$i1]['name']??'-'?>(<?=$level[$i1]['belong']??'-'?>년)</font></td>
<td width=98 align=center id=bg1><font size=4><?=getOfficerLevelText($i2, $nation['level'])?></font></td> <td width=98 align=center id=bg1><font size=4><?=getOfficerLevelText($i2, $nation['level'])?></font></td>
<td width=64 class='generalIcon' height=64 style='background:no-repeat center url("<?=$imageTemp2?>/<?=$level[$i2]['picture']??'default.jpg'?>");background-size:64px;'></td> <td width=64 class='generalIcon' height=64 style='background:no-repeat center url("<?=$imageTemp2?>/<?=$level[$i2]['picture']??'default.jpg'?>");background-size:64px;'></td>
<td width=332><font size=4><?=$level[$i2]['name']??'-'?>(<?=$level[$i2]['belong']??'-'?>년)</font></td> <td width=332><font size=4><?=$level[$i2]['name']??'-'?>(<?=$level[$i2]['belong']??'-'?>년)</font></td>
</tr> </tr>
<?php <?php
} }
?> ?>
<tr> <tr>
<td width=98 align=center id=bg1>오호장군【승전】</td> <td width=98 align=center id=bg1>오호장군【승전】</td>
<td colspan=5><?=$tigerstr?></td> <td colspan=5><?=$tigerstr?></td>
</tr> </tr>
<tr> <tr>
<td width=98 align=center id=bg1>건안칠자【계략】</td> <td width=98 align=center id=bg1>건안칠자【계략】</td>
<td colspan=5><?=$eaglestr?></td> <td colspan=5><?=$eaglestr?></td>
</tr> </tr>
</table> </table>
<table align=center width=1000 class='tb_layout bg0'> <table align=center width=1000 class='tb_layout bg0'>
<tr><td colspan=6 height=5></td></tr> <tr><td colspan=6 height=5></td></tr>
<tr><td colspan=2 align=center bgcolor=red>추 방</td></tr> <tr><td colspan=2 align=center bgcolor=red>추 방</td></tr>
<tr> <tr>
<td width=498 align=right id=bg1>대상 장수</td> <td width=498 align=right id=bg1>대상 장수</td>
<td width=498> <td width=498>
<?php <?php
if($meLevel >= 5){ if($meLevel >= 5){
$candidateStrength = $db->query('SELECT no,name,officer_level,city,npc from general where nation=%i and officer_level!=12 and strength>=%i order by npc,binary(name)', $nationID, GameConst::$chiefStatMin); $candidateStrength = $db->query('SELECT no,name,officer_level,city,npc from general where nation=%i and officer_level!=12 and strength>=%i order by npc,binary(name)', $nationID, GameConst::$chiefStatMin);
$candidateIntel = $db->query('SELECT no,name,officer_level,city,npc from general where nation=%i and officer_level!=12 and intel>=%i order by npc,binary(name)', $nationID, GameConst::$chiefStatMin); $candidateIntel = $db->query('SELECT no,name,officer_level,city,npc from general where nation=%i and officer_level!=12 and intel>=%i order by npc,binary(name)', $nationID, GameConst::$chiefStatMin);
$candidateAny = $db->query('SELECT no,name,officer_level,city,npc,leadership,strength,intel,killturn from general where nation=%i and officer_level!=12 order by npc,binary(name)', $nationID); //추방 때문에 조금 더 김 $candidateAny = $db->query('SELECT no,name,officer_level,city,npc,leadership,strength,intel,killturn from general where nation=%i and officer_level!=12 order by npc,binary(name)', $nationID); //추방 때문에 조금 더 김
} }
else{ else{
$candidateStrength = []; $candidateStrength = [];
$candidateIntel = []; $candidateIntel = [];
$candidateAny = []; $candidateAny = [];
} }
if($meLevel >= 5 && !isOfficerSet($nation['chief_set'], $meLevel)) { if($meLevel >= 5 && !isOfficerSet($nation['chief_set'], $meLevel)) {
echo " echo "
<select id='genlist_kick' size=1 style=color:white;background-color:black;>"; <select id='genlist_kick' size=1 style=color:white;background-color:black;>";
foreach($candidateAny as $general) { foreach($candidateAny as $general) {
if($general['no'] === $me['no']){ if($general['no'] === $me['no']){
continue; continue;
} }
echo " echo "
<option data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} <small>({$general['leadership']}/{$general['strength']}/{$general['intel']}, {$general['killturn']}턴)</small></option>"; <option data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} <small>({$general['leadership']}/{$general['strength']}/{$general['intel']}, {$general['killturn']}턴)</small></option>";
} }
echo " echo "
</select> </select>
<input type=$btn id='btn_kick' value=추방>"; <input type=$btn id='btn_kick' value=추방>";
} }
$officerLevelText = getOfficerLevelText(11, $nation['level']); $officerLevelText = getOfficerLevelText(11, $nation['level']);
echo " echo "
</td> </td>
</tr> </tr>
</table> </table>
<table align=center width=1000 class='tb_layout bg0'> <table align=center width=1000 class='tb_layout bg0'>
<tr><td colspan=4 height=5></td></tr> <tr><td colspan=4 height=5></td></tr>
<tr><td colspan=4 align=center bgcolor=blue>수 뇌 부 임 명</td></tr> <tr><td colspan=4 align=center bgcolor=blue>수 뇌 부 임 명</td></tr>
<tr> <tr>
<td width=98 align=right id=bg1>".getOfficerLevelText(12, $nation['level'])."</td> <td width=98 align=right id=bg1>".getOfficerLevelText(12, $nation['level'])."</td>
<td width=398>{$level[12]['name']} 【".CityConst::byID($level[12]['city'])->name."】</td> <td width=398>{$level[12]['name']} 【".CityConst::byID($level[12]['city'])->name."】</td>
<td width=98 align=right id=bg1>{$officerLevelText}</td> <td width=98 align=right id=bg1>{$officerLevelText}</td>
<td width=398> <td width=398>
"; ";
if($meLevel >= 5 && !isOfficerSet($nation['chief_set'], 11)) { if($meLevel >= 5 && !isOfficerSet($nation['chief_set'], 11)) {
echo " echo "
<select id='genlist_11' size=1 maxlength=15 style=color:white;background-color:black;> <select id='genlist_11' size=1 maxlength=15 style=color:white;background-color:black;>
<option value=0 data-officer_level='0' data-name=''>____공석____</option>"; <option value=0 data-officer_level='0' data-name=''>____공석____</option>";
foreach($candidateAny as $general) { foreach($candidateAny as $general) {
if($general['officer_level'] == 11) { if($general['officer_level'] == 11) {
echo "<option style=color:red; selected data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>"; echo "<option style=color:red; selected data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>";
} elseif($general['officer_level'] > 1) { } elseif($general['officer_level'] > 1) {
echo "<option style=color:orange; data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>"; echo "<option style=color:orange; data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>";
} else { } else {
echo "<option data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>"; echo "<option data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>";
} }
} }
echo " echo "
</select> </select>
<input class='btn_appoint' type=$btn data-officer_level='11' data-officer_level_text='{$officerLevelText}' value=임명>"; <input class='btn_appoint' type=$btn data-officer_level='11' data-officer_level_text='{$officerLevelText}' value=임명>";
} else { } else {
if(key_exists(11, $level)){ if(key_exists(11, $level)){
echo "{$level[11]['name']} 【".CityConst::byID($level[11]['city'])->name."】"; echo "{$level[11]['name']} 【".CityConst::byID($level[11]['city'])->name."】";
} }
} }
echo " echo "
</td> </td>
</tr> </tr>
"; ";
for($i=10; $i >= $lv; $i--) { for($i=10; $i >= $lv; $i--) {
if($i % 2 == 0) { echo "<tr>"; } if($i % 2 == 0) { echo "<tr>"; }
$officerLevelText = getOfficerLevelText($i, $nation['level']); $officerLevelText = getOfficerLevelText($i, $nation['level']);
echo " echo "
<td width=98 align=right id=bg1>{$officerLevelText}</td> <td width=98 align=right id=bg1>{$officerLevelText}</td>
<td width=398> <td width=398>
"; ";
if($meLevel >= 5 && !isOfficerSet($nation['chief_set'], $i)) { if($meLevel >= 5 && !isOfficerSet($nation['chief_set'], $i)) {
echo " echo "
<select id='genlist_{$i}' size=1 style=color:white;background-color:black;> <select id='genlist_{$i}' size=1 style=color:white;background-color:black;>
<option value=0 data-officer_level='0' data-name=''>____공석____</option>"; <option value=0 data-officer_level='0' data-name=''>____공석____</option>";
foreach(($i%2==0?$candidateStrength:$candidateIntel) as $general) { foreach(($i%2==0?$candidateStrength:$candidateIntel) as $general) {
if($general['officer_level'] == $i) { if($general['officer_level'] == $i) {
echo "<option style=color:red; selected data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>"; echo "<option style=color:red; selected data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>";
} elseif($general['officer_level'] > 1) { } elseif($general['officer_level'] > 1) {
echo "<option style=color:orange; data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>"; echo "<option style=color:orange; data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>";
} else { } else {
echo "<option data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>"; echo "<option data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>";
} }
} }
echo " echo "
</select> </select>
<input class='btn_appoint' type=$btn data-officer_level='{$i}' data-officer_level_text='$officerLevelText' value=임명>"; <input class='btn_appoint' type=$btn data-officer_level='{$i}' data-officer_level_text='$officerLevelText' value=임명>";
} else { } else {
$general = $level[$i]??null; $general = $level[$i]??null;
if($general){ if($general){
echo "{$general['name']} 【".CityConst::byID($general['city'])->name."】"; echo "{$general['name']} 【".CityConst::byID($general['city'])->name."】";
} }
} }
echo "</td>"; echo "</td>";
if($i % 2 == 1) { echo "</tr>"; } if($i % 2 == 1) { echo "</tr>"; }
} }
echo " echo "
<tr><td colspan=4>※ <font color=red>빨간색</font>은 현재 임명중인 장수, <font color=orange>노란색</font>은 다른 관직에 임명된 장수, 하얀색은 일반 장수를 뜻합니다.</td></tr> <tr><td colspan=4>※ <font color=red>빨간색</font>은 현재 임명중인 장수, <font color=orange>노란색</font>은 다른 관직에 임명된 장수, 하얀색은 일반 장수를 뜻합니다.</td></tr>
</table> </table>
"; ";
if($meLevel == 12): if($meLevel == 12):
?> ?>
<table align='center' width='1000' class='tb_layout bg0'> <table align='center' width='1000' class='tb_layout bg0'>
<tr><td colspan='4' height='5'></td></tr> <tr><td colspan='4' height='5'></td></tr>
<tr><td colspan='4' align='center' bgcolor='purple'>외 교 권 자 임 명</td></tr> <tr><td colspan='4' align='center' bgcolor='purple'>외 교 권 자 임 명</td></tr>
<tr> <tr>
<td width=98 align=right id=bg1>외교권자</td> <td width=98 align=right id=bg1>외교권자</td>
<td width=398> <td width=398>
<select id="selectAmbassador" multiple="multiple"> <select id="selectAmbassador" multiple="multiple">
</select> </select>
<button id='changeAmbassador' type='button'>임명</button> <button id='changeAmbassador' type='button'>임명</button>
</td> </td>
<td width=98 align=right id=bg1>조언자</td> <td width=98 align=right id=bg1>조언자</td>
<td width=398> <td width=398>
<select id="selectAuditor" multiple="multiple"> <select id="selectAuditor" multiple="multiple">
</select> </select>
<button id='changeAuditor' type='button'>임명</button> <button id='changeAuditor' type='button'>임명</button>
</td> </td>
</tr> </tr>
</table> </table>
<?php <?php
endif; endif;
?> ?>
<table align=center width=1000 id='officer_list' class='tb_layout bg0'> <table align=center width=1000 id='officer_list' class='tb_layout bg0'>
<tr><td colspan=5 height=5></td></tr> <tr><td colspan=5 height=5></td></tr>
<?php <?php
if($meLevel >= 5) { if($meLevel >= 5) {
$officerLevelText = getOfficerLevelText(4, $nation['level']); $officerLevelText = getOfficerLevelText(4, $nation['level']);
echo " echo "
<tr><td colspan=5 align=center bgcolor=orange>도 시 관 직 임 명</td></tr> <tr><td colspan=5 align=center bgcolor=orange>도 시 관 직 임 명</td></tr>
<tr> <tr>
<td colspan=3 align=right id=bg2>{$officerLevelText} 임명</td> <td colspan=3 align=right id=bg2>{$officerLevelText} 임명</td>
<td colspan=2> <td colspan=2>
<select id='citylist_4' size=1 style=color:white;background-color:black;> <select id='citylist_4' size=1 style=color:white;background-color:black;>
"; ";
$cityList = $db->query('SELECT city,name,region,officer_set FROM city WHERE nation=%i ORDER BY region,level DESC,binary(name)', $nationID); $cityList = $db->query('SELECT city,name,region,officer_set FROM city WHERE nation=%i ORDER BY region,level DESC,binary(name)', $nationID);
$region = 0; $region = 0;
foreach($cityList as $city){ foreach($cityList as $city){
if(isOfficerSet($city['officer_set'], 4)){ if(isOfficerSet($city['officer_set'], 4)){
continue; continue;
} }
if($region != $city['region']) { if($region != $city['region']) {
if($region != 0) { if($region != 0) {
echo "</optgroup>"; echo "</optgroup>";
} }
echo "<optgroup label=' 【 ".CityConst::$regionMap[$city['region']]." 】 ' style=color:skyblue;>"; echo "<optgroup label=' 【 ".CityConst::$regionMap[$city['region']]." 】 ' style=color:skyblue;>";
$region = $city['region']; $region = $city['region'];
} }
echo "<option value='{$city['city']}' style=color:white;><span class='name_field'>{$city['name']}</span></option>"; echo "<option value='{$city['city']}' style=color:white;><span class='name_field'>{$city['name']}</span></option>";
} }
echo "</optgroup>"; echo "</optgroup>";
echo " echo "
</select> </select>
<select id='genlist_4' size=1 style=color:white;background-color:black;> <select id='genlist_4' size=1 style=color:white;background-color:black;>
<option value=0 data-officer_level='0' data-name=''>____공석____</option> <option value=0 data-officer_level='0' data-name=''>____공석____</option>
"; ";
foreach($candidateStrength as $general) { foreach($candidateStrength as $general) {
if($general['officer_level'] == 4) { if($general['officer_level'] == 4) {
echo "<option style=color:red; data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>"; echo "<option style=color:red; data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>";
} elseif($general['officer_level'] > 1) { } elseif($general['officer_level'] > 1) {
echo "<option style=color:orange; data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>"; echo "<option style=color:orange; data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>";
} else { } else {
echo "<option data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>"; echo "<option data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>";
} }
} }
echo " echo "
</select> </select>
<input class='btn_appoint' type=$btn data-officer_level='4' data-officer_level_text='{$officerLevelText}' value=임명> <input class='btn_appoint' type=$btn data-officer_level='4' data-officer_level_text='{$officerLevelText}' value=임명>
</td> </td>
</tr>"; </tr>";
$officerLevelText = getOfficerLevelText(3, $nation['level']); $officerLevelText = getOfficerLevelText(3, $nation['level']);
echo "<tr> echo "<tr>
<td colspan=3 align=right id=bg2>{$officerLevelText} 임명</td> <td colspan=3 align=right id=bg2>{$officerLevelText} 임명</td>
<td colspan=2> <td colspan=2>
<select id='citylist_3' size=1 style=color:white;background-color:black;> <select id='citylist_3' size=1 style=color:white;background-color:black;>
"; ";
$region = 0; $region = 0;
foreach($cityList as $city){ foreach($cityList as $city){
if(isOfficerSet($city['officer_set'], 3)){ if(isOfficerSet($city['officer_set'], 3)){
continue; continue;
} }
if($region != $city['region']) { if($region != $city['region']) {
if($region != 0) { if($region != 0) {
echo "</optgroup>"; echo "</optgroup>";
} }
echo "<optgroup label=' 【 ".CityConst::$regionMap[$city['region']]." 】 ' style=color:skyblue;>"; echo "<optgroup label=' 【 ".CityConst::$regionMap[$city['region']]." 】 ' style=color:skyblue;>";
$region = $city['region']; $region = $city['region'];
} }
echo "<option value='{$city['city']}' style=color:white;><span class='name_field'>{$city['name']}</span></option>"; echo "<option value='{$city['city']}' style=color:white;><span class='name_field'>{$city['name']}</span></option>";
} }
echo "</optgroup>"; echo "</optgroup>";
echo " echo "
</select> </select>
<select id='genlist_3' size=1 style=color:white;background-color:black;> <select id='genlist_3' size=1 style=color:white;background-color:black;>
<option value=0 data-officer_level='0' data-name=''>____공석____</option> <option value=0 data-officer_level='0' data-name=''>____공석____</option>
"; ";
foreach($candidateIntel as $general) { foreach($candidateIntel as $general) {
if($general['officer_level'] == 3) { if($general['officer_level'] == 3) {
echo "<option style=color:red; data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>"; echo "<option style=color:red; data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>";
} elseif($general['officer_level'] > 1) { } elseif($general['officer_level'] > 1) {
echo "<option style=color:orange; data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>"; echo "<option style=color:orange; data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>";
} else { } else {
echo "<option data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>"; echo "<option data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>";
} }
} }
echo " echo "
</select> </select>
<input class='btn_appoint' type=$btn data-officer_level='3' data-officer_level_text='{$officerLevelText}' value=임명> <input class='btn_appoint' type=$btn data-officer_level='3' data-officer_level_text='{$officerLevelText}' value=임명>
</td> </td>
</tr>"; </tr>";
$officerLevelText = getOfficerLevelText(2, $nation['level']); $officerLevelText = getOfficerLevelText(2, $nation['level']);
echo "<tr> echo "<tr>
<td colspan=3 align=right id=bg2>{$officerLevelText} 임명</td> <td colspan=3 align=right id=bg2>{$officerLevelText} 임명</td>
<td colspan=2> <td colspan=2>
<select id='citylist_2' size=1 style=color:white;background-color:black;> <select id='citylist_2' size=1 style=color:white;background-color:black;>
"; ";
$region = 0; $region = 0;
foreach($cityList as $city){ foreach($cityList as $city){
if(isOfficerSet($city['officer_set'], 2)){ if(isOfficerSet($city['officer_set'], 2)){
continue; continue;
} }
if($region != $city['region']) { if($region != $city['region']) {
if($region != 0) { if($region != 0) {
echo "</optgroup>"; echo "</optgroup>";
} }
echo "<optgroup label=' 【 ".CityConst::$regionMap[$city['region']]." 】 ' style=color:skyblue;>"; echo "<optgroup label=' 【 ".CityConst::$regionMap[$city['region']]." 】 ' style=color:skyblue;>";
$region = $city['region']; $region = $city['region'];
} }
echo "<option value='{$city['city']}' style=color:white;><span class='name_field'>{$city['name']}</span></option>"; echo "<option value='{$city['city']}' style=color:white;><span class='name_field'>{$city['name']}</span></option>";
} }
echo "</optgroup>"; echo "</optgroup>";
echo " echo "
</select> </select>
<select id='genlist_2' size=1 style=color:white;background-color:black;> <select id='genlist_2' size=1 style=color:white;background-color:black;>
<option value=0>____<span class='name_field'>공석</span>____</option> <option value=0>____<span class='name_field'>공석</span>____</option>
"; ";
foreach ($candidateAny as $general) { foreach ($candidateAny as $general) {
if($general['officer_level'] == 2) { if($general['officer_level'] == 2) {
echo "<option style=color:red; data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>"; echo "<option style=color:red; data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>";
} elseif($general['officer_level'] > 1) { } elseif($general['officer_level'] > 1) {
echo "<option style=color:orange; data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>"; echo "<option style=color:orange; data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>";
} else { } else {
echo "<option data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>"; echo "<option data-officer_level='{$general['officer_level']}' data-name='{$general['name']}' value={$general['no']}>{$general['name']} 【".CityConst::byID($general['city'])->name."】</option>";
} }
} }
echo " echo "
</select> </select>
<input class='btn_appoint' type=$btn data-officer_level='2' data-officer_level_text='{$officerLevelText}' value=임명> <input class='btn_appoint' type=$btn data-officer_level='2' data-officer_level_text='{$officerLevelText}' value=임명>
</td> </td>
</tr> </tr>
<tr><td colspan=5>※ <font color=red>빨간색</font>은 현재 임명중인 장수, <font color=orange>노란색</font>은 다른 관직에 임명된 장수, 하얀색은 일반 장수를 뜻합니다.</td></tr> <tr><td colspan=5>※ <font color=red>빨간색</font>은 현재 임명중인 장수, <font color=orange>노란색</font>은 다른 관직에 임명된 장수, 하얀색은 일반 장수를 뜻합니다.</td></tr>
"; ";
} }
echo " echo "
<tr> <tr>
<td width=158 align=center id=bg1 colspan=2><font size=4>도 시</font></td> <td width=158 align=center id=bg1 colspan=2><font size=4>도 시</font></td>
<td width=278 align=center id=bg1><font size=4>태 수 (사관) 【현재도시】</font></td> <td width=278 align=center id=bg1><font size=4>태 수 (사관) 【현재도시】</font></td>
<td width=278 align=center id=bg1><font size=4>군 사 (사관) 【현재도시】</font></td> <td width=278 align=center id=bg1><font size=4>군 사 (사관) 【현재도시】</font></td>
<td width=278 align=center id=bg1><font size=4>종 사 (사관) 【현재도시】</font></td> <td width=278 align=center id=bg1><font size=4>종 사 (사관) 【현재도시】</font></td>
</tr> </tr>
"; ";
$citylevel = getCityLevelList(); $citylevel = getCityLevelList();
$officerList = []; $officerList = [];
foreach($db->query('SELECT no,name,npc,city,officer_level,officer_city,belong FROM general WHERE nation = %i AND 2 <= officer_level AND officer_level <= 4', $nationID) as $officer){ foreach($db->query('SELECT no,name,npc,city,officer_level,officer_city,belong FROM general WHERE nation = %i AND 2 <= officer_level AND officer_level <= 4', $nationID) as $officer){
$officerCityID = $officer['officer_city']; $officerCityID = $officer['officer_city'];
if(!key_exists($officerCityID, $officerList)){ if(!key_exists($officerCityID, $officerList)){
$officerList[$officerCityID] = []; $officerList[$officerCityID] = [];
} }
$officerList[$officerCityID][$officer['officer_level']] = $officer; $officerList[$officerCityID][$officer['officer_level']] = $officer;
} }
$region = 0; $region = 0;
$dummyOfficer = [ $dummyOfficer = [
'name'=>'-', 'name'=>'-',
'belong'=>0, 'belong'=>0,
]; ];
$textColor = newColor($nation['color']); $textColor = newColor($nation['color']);
$nationColor = $nation['color']; $nationColor = $nation['color'];
foreach($db->query('SELECT city,name,level,region,officer_set from city where nation=%i order by region,level desc,binary(name)', $nationID) as $city) { foreach($db->query('SELECT city,name,level,region,officer_set from city where nation=%i order by region,level desc,binary(name)', $nationID) as $city) {
$cityID = $city['city']; $cityID = $city['city'];
$cityOfficerList = $officerList[$cityID]??[]; $cityOfficerList = $officerList[$cityID]??[];
?> ?>
<?php if($region != $city['region']): ?> <?php if($region != $city['region']): ?>
<tr><td colspan=5 height=3 id=bg1></td></tr> <tr><td colspan=5 height=3 id=bg1></td></tr>
<tr><td colspan=5 id=bg1><font size=4 color=skyblue> 【 <?=CityConst::$regionMap[$city['region']]?> 】 </font></td></tr> <tr><td colspan=5 id=bg1><font size=4 color=skyblue> 【 <?=CityConst::$regionMap[$city['region']]?> 】 </font></td></tr>
<?php endif; $region = $city['region']; ?> <?php endif; $region = $city['region']; ?>
<tr> <tr>
<td width=78 align=center style='color:<?=$textColor?>;background-color:<?=$nationColor?>;font-size:1.2em;'>【<?=$citylevel[$city['level']]?>】</td> <td width=78 align=center style='color:<?=$textColor?>;background-color:<?=$nationColor?>;font-size:1.2em;'>【<?=$citylevel[$city['level']]?>】</td>
<td width=78 align=right style='color:<?=$textColor?>;background-color:<?=$nationColor?>;font-size:1.2em;'><?=$city['name']?>&nbsp;&nbsp;</td> <td width=78 align=right style='color:<?=$textColor?>;background-color:<?=$nationColor?>;font-size:1.2em;'><?=$city['name']?>&nbsp;&nbsp;</td>
<?php foreach(Util::range(4, 1, -1) as $officerLevel): ?> <?php foreach(Util::range(4, 1, -1) as $officerLevel): ?>
<?php if(key_exists($officerLevel, $cityOfficerList)): <?php if(key_exists($officerLevel, $cityOfficerList)):
$officer = $cityOfficerList[$officerLevel]; $officer = $cityOfficerList[$officerLevel];
?> ?>
<td><?=$officer['name']?>(<?=$officer['belong']?>년) 【<?=CityConst::byID($officer['city'])->name?>】</td> <td style="color:<?=isOfficerSet($city['officer_set'], $officerLevel)?'orange':'white'?>;"><?=$officer['name']?>(<?=$officer['belong']?>년) 【<?=CityConst::byID($officer['city'])->name?>】</td>
<?php else: ?> <?php else: ?>
<td>-</td> <td>-</td>
<?php endif; ?> <?php endif; ?>
<?php endforeach; ?> <?php endforeach; ?>
</tr> </tr>
<?php <?php
} }
?> ?>
<tr><td colspan=5>※ <font color=orange>노란색</font>은 변경 불가능, 하얀색은 변경 가능 관직입니다.</td></tr> <tr><td colspan=5>※ <font color=orange>노란색</font>은 변경 불가능, 하얀색은 변경 가능 관직입니다.</td></tr>
</table> </table>
<br> <br>
<table align=center width=1000 class='tb_layout bg0'> <table align=center width=1000 class='tb_layout bg0'>
<tr><td><?=backButton()?></td></tr> <tr><td><?=backButton()?></td></tr>
<tr><td><?=banner()?></td></tr> <tr><td><?=banner()?></td></tr>
</table> </table>
</body> </body>
</html> </html>
+32 -90
View File
@@ -4,29 +4,9 @@ namespace sammo;
include "lib.php"; include "lib.php";
include "func.php"; include "func.php";
$btn = Util::getPost('btn');
$defence_train = Util::getPost('defence_train', 'int', 2);
$tnmt = Util::getPost('tnmt', 'int', 1);
//$detachNPC = Util::getPost('detachNPC', 'bool');
$detachNPC = false;
$showDieImmediatelyBtn = false; $showDieImmediatelyBtn = false;
$availableDieImmediately = false; $availableDieImmediately = false;
if ($defence_train <= 60) {
$defence_train = 60;
}
else if($defence_train <= 80){
$defence_train = 80;
}
else{
$defence_train = 999;
}
if($tnmt < 0 || $tnmt > 1){
$tnmt = 1;
}
//로그인 검사 //로그인 검사
$session = Session::requireGameLogin()->setReadOnly(); $session = Session::requireGameLogin()->setReadOnly();
$userID = Session::getUserID(); $userID = Session::getUserID();
@@ -41,61 +21,24 @@ $me = General::createGeneralObjFromDB($generalID);
$myset = $me->getVar('myset'); $myset = $me->getVar('myset');
if ($myset > 0) { if ($myset > 0) {
$submit = 'submit'; $submit = 'button';
} else { } else {
$submit = 'hidden'; $submit = 'hidden';
} }
if (($btn == "설정저장" || $detachNPC) && $myset > 0) { $targetTime = addTurn($me->getVar('lastrefresh'), $gameStor->turnterm, 2);
if ($myset > 1) {
$submit = 'submit';
} else {
$submit = 'hidden';
}
if($defence_train != $me->getVar('defence_train')){
if($defence_train == 999){
$me->increaseVar('myset', -1);
$me->setVar('defence_train', $defence_train);
$me->increaseVar('train', -3);
$me->increaseVar('atmos', -3);
}
else{
$me->increaseVar('myset', -1);
$me->setVar('defence_train', $defence_train);
}
$myset -= 1;
}
if($me->getVar('tnmt') != $tnmt){
$me->setVar('tnmt', $tnmt);
}
if($me->getNPCType() == 1 && $detachNPC){
$turnterm = $gameStor->turnterm;
if($turnterm < 10){
$targetKillTurn = 30 / $turnterm;
}
else{
$targetKillTurn = 60 / $turnterm;
}
$me->setVar('killturn', $targetKillTurn);
}
}
$me->applyDB($db);
if($gameStor->turntime <= $gameStor->opentime){ if($gameStor->turntime <= $gameStor->opentime){
//서버 가오픈시 할 수 있는 행동 //서버 가오픈시 할 수 있는 행동
if($me->getNPCType() == 0){ if($me->getNPCType() == 0){
$showDieImmediatelyBtn = true; $showDieImmediatelyBtn = true;
if(addTurn($me->getVar('lastrefresh'), $gameStor->turnterm, 2) <= TimeUtil::now()){ if($targetTime <= TimeUtil::now()){
$availableDieImmediately = true; $availableDieImmediately = true;
} }
} }
} }
$use_treatment = $me->getAuxVar('use_treatment')??10;
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
@@ -104,6 +47,9 @@ if($gameStor->turntime <= $gameStor->opentime){
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=1024" /> <meta name="viewport" content="width=1024" />
<title><?=UniqueConst::$serverName?>: 내정보</title> <title><?=UniqueConst::$serverName?>: 내정보</title>
<script>
var availableDieImmediately = <?=$availableDieImmediately?'true':'false'?>;
</script>
<?=WebUtil::printJS('../e_lib/jquery-3.3.1.min.js')?> <?=WebUtil::printJS('../e_lib/jquery-3.3.1.min.js')?>
<?=WebUtil::printJS('../e_lib/bootstrap.bundle.min.js')?> <?=WebUtil::printJS('../e_lib/bootstrap.bundle.min.js')?>
<?=WebUtil::printJS('js/common.js')?> <?=WebUtil::printJS('js/common.js')?>
@@ -111,21 +57,6 @@ if($gameStor->turntime <= $gameStor->opentime){
<?=WebUtil::printCSS('../e_lib/bootstrap.min.css')?> <?=WebUtil::printCSS('../e_lib/bootstrap.min.css')?>
<?=WebUtil::printCSS('../d_shared/common.css')?> <?=WebUtil::printCSS('../d_shared/common.css')?>
<?=WebUtil::printCSS('css/common.css')?> <?=WebUtil::printCSS('css/common.css')?>
<script>
var availableDieImmediately = <?=$availableDieImmediately?'true':'false'?>;
jQuery(function($){
$('#die_immediately').click(function(){
if(!availableDieImmediately){
alert('삭제를 위해서는 생성 후 2턴 가량의 시간이 필요합니다.');
location.reload();
return false;
}
return confirm('정말로 삭제하시겠습니까?');
});
});
</script>
</head> </head>
<body> <body>
@@ -139,29 +70,40 @@ $('#die_immediately').click(function(){
<?php generalInfo2($me); ?> <?php generalInfo2($me); ?>
</td> </td>
<td width=50% valign=top style="padding-left:4ch;"> <td width=50% valign=top style="padding-left:4ch;">
<form name=form1 action=b_myPage.php method=post>
토너먼트 【 토너먼트 【
<input type=radio name=tnmt value=0 <?=$me->getVar('tnmt')==0?"checked":""; ?>>수동참여 <input type=radio class='tnmt' name=tnmt value=0 <?=$me->getVar('tnmt')==0?"checked":""; ?>>수동참여
<input type=radio name=tnmt value=1 <?=$me->getVar('tnmt')==1?"checked":""; ?>>자동참여 <input type=radio class='tnmt' name=tnmt value=1 <?=$me->getVar('tnmt')==1?"checked":""; ?>>자동참여
】<br> 】<br>
∞<font color=orange>개막직전 남는자리가 있을경우 랜덤하게 참여합니다.</font><br><br> ∞<span style='color:orange'>개막직전 남는자리가 있을경우 랜덤하게 참여합니다.</span><br><br>
수비 【
<input type=radio name=defence_train value=80 <?=$me->getVar('defence_train')==80?"checked":""; ?>>◎(훈사80) 환약 사용 【<select id='use_treatment' name='use_treatment'>
<input type=radio name=defence_train value=60 <?=$me->getVar('defence_train')==60?"checked":""; ?>>○(훈사60) <option value=10 <?=$use_treatment==10?"selected":""; ?>>경상</option>
<input type=radio name=defence_train value=999 <?=$me->getVar('defence_train')==999?"checked":""; ?>>× <option value=20 <?=$use_treatment==21?"selected":""; ?>>중상</option>
<option value=40 <?=$use_treatment==41?"selected":""; ?>>심각</option>
<option value=60 <?=$use_treatment==61?"selected":""; ?>>위독</option>
<option value=100 <?=$use_treatment==100?"selected":""; ?>>사용안함</option>
</select>】<br>
∞<span style='color:orange'>부상을 입었을 때 환약을 사용하는 기준입니다.</span><br><br>
수비 【<select id='defence_train' name='defence_train'>
<option value=90 <?=$me->getVar('defence_train')==90?"selected":""; ?>>☆(훈사90)</option>
<option value=80 <?=$me->getVar('defence_train')==80?"selected":""; ?>>◎(훈사80)</option>
<option value=60 <?=$me->getVar('defence_train')==60?"selected":""; ?>>○(훈사60)</option>
<option value=40 <?=$me->getVar('defence_train')==40?"selected":""; ?>>△(훈사40)</option>
<option value=999 <?=$me->getVar('defence_train')==999?"selected":""; ?>>×[훈련, 사기 -3]</option>
</select>
】<br><br> 】<br><br>
<input type=<?=$submit?> name=btn style=background-color:<?=GameConst::$basecolor2?>;color:white;width:160px;height:30px;font-size:13px; value=설정저장><br> <input type=<?=$submit?> id='set_my_setting' name=btn style=background-color:<?=GameConst::$basecolor2?>;color:white;width:160px;height:30px;font-size:13px; value=설정저장><br>
∞<font color=orange>설정저장은 이달중 <?=$myset?>회 남았습니다.</font><br><br> ∞<span style='color:orange'>설정저장은 이달중 <?=$myset?>회 남았습니다.</span><br><br>
</form>
<?php if(!($gameStor->autorun_user['limit_minutes']??false)): ?> <?php if(!($gameStor->autorun_user['limit_minutes']??false)): ?>
휴 가 신 청<br> 휴 가 신 청<br>
<a href="c_vacation.php"><button type="button" style=background-color:<?=GameConst::$basecolor2?>;color:white;width:160px;height:30px;font-size:13px;>휴가 신청</button></a><br><br> <button type="button" id='vacation' style=background-color:<?=GameConst::$basecolor2?>;color:white;width:160px;height:30px;font-size:13px;>휴가 신청</button><br><br>
<?php endif; ?> <?php endif; ?>
<!--빙의 해제용 삭턴 조절<br> <!--빙의 해제용 삭턴 조절<br>
<a href="b_myPage.php?detachNPC=1"><button type="button" style=background-color:<?=GameConst::$basecolor2?>;color:white;width:160px;height:30px;font-size:13px;>빙의 해체 요청</button></a>--> <a href="b_myPage.php?detachNPC=1"><button type="button" style=background-color:<?=GameConst::$basecolor2?>;color:white;width:160px;height:30px;font-size:13px;>빙의 해체 요청</button></a>-->
<?php if($showDieImmediatelyBtn): ?> <?php if($showDieImmediatelyBtn): ?>
가오픈 기간 내 장수 삭제<br> 가오픈 기간 내 장수 삭제 (<?=substr($targetTime, 0, 19)?> 부터)<br>
<a href="c_die_immediately.php" id='die_immediately'><button type="button" style=background-color:<?=GameConst::$basecolor2?>;color:white;width:160px;height:30px;font-size:13px;>장수 삭제</button></a><br><br> <a href="c_die_immediately.php" id='die_immediately'><button type="button" style=background-color:<?=GameConst::$basecolor2?>;color:white;width:160px;height:30px;font-size:13px;>장수 삭제</button></a><br><br>
<?php endif; ?> <?php endif; ?>
+6 -5
View File
@@ -64,6 +64,7 @@ if ($currentNationPolicy['reqHumanWarUrgentGold'] ?? 0) {
$autoPolicyVariable['reqHumanWarUrgentGold'] = $currentNationPolicy['reqHumanWarUrgentGold']; $autoPolicyVariable['reqHumanWarUrgentGold'] = $currentNationPolicy['reqHumanWarUrgentGold'];
} }
$autoPolicy = new AutorunNationPolicy($general, ($gameStor->autorun_user)['options'], ['values' => $autoPolicyVariable], null, $nation, $gameStor->getAll(true)); $autoPolicy = new AutorunNationPolicy($general, ($gameStor->autorun_user)['options'], ['values' => $autoPolicyVariable], null, $nation, $gameStor->getAll(true));
$zeroPolicy = new AutorunNationPolicy($general, ($gameStor->autorun_user)['options'], null, null, $nation, $gameStor->getAll(true));
?> ?>
@@ -117,7 +118,7 @@ $autoPolicy = new AutorunNationPolicy($general, ($gameStor->autorun_user)['optio
'긴급내정': '전쟁중에 민심이 70 미만이거나,<br>인구가 제자리 징병이 가능하지 않을 정도로 적을 경우,<br>일정확률로 주민선정과 정착장려를 수행합니다.<br><br>통솔이 높을 수록 수행할 확률이 높습니다.', '긴급내정': '전쟁중에 민심이 70 미만이거나,<br>인구가 제자리 징병이 가능하지 않을 정도로 적을 경우,<br>일정확률로 주민선정과 정착장려를 수행합니다.<br><br>통솔이 높을 수록 수행할 확률이 높습니다.',
'전투준비': '충분한 병력을 가지고 있지만 훈련과 사기가 부족한 경우 훈련과 사기진작을 수행합니다.', '전투준비': '충분한 병력을 가지고 있지만 훈련과 사기가 부족한 경우 훈련과 사기진작을 수행합니다.',
'전방워프': '전투장이 충분한 병력을 가지고 있다면 전방으로 이동합니다.', '전방워프': '전투장이 충분한 병력을 가지고 있다면 전방으로 이동합니다.',
'NPC헌납': '국고가 부족한데 NPC장수가 충분한 금쌀을 가지고 있다면 일부를 헌납합니다. <br>NPC내정장은 국고가 넉넉하더라도 충분한 금쌀을 가지고 있다면 일부를 헌납합니다.', 'NPC헌납': '국고가 부족한데 NPC전쟁장이 충분한 금쌀(권장량 대비 1.5배)을 가지고 있다면 일부를 헌납합니다. <br>NPC내정장은 국고가 넉넉하더라도 충분한 금쌀을 가지고 있다면 권장량만 유지하고 헌납합니다.',
'징병': '전쟁 중 병력을 소진하였다면 재 징병합니다.<br><br>기존에 사용한 병종군 중에서 사용가능한 병종을 랜덤하게 선택합니다.<br>고급 병종을 선택할 확률이 조금 더 높습니다.<br><br>NPC의 경우 도시의 인구가 충분하지 않다면 징병을 할 확률이 감소합니다.<br><br>유저장은 최대한 고급병종을 유지하며,<br>유저장 모병이 허용되는 경우 모병을 3회할 수 있다면 모병합니다.', '징병': '전쟁 중 병력을 소진하였다면 재 징병합니다.<br><br>기존에 사용한 병종군 중에서 사용가능한 병종을 랜덤하게 선택합니다.<br>고급 병종을 선택할 확률이 조금 더 높습니다.<br><br>NPC의 경우 도시의 인구가 충분하지 않다면 징병을 할 확률이 감소합니다.<br><br>유저장은 최대한 고급병종을 유지하며,<br>유저장 모병이 허용되는 경우 모병을 3회할 수 있다면 모병합니다.',
'후방워프': '전쟁 중 병력을 소진하였는데 도시의 인구가 충분하지 않다면,<br>인구가 많은 도시로 이동합니다.', '후방워프': '전쟁 중 병력을 소진하였는데 도시의 인구가 충분하지 않다면,<br>인구가 많은 도시로 이동합니다.',
'전쟁내정': '전쟁 중 수행하는 내정입니다.<br>정착장려, 기술연구의 확률이 좀 더 높고,<br>치안강화, 농지개간, 상업투자의 확률이 낮습니다.<br><br>내정이 가능하다 하더라도 전시임을 고려해,<br>30% 확률로 다른 턴을 수행합니다.', '전쟁내정': '전쟁 중 수행하는 내정입니다.<br>정착장려, 기술연구의 확률이 좀 더 높고,<br>치안강화, 농지개간, 상업투자의 확률이 낮습니다.<br><br>내정이 가능하다 하더라도 전시임을 고려해,<br>30% 확률로 다른 턴을 수행합니다.',
@@ -184,7 +185,7 @@ $autoPolicy = new AutorunNationPolicy($general, ($gameStor->autorun_user)['optio
</div> </div>
<div style='text-align:right;'><small class="form-text text-muted"> <div style='text-align:right;'><small class="form-text text-muted">
유저장긴급포상시 이보다 금이 적은 장수에게 포상합니다.<br> 유저장긴급포상시 이보다 금이 적은 장수에게 포상합니다.<br>
0이면 보병 6회 징병(<?= number_format(GameConst::$defaultStatMax * 100) ?> * 6) 가능한 금을 기준으로 하며, 그 수치는 현재 <?= number_format($autoPolicy->reqHumanWarUrgentGold) ?>입니다.</small></div> 0이면 보병 6회 징병(<?= number_format(GameConst::$defaultStatMax * 100) ?> * 6) 가능한 금을 기준으로 하며, 그 수치는 현재 <?= number_format($zeroPolicy->reqHumanWarUrgentGold) ?>입니다.</small></div>
</div> </div>
<div class="col-sm-6"> <div class="col-sm-6">
<div class="row"> <div class="row">
@@ -193,7 +194,7 @@ $autoPolicy = new AutorunNationPolicy($general, ($gameStor->autorun_user)['optio
<input type="number" class="form-control" data-type="integer" id="reqHumanWarUrgentRice" min="0" value="0"> <input type="number" class="form-control" data-type="integer" id="reqHumanWarUrgentRice" min="0" value="0">
</div> </div>
</div> </div>
<div style='text-align:right;'><small class="form-text text-muted">유저장긴급포상시 이보다 쌀이 적은 장수에게 포상합니다.<br>0이면 기본 병종으로 <?= number_format(GameConst::$defaultStatMax * 100 * 6) ?>명 사살 가능한 쌀을 기준으로 하며, 그 수치는 현재 <?= number_format($autoPolicy->reqHumanWarUrgentRice) ?>입니다.</small></div> <div style='text-align:right;'><small class="form-text text-muted">유저장긴급포상시 이보다 쌀이 적은 장수에게 포상합니다.<br>0이면 기본 병종으로 <?= number_format(GameConst::$defaultStatMax * 100 * 6) ?>명 사살 가능한 쌀을 기준으로 하며, 그 수치는 현재 <?= number_format($zeroPolicy->reqHumanWarUrgentRice) ?>입니다.</small></div>
</div> </div>
</div> </div>
<div class="form-group row"> <div class="form-group row">
@@ -205,7 +206,7 @@ $autoPolicy = new AutorunNationPolicy($general, ($gameStor->autorun_user)['optio
</div> </div>
</div> </div>
<div style='text-align:right;'><small class="form-text text-muted">유저전투장에게 주는 금입니다. 이보다 적으면 포상합니다. <br> <div style='text-align:right;'><small class="form-text text-muted">유저전투장에게 주는 금입니다. 이보다 적으면 포상합니다. <br>
0이면 유저전투장 긴급포상 금의 3배를 기준으로 하며, 그 수치는 현재 <?= number_format($autoPolicy->reqHumanWarRecommandGold) ?>입니다.</small></div> 0이면 유저전투장 긴급포상 금의 2배를 기준으로 하며, 그 수치는 현재 <?= number_format($autoPolicy->reqHumanWarRecommandGold) ?>입니다.</small></div>
</div> </div>
<div class="col-sm-6"> <div class="col-sm-6">
<div class="row"> <div class="row">
@@ -215,7 +216,7 @@ $autoPolicy = new AutorunNationPolicy($general, ($gameStor->autorun_user)['optio
</div> </div>
</div> </div>
<div style='text-align:right;'><small class="form-text text-muted">유저전투장에게 주는 쌀입니다. 이보다 적으면 포상합니다. <br> <div style='text-align:right;'><small class="form-text text-muted">유저전투장에게 주는 쌀입니다. 이보다 적으면 포상합니다. <br>
0이면 유저전투장 긴급포상 쌀의 3배를 기준으로 하며, 그 수치는 현재 <?= number_format($autoPolicy->reqHumanWarRecommandRice) ?>입니다.</small></div> 0이면 유저전투장 긴급포상 쌀의 2배를 기준으로 하며, 그 수치는 현재 <?= number_format($autoPolicy->reqHumanWarRecommandRice) ?>입니다.</small></div>
</div> </div>
</div> </div>
<div class="form-group row"> <div class="form-group row">
+131 -127
View File
@@ -1,127 +1,131 @@
<?php <?php
namespace sammo; namespace sammo;
include "lib.php"; include "lib.php";
include "func.php"; include "func.php";
//로그인 검사 //로그인 검사
$commandType = Util::getReq('command', 'string'); $commandType = Util::getReq('command', 'string');
$turnList = array_map('intval', explode('_', Util::getReq('turnList', 'string', '0'))); $turnList = array_map('intval', explode('_', Util::getReq('turnList', 'string', '0')));
$isChiefTurn = Util::getReq('is_chief', 'bool', false); $isChiefTurn = Util::getReq('is_chief', 'bool', false);
function die_redirect() function die_redirect()
{ {
global $isChiefTurn; global $isChiefTurn;
if(!$isChiefTurn){ if(!$isChiefTurn){
header('location:index.php', true, 303); header('location:index.php', true, 303);
} }
else{ else{
header('location:b_chiefcenter.php', true, 303); header('location:b_chiefcenter.php', true, 303);
} }
die(); die();
} }
if(!$turnList || !$commandType){ if(!$turnList || !$commandType){
die_redirect(); die_redirect();
} }
if(!is_array($turnList)){ if(!is_array($turnList)){
die_redirect(); die_redirect();
} }
$session = Session::requireGameLogin()->setReadOnly(); $session = Session::requireGameLogin()->setReadOnly();
$db = DB::db(); $db = DB::db();
if(!$isChiefTurn && !in_array($commandType, Util::array_flatten(GameConst::$availableGeneralCommand))){ if(!$isChiefTurn && !in_array($commandType, Util::array_flatten(GameConst::$availableGeneralCommand))){
die_redirect(); die_redirect();
} }
if($isChiefTurn && !in_array($commandType, Util::array_flatten(GameConst::$availableChiefCommand))){ if($isChiefTurn && !in_array($commandType, Util::array_flatten(GameConst::$availableChiefCommand))){
die_redirect(); die_redirect();
} }
$gameStor = KVStorage::getStorage($db, 'game_env')->turnOnCache(); $gameStor = KVStorage::getStorage($db, 'game_env')->turnOnCache();
$env = $gameStor->getAll(); $env = $gameStor->getAll();
$general = General::createGeneralObjFromDB($session->generalID); $general = General::createGeneralObjFromDB($session->generalID);
if(!$isChiefTurn){ if(!$isChiefTurn){
$commandObj = buildGeneralCommandClass($commandType, $general, $env); $commandObj = buildGeneralCommandClass($commandType, $general, $env);
} }
else{ else{
if($general->getVar('officer_level') < 5){ if($general->getVar('officer_level') < 5){
die_redirect(); die_redirect();
} }
$commandObj = buildNationCommandClass($commandType, $general, $env, new LastTurn()); $commandObj = buildNationCommandClass($commandType, $general, $env, new LastTurn());
} }
if($commandObj->isArgValid()){ if($commandObj->isArgValid()){
//인자가 필요없는 타입의 경우 processing에서 '전혀' 처리하지 않음! //인자가 필요없는 타입의 경우 processing에서 '전혀' 처리하지 않음!
die_redirect(); die_redirect();
} }
if(!$commandObj->hasPermissionToReserve()){ if(!$commandObj->hasPermissionToReserve()){
die_redirect(); die_redirect();
} }
$jsList = $commandObj->getJSFiles(); $jsList = $commandObj->getJSFiles();
$cssList = $commandObj->getCSSFiles(); $cssList = $commandObj->getCSSFiles();
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<title><?=$commandObj->getName()?></title> <title><?=$commandObj->getName()?></title>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=1024" /> <meta name="viewport" content="width=1024" />
<?=WebUtil::printJS('../e_lib/jquery-3.3.1.min.js')?> <?=WebUtil::printJS('../e_lib/jquery-3.3.1.min.js')?>
<?=WebUtil::printJS('../e_lib/bootstrap.bundle.min.js')?> <?=WebUtil::printJS('../e_lib/bootstrap.bundle.min.js')?>
<?=WebUtil::printJS('../d_shared/common_path.js')?> <?=WebUtil::printJS('../e_lib/select2/select2.full.min.js')?>
<?=WebUtil::printJS('js/common.js')?> <?=WebUtil::printJS('../d_shared/common_path.js')?>
<?=WebUtil::printJS('d_shared/base_map.js')?> <?=WebUtil::printJS('js/common.js')?>
<?=WebUtil::printJS('js/map.js')?> <?=WebUtil::printJS('d_shared/base_map.js')?>
<?=WebUtil::printJS('js/processing.js')?> <?=WebUtil::printJS('js/map.js')?>
<script> <?=WebUtil::printJS('js/processing.js')?>
window.serverNick = '<?=DB::prefix()?>'; <script>
window.serverID = '<?=UniqueConst::$serverID?>'; window.serverNick = '<?=DB::prefix()?>';
window.command = '<?=$commandType?>'; window.serverID = '<?=UniqueConst::$serverID?>';
window.turnList = [<?=join(', ',$turnList)?>]; window.command = '<?=$commandType?>';
window.isChiefTurn = <?=$isChiefTurn?'true':'false'?>; window.turnList = [<?=join(', ',$turnList)?>];
</script> window.isChiefTurn = <?=$isChiefTurn?'true':'false'?>;
<?php </script>
foreach($jsList as $js){ <?php
print(WebUtil::printJS($js)); foreach($jsList as $js){
} print(WebUtil::printJS($js));
?> }
<?=WebUtil::printCSS('../e_lib/bootstrap.min.css')?> ?>
<?=WebUtil::printCSS('../d_shared/common.css')?> <?=WebUtil::printCSS('../e_lib/bootstrap.min.css')?>
<?=WebUtil::printCSS('css/common.css')?> <?=WebUtil::printCSS('../e_lib/select2/select2.min.css')?>
<?=WebUtil::printCSS('css/main.css')?> <?=WebUtil::printCSS('../e_lib/select2/select2-bootstrap4.css')?>
<?=WebUtil::printCSS('css/map.css')?> <?=WebUtil::printCSS('../d_shared/common.css')?>
<?php <?=WebUtil::printCSS('css/common.css')?>
foreach($cssList as $css){ <?=WebUtil::printCSS('css/main.css')?>
print(WebUtil::printCSS($css)); <?=WebUtil::printCSS('css/map.css')?>
} <?=WebUtil::printCSS('css/processing.css')?>
?> <?php
</head> foreach($cssList as $css){
<body class="img_back"> print(WebUtil::printCSS($css));
<table class="tb_layout bg0" style="width:1000px;margin:auto;"> }
<tr><td class="bg1" style='text-align:center;'><?=$commandObj->getName()?></td></tr> ?>
<tr><td> </head>
<input type=button value='돌아가기' onclick="history.back();"><br> <body class="img_back">
</td></tr></table> <table class="tb_layout bg0" style="width:1000px;margin:auto;">
<tr><td class="bg1" style='text-align:center;'><?=$commandObj->getName()?></td></tr>
<div class="tb_layout bg0" style="width:1000px;margin:auto;padding-bottom:2em;border:solid 1px gray;"> <tr><td>
<?=$commandObj->getForm()?> <input type=button value='돌아가기' onclick="history.back();"><br>
</div> </td></tr></table>
<table class="tb_layout bg0" style="width:1000px;margin:auto;"> <div class="tb_layout bg0" style="width:1000px;margin:auto;padding-bottom:2em;border:solid 1px gray;">
<tr><td> <?=$commandObj->getForm()?>
<input type=button value='돌아가기' onclick="history.back();"><br> </div>
<?=banner()?>
</td></tr></table> <table class="tb_layout bg0" style="width:1000px;margin:auto;">
<tr><td>
<input type=button value='돌아가기' onclick="history.back();"><br>
</body> <?=banner()?>
</html> </td></tr></table>
</body>
</html>
+1 -1
View File
@@ -49,6 +49,7 @@ if($btn == '참가') {
$general['gold'] -= $admin['develcost']; $general['gold'] -= $admin['develcost'];
$freeSlot = [ $freeSlot = [
0=>8,
1=>8, 1=>8,
2=>8, 2=>8,
3=>8, 3=>8,
@@ -56,7 +57,6 @@ if($btn == '참가') {
5=>8, 5=>8,
6=>8, 6=>8,
7=>8, 7=>8,
8=>8,
]; ];
foreach($db->query('SELECT count(*) as cnt, grp FROM tournament WHERE grp < 10 GROUP BY grp') as $grpInfo){ foreach($db->query('SELECT count(*) as cnt, grp FROM tournament WHERE grp < 10 GROUP BY grp') as $grpInfo){
if($grpInfo['cnt'] == 8){ if($grpInfo['cnt'] == 8){
+11
View File
@@ -0,0 +1,11 @@
#amount {
width: 100px;
}
#colorType {
width: 150px;
}
.no-padding .select2-results__option {
padding: 0;
}
+8 -1
View File
@@ -1241,7 +1241,7 @@ function addAge()
$generalID = $general['no']; $generalID = $general['no'];
$special = SpecialityHelper::pickSpecialDomestic( $special = SpecialityHelper::pickSpecialDomestic(
$general, $general,
(Json::decode($general['aux'])['prev_types_special2'])??[] (Json::decode($general['aux'])['prev_types_special'])??[]
); );
$specialClass = buildGeneralSpecialDomesticClass($special); $specialClass = buildGeneralSpecialDomesticClass($special);
$specialText = $specialClass->getName(); $specialText = $specialClass->getName();
@@ -1336,8 +1336,11 @@ function CheckHall($no)
["warnum", 'rank'], ["warnum", 'rank'],
["killnum", 'rank'], ["killnum", 'rank'],
["winrate", 'calc'], ["winrate", 'calc'],
["occupied", 'rank'],
["killcrew", 'rank'], ["killcrew", 'rank'],
["killrate", 'calc'], ["killrate", 'calc'],
["killcrew_person", 'rank'],
["killrate_person", 'calc'],
["dex1", 'natural'], ["dex1", 'natural'],
["dex2", 'natural'], ["dex2", 'natural'],
["dex3", 'natural'], ["dex3", 'natural'],
@@ -1380,6 +1383,9 @@ function CheckHall($no)
$kill = $generalObj->getRankVar('killcrew'); $kill = $generalObj->getRankVar('killcrew');
$death = Util::valueFit($generalObj->getRankVar('deathcrew'), 1); $death = Util::valueFit($generalObj->getRankVar('deathcrew'), 1);
$killPerson = $generalObj->getRankVar('killcrew_person');
$deathPerson = Util::valueFit($generalObj->getRankVar('deathcrew_person'), 1);
$tt = Util::valueFit($ttw + $ttd + $ttl, 1); $tt = Util::valueFit($ttw + $ttd + $ttl, 1);
$tl = Util::valueFit($tlw + $tld + $tll, 1); $tl = Util::valueFit($tlw + $tld + $tll, 1);
$ts = Util::valueFit($tsw + $tsd + $tsl, 1); $ts = Util::valueFit($tsw + $tsd + $tsl, 1);
@@ -1393,6 +1399,7 @@ function CheckHall($no)
$calcVar['betrate'] = $betWinGold / $betGold; $calcVar['betrate'] = $betWinGold / $betGold;
$calcVar['winrate'] = $win / $war; $calcVar['winrate'] = $win / $war;
$calcVar['killrate'] = $kill / $death; $calcVar['killrate'] = $kill / $death;
$calcVar['killrate_person'] = $killPerson / $deathPerson;
if ($generalObj instanceof DummyGeneral) { if ($generalObj instanceof DummyGeneral) {
return; return;
+6 -4
View File
@@ -565,7 +565,9 @@ function updateNationState()
$nation['level'] = $nationlevel; $nation['level'] = $nationlevel;
$updateVals = [ $updateVals = [
'level' => $nationlevel 'level' => $nationlevel,
'gold'=>$db->sqleval('gold + %i', $nationlevel*1000),
'rice'=>$db->sqleval('rice + %i', $nationlevel*1000),
]; ];
switch ($nationlevel) { switch ($nationlevel) {
@@ -708,7 +710,8 @@ function updateNationState()
'troop' => $npcID 'troop' => $npcID
], 'no=%i', $npcID); ], 'no=%i', $npcID);
//TODO: 5턴간 집합턴 입력 $cmd = buildGeneralCommandClass('che_집합', General::createGeneralObjFromDB($npcID), $admin);
_setGeneralCommand($cmd, iterator_to_array(Util::range(GameConst::$maxTurn)));
$assemblerCnt += 1; $assemblerCnt += 1;
$gameStor->assembler_id = $lastAssemblerID; $gameStor->assembler_id = $lastAssemblerID;
} }
@@ -1008,7 +1011,7 @@ function checkEmperior()
$tigers = $db->query( $tigers = $db->query(
'SELECT value, name 'SELECT value, name
FROM rank_data LEFT JOIN general ON rank_data.general_id = general.no FROM rank_data LEFT JOIN general ON rank_data.general_id = general.no
WHERE rank_data.nation_id = %i AND rank_data.type = "warnum" AND value > 0 ORDER BY value DESC LIMIT 5', WHERE rank_data.nation_id = %i AND rank_data.type = "killnum" AND value > 0 ORDER BY value DESC LIMIT 5',
$nationID $nationID
); // 오호장군 ); // 오호장군
@@ -1037,7 +1040,6 @@ function checkEmperior()
} }
$gen = join(', ', array_column($rawGeneral, 'name')); $gen = join(', ', array_column($rawGeneral, 'name'));
$nation['type'] = getNationType($nation['type']);
$stat = $db->queryFirstRow('SELECT max(nation_count) as nc, max(gen_count) as gc FROM statistic'); $stat = $db->queryFirstRow('SELECT max(nation_count) as nc, max(gen_count) as gc FROM statistic');
$genCnt = $db->queryFirstField('SELECT count(*) FROM general'); $genCnt = $db->queryFirstField('SELECT count(*) FROM general');
+20 -4
View File
@@ -39,10 +39,26 @@ function bar($per, $h=7) {
} }
function optionsForCities() { function optionsForCities(callable $infoCall=null) {
return join('', array_map(function($city){
return "<option value='{$city->id}'>{$city->name}</option>"; if(!$infoCall){
}, CityConst::all())); return join('', array_map(function($city){
return "<option value='{$city->id}'>{$city->name}</option>";
}, CityConst::all()));
}
$infoList = [];
$noInfoList = [];
foreach(CityConst::all() as $city){
$info = $infoCall($city);
if(!$info){
$noInfoList[] = "<option value='{$city->id}'>{$city->name}</option>";
continue;
}
$infoList[] = "<option value='{$city->id}'>{$city->name} ({$info})</option>";
}
return join('', array_merge($infoList, $noInfoList));
} }
function Submit($url, $msg="", $msg2="") { function Submit($url, $msg="", $msg2="") {
+23 -17
View File
@@ -78,6 +78,7 @@ function processGoldIncome() {
// 실지급률 // 실지급률
$ratio = $realoutcome / $originoutcome; $ratio = $realoutcome / $originoutcome;
} }
$nation['gold'] = Util::valueFit($nation['gold'], GameConst::$basegold);
$adminLog[] = StringUtil::padStringAlignRight((string)$nation['name'],12," ") $adminLog[] = StringUtil::padStringAlignRight((string)$nation['name'],12," ")
." // 세금 : ".StringUtil::padStringAlignRight((string)$income,6," ") ." // 세금 : ".StringUtil::padStringAlignRight((string)$income,6," ")
." // 세출 : ".StringUtil::padStringAlignRight((string)$originoutcome,6," ") ." // 세출 : ".StringUtil::padStringAlignRight((string)$originoutcome,6," ")
@@ -87,6 +88,8 @@ function processGoldIncome() {
$incomeText = number_format($income); $incomeText = number_format($income);
$incomeLog = "이번 수입은 금 <C>$incomeText</>입니다."; $incomeLog = "이번 수입은 금 <C>$incomeText</>입니다.";
$nationStor = KVStorage::getStorage($db, $nationID, 'nation_env');
$nationStor->prev_income_gold = $income;
$db->update('nation', [ $db->update('nation', [
'gold'=>$nation['gold'] 'gold'=>$nation['gold']
@@ -353,6 +356,7 @@ function processRiceIncome() {
// 실지급률 // 실지급률
$ratio = $realoutcome / $originoutcome; $ratio = $realoutcome / $originoutcome;
} }
$nation['rice'] = Util::valueFit($nation['rice'], GameConst::$baserice);
$adminLog[] = StringUtil::padStringAlignRight($nation['name'],12," ") $adminLog[] = StringUtil::padStringAlignRight($nation['name'],12," ")
." // 세곡 : ".StringUtil::padStringAlignRight((string)$income,6," ") ." // 세곡 : ".StringUtil::padStringAlignRight((string)$income,6," ")
." // 세출 : ".StringUtil::padStringAlignRight((string)$originoutcome,6," ") ." // 세출 : ".StringUtil::padStringAlignRight((string)$originoutcome,6," ")
@@ -362,6 +366,8 @@ function processRiceIncome() {
$incomeText = number_format($income); $incomeText = number_format($income);
$incomeLog = "이번 수입은 쌀 <C>$incomeText</>입니다."; $incomeLog = "이번 수입은 쌀 <C>$incomeText</>입니다.";
$nationStor = KVStorage::getStorage($db, $nationID, 'nation_env');
$nationStor->prev_income_rice = $income;
$db->update('nation', [ $db->update('nation', [
'rice'=>$nation['rice'] 'rice'=>$nation['rice']
@@ -528,36 +534,36 @@ function disaster() {
$targetCityNames = "<G><b>".join(' ', Util::squeezeFromArray($targetCityList, 'name'))."</b></>"; $targetCityNames = "<G><b>".join(' ', Util::squeezeFromArray($targetCityList, 'name'))."</b></>";
$disasterTextList = [ $disasterTextList = [
1 => [ 1 => [
['재난', 4, '역병이 발생하여 도시가 황폐해지고 있습니다.'], ['<M><b>【재난】</b></>', 4, '역병이 발생하여 도시가 황폐해지고 있습니다.'],
['재난', 5, '지진으로 피해가 속출하고 있습니다.'], ['<M><b>【재난】</b></>', 5, '지진으로 피해가 속출하고 있습니다.'],
['재난', 3, '추위가 풀리지 않아 얼어죽는 백성들이 늘어나고 있습니다.'], ['<M><b>【재난】</b></>', 3, '추위가 풀리지 않아 얼어죽는 백성들이 늘어나고 있습니다.'],
['재난', 9, '황건적이 출현해 도시를 습격하고 있습니다.'], ['<M><b>【재난】</b></>', 9, '황건적이 출현해 도시를 습격하고 있습니다.'],
], ],
4 => [ 4 => [
['재난', 7, '홍수로 인해 피해가 급증하고 있습니다.'], ['<M><b>【재난】</b></>', 7, '홍수로 인해 피해가 급증하고 있습니다.'],
['재난', 5, '지진으로 피해가 속출하고 있습니다.'], ['<M><b>【재난】</b></>', 5, '지진으로 피해가 속출하고 있습니다.'],
['재난', 6, '태풍으로 인해 피해가 속출하고 있습니다.'], ['<M><b>【재난】</b></>', 6, '태풍으로 인해 피해가 속출하고 있습니다.'],
], ],
7 => [ 7 => [
['재난', 8, '메뚜기 떼가 발생하여 도시가 황폐해지고 있습니다.'], ['<M><b>【재난】</b></>', 8, '메뚜기 떼가 발생하여 도시가 황폐해지고 있습니다.'],
['재난', 5, '지진으로 피해가 속출하고 있습니다.'], ['<M><b>【재난】</b></>', 5, '지진으로 피해가 속출하고 있습니다.'],
['재난', 8, '흉년이 들어 굶어죽는 백성들이 늘어나고 있습니다.'], ['<M><b>【재난】</b></>', 8, '흉년이 들어 굶어죽는 백성들이 늘어나고 있습니다.'],
], ],
10 => [ 10 => [
['재난', 3, '혹한으로 도시가 황폐해지고 있습니다.'], ['<M><b>【재난】</b></>', 3, '혹한으로 도시가 황폐해지고 있습니다.'],
['재난', 5, '지진으로 피해가 속출하고 있습니다.'], ['<M><b>【재난】</b></>', 5, '지진으로 피해가 속출하고 있습니다.'],
['재난', 3, '눈이 많이 쌓여 도시가 황폐해지고 있습니다.'], ['<M><b>【재난】</b></>', 3, '눈이 많이 쌓여 도시가 황폐해지고 있습니다.'],
['재난', 9, '황건적이 출현해 도시를 습격하고 있습니다.'], ['<M><b>【재난】</b></>', 9, '황건적이 출현해 도시를 습격하고 있습니다.'],
] ]
]; ];
$boomingTextList = [ $boomingTextList = [
1 => null, 1 => null,
4 => [ 4 => [
['호황', 2, '호황으로 도시가 번창하고 있습니다.'], ['<C><b>【호황】</b></>', 2, '호황으로 도시가 번창하고 있습니다.'],
], ],
7 => [ 7 => [
['풍작', 1, '풍작으로 도시가 번창하고 있습니다.'], ['<C><b>【풍작】</b></>', 1, '풍작으로 도시가 번창하고 있습니다.'],
], ],
10 => null 10 => null
]; ];
@@ -566,7 +572,7 @@ function disaster() {
$logger = new ActionLogger(0, 0, $year, $month, false); $logger = new ActionLogger(0, 0, $year, $month, false);
$logger->pushGlobalHistoryLog("<M><b>【{$logTitle}】</b></>{$targetCityNames}{$logBody}"); $logger->pushGlobalHistoryLog("{$logTitle}{$targetCityNames}{$logBody}");
$logger->flush(); $logger->flush();
if (!$isGood) { if (!$isGood) {
@@ -4,6 +4,9 @@ namespace sammo;
include "lib.php"; include "lib.php";
include "func.php"; include "func.php";
WebUtil::requireAJAX();
$availableDieImmediately = false; $availableDieImmediately = false;
//로그인 검사 //로그인 검사
@@ -16,25 +19,31 @@ $gameStor = KVStorage::getStorage($db, 'game_env');
$general = $db->queryFirstRow('SELECT no,name,owner_name,npc,lastrefresh FROM general WHERE owner=%i AND npc = 0', $userID); $general = $db->queryFirstRow('SELECT no,name,owner_name,npc,lastrefresh FROM general WHERE owner=%i AND npc = 0', $userID);
if(!$general){ if(!$general){
header('location:b_myPage.php'); Json::die([
die(); 'result'=>false,
'reason'=>'장수가 없습니다.'
]);
} }
increaseRefresh("장수 삭제", 1); increaseRefresh("장수 삭제", 1);
$gameStor->cacheValues(['turnterm', 'opentime', 'turntime', 'year', 'month']); $gameStor->cacheValues(['turnterm', 'opentime', 'turntime', 'year', 'month']);
if($gameStor->turntime <= $gameStor->opentime){ if($gameStor->turntime > $gameStor->opentime){
//서버 가오픈시 할 수 있는 행동 Json::die([
if(addTurn($general['lastrefresh'], $gameStor->turnterm, 2) <= TimeUtil::now()){ 'result'=>false,
$availableDieImmediately = true; 'reason'=>'이미 서버가 시작되었습니다.'
} ]);
} }
if(!$availableDieImmediately){
header('location:b_myPage.php');
die();
}
$targetTime = addTurn($general['lastrefresh'], $gameStor->turnterm, 2);
if($targetTime > TimeUtil::now()){
$targetTimeShort = substr($targetTime, 0, 19);
Json::die([
'result'=>false,
'reason'=>"아직 삭제할 수 없습니다. {$targetTimeShort} 부터 가능합니다."
]);
}
$generalObj = General::createGeneralObjFromDB($general['no']); $generalObj = General::createGeneralObjFromDB($general['no']);
@@ -46,4 +55,7 @@ $josaYi = JosaUtil::pick($generalName, '이');
$generalObj->kill($db, true, "<Y>{$generalName}</>{$josaYi} 이 홀연히 모습을 <R>감추었습니다</>"); $generalObj->kill($db, true, "<Y>{$generalName}</>{$josaYi} 이 홀연히 모습을 <R>감추었습니다</>");
$session->logoutGame(); $session->logoutGame();
header('location:..'); Json::die([
'result'=>true,
'reason'=>'success'
]);
+100 -93
View File
@@ -1,94 +1,101 @@
<?php <?php
namespace sammo; namespace sammo;
include "lib.php"; include "lib.php";
include "func.php"; include "func.php";
//로그인 검사 //로그인 검사
$session = Session::requireGameLogin()->setReadOnly(); $session = Session::requireGameLogin()->setReadOnly();
$userID = Session::getUserID(); $userID = Session::getUserID();
$db = DB::db(); $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
increaseRefresh("사령부", 1); increaseRefresh("사령부", 1);
$me = $db->queryFirstRow('SELECT no,nation,officer_level,con,turntime,belong,penalty,permission FROM general WHERE owner=%i', $userID); $me = $db->queryFirstRow('SELECT no,nation,officer_level,con,turntime,belong,penalty,permission FROM general WHERE owner=%i', $userID);
$nationLevel = $db->queryFirstField('SELECT level FROM nation WHERE nation = %i', $me['nation']); $nationLevel = $db->queryFirstField('SELECT level FROM nation WHERE nation = %i', $me['nation']);
$nationID = $me['nation']; $nationID = $me['nation'];
$con = checkLimit($me['con']); $con = checkLimit($me['con']);
if($con >= 2) { if($con >= 2) {
Json::die([ Json::die([
'result'=>false, 'result'=>false,
'reason'=>"접속 제한중입니다. 1턴 이내에 너무 많은 갱신을 하셨습니다. (다음 접속 가능 시각 : {$me['turntime']})" 'reason'=>"접속 제한중입니다. 1턴 이내에 너무 많은 갱신을 하셨습니다. (다음 접속 가능 시각 : {$me['turntime']})"
]); ]);
} }
$permission = checkSecretPermission($me); $permission = checkSecretPermission($me);
if($permission < 0){ if($permission < 0){
Json::die([ Json::die([
'result'=>false, 'result'=>false,
'reason'=>'국가에 소속되어있지 않습니다.' 'reason'=>'국가에 소속되어있지 않습니다.'
]); ]);
echo '국가에 소속되어있지 않습니다.'; echo '국가에 소속되어있지 않습니다.';
die(); die();
} }
else if ($permission < 1) { else if ($permission < 1) {
Json::die([ Json::die([
'result'=>false, 'result'=>false,
'reason'=>'수뇌부가 아니거나 사관년도가 부족합니다.' 'reason'=>'수뇌부가 아니거나 사관년도가 부족합니다.'
]); ]);
die(); die();
} }
$date = TimeUtil::now(); $date = TimeUtil::now();
// 명령 목록 // 명령 목록
[$year, $month, $turnterm] = $gameStor->getValuesAsArray(['year', 'month', 'turnterm']); [$year, $month, $turnterm] = $gameStor->getValuesAsArray(['year', 'month', 'turnterm']);
$lv = getNationChiefLevel($nationLevel); $lv = getNationChiefLevel($nationLevel);
$turn = []; $turn = [];
$generals = []; $generals = [];
foreach($db->query('SELECT no,name,turntime,npc,city,nation,officer_level FROM general WHERE nation = %i AND officer_level >= 5',$nationID) as $rawGeneral){ foreach($db->query('SELECT no,name,turntime,npc,city,nation,officer_level FROM general WHERE nation = %i AND officer_level >= 5',$nationID) as $rawGeneral){
$generals[$rawGeneral['officer_level']] = new General($rawGeneral, null, null, null, $year, $month, false); $generals[$rawGeneral['officer_level']] = new General($rawGeneral, null, null, null, $year, $month, false);
} }
$nationTurnList = []; $nationTurnList = [];
foreach( foreach(
$db->queryAllLists( $db->queryAllLists(
'SELECT officer_level, turn_idx, action, arg, brief FROM nation_turn WHERE nation_id = %i ORDER BY officer_level DESC, turn_idx ASC', 'SELECT officer_level, turn_idx, action, arg, brief FROM nation_turn WHERE nation_id = %i ORDER BY officer_level DESC, turn_idx ASC',
$me['nation'] $me['nation']
) as [$officer_level, $turn_idx, $action, $arg, $brief] ) as [$officer_level, $turn_idx, $action, $arg, $brief]
){ ){
if(!key_exists($officer_level, $nationTurnList)){ if(!key_exists($officer_level, $nationTurnList)){
$nationTurnList[$officer_level] = []; $nationTurnList[$officer_level] = [];
} }
$nationTurnList[$officer_level][$turn_idx] = $brief; $nationTurnList[$officer_level][$turn_idx] = $brief;
} }
$nationTurnBrief = []; $nationTurnBrief = [];
foreach($nationTurnList as $officer_level=>$turnBrief){ foreach($nationTurnList as $officer_level=>$turnBrief){
if(!key_exists($officer_level, $generals)){ if(!key_exists($officer_level, $generals)){
continue; $nationTurnBrief[$officer_level] = [
} 'name'=>null,
$general = $generals[$officer_level]; 'turnTime'=>null,
$nationTurnBrief[$officer_level] = [ 'officerLevelText'=>getOfficerLevelText($officer_level, $nationLevel),
'name'=>$general->getName(), 'npcType'=>null,
'turnTime'=>$general->getTurnTime($general::TURNTIME_FULL), 'turn'=>$turnBrief
'officerLevelText'=>getOfficerLevelText($general->getVar('officer_level'), $nationLevel), ];
'npcType'=>$general->getNPCType(), continue;
'turn'=>$turnBrief }
]; $general = $generals[$officer_level];
} $nationTurnBrief[$officer_level] = [
'name'=>$general->getName(),
$date = substr(TimeUtil::now(), 14); 'turnTime'=>$general->getTurnTime($general::TURNTIME_FULL),
'officerLevelText'=>getOfficerLevelText($general->getVar('officer_level'), $nationLevel),
Json::die([ 'npcType'=>$general->getNPCType(),
'result'=>true, 'turn'=>$turnBrief
'reason'=>'success', ];
'date'=>$date, }
'nationTurnBrief'=>$nationTurnBrief,
'isChief'=>($me['officer_level'] > 4), $date = substr(TimeUtil::now(), 14);
'turnTerm'=>$turnterm
Json::die([
'result'=>true,
'reason'=>'success',
'date'=>$date,
'nationTurnBrief'=>$nationTurnBrief,
'isChief'=>($me['officer_level'] > 4),
'turnTerm'=>$turnterm
]); ]);
+95 -77
View File
@@ -1,4 +1,5 @@
<?php <?php
namespace sammo; namespace sammo;
//통합 세력장수&암행부 viewer //통합 세력장수&암행부 viewer
@@ -11,145 +12,162 @@ $session = Session::requireGameLogin([])->setReadOnly();
$userID = Session::getUserID(); $userID = Session::getUserID();
$db = DB::db(); $db = DB::db();
$reqType = Util::getPost('req', 'int', 1); $reqType = Util::getReq('req', 'int', 1);
$reqForce = Util::getPost('force', 'bool', false); $reqForce = Util::getReq('force', 'bool', false);
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
increaseRefresh("세력장수", 1); increaseRefresh("세력장수", 1);
$me = $db->queryFirstRow('SELECT con, turntime, nation, officer_level, permission, penalty FROM general WHERE owner=%i', $userID); $me = $db->queryFirstRow('SELECT con, turntime, belong, nation, officer_level, permission, penalty FROM general WHERE owner=%i', $userID);
$con = checkLimit($me['con']); $con = checkLimit($me['con']);
if ($con >= 2) { if ($con >= 2) {
Json::die([ Json::die([
'result'=>false, 'result' => false,
'reason'=>'접속 제한중입니다. 1턴 이내에 너무 많은 갱신을 하셨습니다.' 'reason' => '접속 제한중입니다. 1턴 이내에 너무 많은 갱신을 하셨습니다.'
]); ]);
} }
$nationID = $me['nation']; $nationID = $me['nation'];
$permission = checkSecretPermission($me, true); $permission = checkSecretPermission($me, true);
if($reqForce && $reqType > $permission){ if ($reqForce && $reqType > $permission) {
Json::die([ Json::die([
'result'=>false, 'result' => false,
'reason'=>'권한이 부족합니다.' 'reason' => '권한이 부족합니다.'
]); ]);
} }
$permission = min($reqType, $permission); $permission = min($reqType, $permission);
$nationArr = getNationStaticInfo($nationID); $nationArr = getNationStaticInfo($nationID);
$viewColumns = [ $viewColumns = [
'no'=>1, 'no' => 0,
'name'=>1, 'name' => 0,
'owner_name'=>9, 'owner_name' => 9,
'nation'=>1, 'nation' => 0,
'city'=>1, 'city' => 1,
'officer_level'=>9, 'officer_level' => 2,
'npc'=>1, 'officer_city' => 2,
'defence_train'=>2, 'npc' => 0,
'troop'=>2, 'defence_train' => 2,
'injury'=>1, 'troop' => 2,
'leadership'=>1, 'injury' => 0,
'strength'=>1, 'leadership' => 0,
'intel'=>1, 'strength' => 0,
'experience'=>1, 'intel' => 0,
'explevel'=>1, 'experience' => 1,
'dedication'=>1, 'explevel' => 0,
'dedlevel'=>1, 'dedication' => 1,
'gold'=>1, 'dedlevel' => 0,
'rice'=>1, 'gold' => 0,
'crewtype'=>2, 'rice' => 0,
'crew'=>2, 'crewtype' => 2,
'train'=>2, 'crew' => 2,
'atmos'=>2, 'train' => 2,
'killturn'=>1, 'atmos' => 2,
'turntime'=>2, 'killturn' => 0,
'picture'=>1, 'turntime' => 2,
'imgsvr'=>1, 'picture' => 0,
'age'=>1, 'imgsvr' => 0,
'special'=>1, 'age' => 0,
'special2'=>1, 'special' => 0,
'personal'=>1, 'special2' => 0,
'horse'=>3, 'personal' => 0,
'weapon'=>3, 'belong' => 0,
'book'=>3, 'horse' => 2,
'item'=>3, 'weapon' => 2,
'connect'=>1 'book' => 2,
'item' => 2,
'connect' => 0
]; ];
$customViewColumns = [ $customViewColumns = [
'officerLevel'=>1, 'officerLevel' => 0,
'officerLevelText'=>1, 'officerLevelText' => 0,
'lbonus'=>1, 'lbonus' => 0,
'ownerName'=>1, 'ownerName' => 0,
'honorText'=>1, 'honorText' => 0
'expLevelText'=>1,
]; ];
function getOfficerLevel($rawGeneral)
{
global $permission;
$level = $rawGeneral['officer_level'];
if ($level >= 5) {
return $level;
}
if ($permission > 1) {
return $level;
}
return 1;
}
$specialViewFilter = [ $specialViewFilter = [
'officerLevel'=>function($rawGeneral){ 'officerLevel' => function ($rawGeneral){
return $rawGeneral['officer_level']; return getOfficerLevel($rawGeneral);
}, },
'special'=>function($rawGeneral){ 'special' => function ($rawGeneral) {
return getGeneralSpecialDomesticName($rawGeneral['special']); return getGeneralSpecialDomesticName($rawGeneral['special']);
}, },
'special2'=>function($rawGeneral){ 'special2' => function ($rawGeneral) {
return getGeneralSpecialWarName($rawGeneral['special2']); return getGeneralSpecialWarName($rawGeneral['special2']);
}, },
'personal'=>function($rawGeneral){ 'personal' => function ($rawGeneral) {
return getGenChar($rawGeneral['personal']); return getGenChar($rawGeneral['personal']);
}, },
'lbonus'=>function($rawGeneral)use($nationArr){ 'lbonus' => function ($rawGeneral) use ($nationArr) {
return calcLeadershipBonus($rawGeneral['officer_level'], $nationArr['level']); return calcLeadershipBonus($rawGeneral['officer_level'], $nationArr['level']);
}, },
'ownerName'=>function($rawGeneral){ 'ownerName' => function ($rawGeneral) {
if($rawGeneral['npc']!=1){ if ($rawGeneral['npc'] != 1) {
return null; return null;
} }
return $rawGeneral['owner_name']; return $rawGeneral['owner_name'];
}, },
'officerLevelText'=>function($rawGeneral)use($nationArr){ 'officerLevelText' => function ($rawGeneral) use ($nationArr) {
return getOfficerLevelText($rawGeneral['officer_level'], $nationArr['level']); $level = getOfficerLevel($rawGeneral);
return getOfficerLevelText($level, $nationArr['level']);
}, },
'honorText'=>function($rawGeneral){ 'honorText' => function ($rawGeneral) {
return getHonor($rawGeneral['experience']); return getHonor($rawGeneral['experience']);
}, },
'dedLevelText'=>function($rawGeneral){ 'dedLevelText' => function ($rawGeneral) {
return getDedLevelText($rawGeneral['dedLevel']); return getDedLevelText($rawGeneral['dedLevel']);
}, },
'turntime'=>function($rawGeneral){ 'turntime' => function ($rawGeneral) {
//'0000-00-00 11:23'; //'0000-00-00 11:23';
return substr($rawGeneral['turntime'], 11, 5); return substr($rawGeneral['turntime'], 11, 5);
} }
]; ];
$queryColumns = General::mergeQueryColumn(array_keys($viewColumns), 1); [$queryColumns, $rankColumns] = General::mergeQueryColumn(array_keys($viewColumns), 1);
$rawGeneralList = Util::convertArrayToDict($db->queryAllLists('SELECT %lb from general WHERE nation = %i', $queryColumns, $nationID), 'no'); $rawGeneralList = Util::convertArrayToDict($db->query('SELECT %l from general WHERE nation = %i', Util::formatListOfBackticks($queryColumns), $nationID), 'no');
$resultColumns = []; $resultColumns = [];
foreach($viewColumns as $column=>$reqPermission){ foreach ($viewColumns as $column => $reqPermission) {
if($reqPermission > $permission){ if ($reqPermission > $permission) {
continue; continue;
} }
$resultColumns[] = $column; $resultColumns[] = $column;
} }
foreach($customViewColumns as $column=>$reqPermission){ foreach ($customViewColumns as $column => $reqPermission) {
if($reqPermission > $permission){ if ($reqPermission > $permission) {
continue; continue;
} }
$resultColumns[] = $column; $resultColumns[] = $column;
} }
foreach($rawGeneralList as $rawGeneral){ foreach ($rawGeneralList as $rawGeneral) {
//General 생성? //General 생성?
$item = []; $item = [];
foreach($resultColumns as $column){ foreach ($resultColumns as $column) {
$value = $rawGeneral[$column]; if (key_exists($column, $specialViewFilter)) {
if(key_exists($column, $specialViewFilter)){
$value = $specialViewFilter[$column]($rawGeneral); $value = $specialViewFilter[$column]($rawGeneral);
} }
else{
$value = $rawGeneral[$column];
}
$item[] = $value; $item[] = $value;
} }
@@ -157,9 +175,9 @@ foreach($rawGeneralList as $rawGeneral){
} }
$result = [ $result = [
'result'=>true, 'result' => true,
'column'=>$resultColumns, 'column' => $resultColumns,
'list'=>$generalList, 'list' => $generalList,
]; ];
Json::die($result); Json::die($result);
+2
View File
@@ -8,6 +8,8 @@ WebUtil::requireAJAX();
$session = Session::requireGameLogin([])->setReadOnly(); $session = Session::requireGameLogin([])->setReadOnly();
increaseRefresh("사령턴 입력", 0);
$generalID = $session->generalID; $generalID = $session->generalID;
+2
View File
@@ -8,6 +8,8 @@ WebUtil::requireAJAX();
$session = Session::requireGameLogin([])->setReadOnly(); $session = Session::requireGameLogin([])->setReadOnly();
increaseRefresh("턴 입력", 0);
$generalID = $session->generalID; $generalID = $session->generalID;
$action = Util::getPost('action', 'string'); $action = Util::getPost('action', 'string');
+77
View File
@@ -0,0 +1,77 @@
<?php
namespace sammo;
include "lib.php";
include "func.php";
WebUtil::requireAJAX();
$session = Session::requireGameLogin([])->setReadOnly();
$userID = Session::getUserID();
$generalID = $session->generalID;
increaseRefresh("내정보 수정", 0);
$action = Util::getPost('action');
$tnmt = Util::getPost('tnmt', 'int', 1);
$defence_train = Util::getPost('defence_train', 'int', 80);
$use_treatment = Util::getPost('use_treatment', 'int', 10);
//$detachNPC = Util::getPost('detachNPC', 'bool');
$detachNPC = false;
if ($defence_train <= 40) {
$defence_train = 40;
}
if($defence_train <= 90){
$defence_train = Util::round($defence_train, -1);
}
else{
$defence_train = 999;
}
if($tnmt < 0 || $tnmt > 1){
$tnmt = 1;
}
$db = DB::db();
$me = General::createGeneralObjFromDB($generalID);
if($defence_train != $me->getVar('defence_train')){
if($defence_train == 999){
$me->increaseVar('myset', -1);
$me->setVar('defence_train', $defence_train);
$me->increaseVar('train', -3);
$me->increaseVar('atmos', -3);
}
else{
$me->increaseVar('myset', -1);
$me->setVar('defence_train', $defence_train);
}
}
$me->setAuxVar('use_treatment', Util::valueFit($use_treatment, 10, 100));
if($me->getVar('tnmt') != $tnmt){
$me->setVar('tnmt', $tnmt);
}
if($me->getNPCType() == 1 && $detachNPC){
$turnterm = $gameStor->turnterm;
if($turnterm < 10){
$targetKillTurn = 30 / $turnterm;
}
else{
$targetKillTurn = 60 / $turnterm;
}
$me->setVar('killturn', $targetKillTurn);
}
$me->applyDB($db);
Json::die([
'result'=>true,
'reason'=>'success'
]);
+2 -6
View File
@@ -10,6 +10,7 @@ $session = Session::requireGameLogin([])->setReadOnly();
$userID = Session::getUserID(); $userID = Session::getUserID();
$generalID = $session->generalID; $generalID = $session->generalID;
increaseRefresh("NPC 정책 수정", 0);
$type = Util::getPost('type', 'string'); $type = Util::getPost('type', 'string');
$data = Util::getPost('data', 'string'); $data = Util::getPost('data', 'string');
@@ -47,12 +48,7 @@ if (!$nationID) {
'reason'=>'국가에 소속되어있지 않습니다.', 'reason'=>'국가에 소속되어있지 않습니다.',
]); ]);
} }
if ($me['officer_level'] < 5) {
Json::die([
'result'=>false,
'reason'=>'수뇌가 아닙니다.',
]);
}
$permission = checkSecretPermission($me); $permission = checkSecretPermission($me);
if ($permission < 3) { if ($permission < 3) {
Json::die([ Json::die([
+2
View File
@@ -9,6 +9,8 @@ WebUtil::requireAJAX();
$session = Session::requireLogin([])->setReadOnly(); $session = Session::requireLogin([])->setReadOnly();
$userID = Session::getUserID(); $userID = Session::getUserID();
increaseRefresh("시뮬레이터", 0);
$query = Util::getPost('query'); $query = Util::getPost('query');
if($query === null){ if($query === null){
Json::die([ Json::die([
+2
View File
@@ -15,6 +15,8 @@ $troop = Util::getPost('troop', 'int');
$session = Session::requireGameLogin([])->setReadOnly(); $session = Session::requireGameLogin([])->setReadOnly();
$userID = $session::getUserID(); $userID = $session::getUserID();
increaseRefresh("부대명령", 0);
$db = DB::db(); $db = DB::db();
$me = $db->queryFirstRow('SELECT `no`, name, nation, troop FROM general WHERE `owner`=%i', $userID); $me = $db->queryFirstRow('SELECT `no`, name, nation, troop FROM general WHERE `owner`=%i', $userID);
+8 -2
View File
@@ -13,7 +13,10 @@ $gameStor = KVStorage::getStorage($db, 'game_env');
$autorun_user = $gameStor->autorun_user; $autorun_user = $gameStor->autorun_user;
if($autorun_user['limit_minutes']??false){ if($autorun_user['limit_minutes']??false){
//자동 턴인 경우에는 휴가 불가 //자동 턴인 경우에는 휴가 불가
header('location:b_myPage.php', true, 303); Json::die([
'result'=>false,
'reason'=>'자동 턴인 경우에는 휴가 명령이 불가능합니다.'
]);
} }
$killturn = $gameStor->killturn; $killturn = $gameStor->killturn;
@@ -23,5 +26,8 @@ $db->update('general', [
], 'owner=%i', $userID); ], 'owner=%i', $userID);
header('location:b_myPage.php', true, 303); Json::die([
'result'=>true,
'reason'=>'success'
]);
+1 -1
View File
@@ -169,7 +169,7 @@ if ($genius) {
'dex5'=>0 'dex5'=>0
]); ]);
} else { } else {
$specage2 = Util::valueFit(Util::round((GameConst::$retirementYear - $age)/4 - $relYear / 2), 3) + $age; $specage2 = Util::valueFit(Util::round((GameConst::$retirementYear - $age)/6 - $relYear / 2), 3) + $age;
$special2 = GameConst::$defaultSpecialWar; $special2 = GameConst::$defaultSpecialWar;
} }
//내특 //내특
+184 -164
View File
@@ -1,165 +1,185 @@
var filledChiefList = {}; var filledChiefList = {};
var chiefTableObj = {}; var chiefTableObj = {};
function clearTable(){ function clearTable(){
$('.chiefLevelText').html('-'); $('.chiefLevelText').html('-');
$('.chiefTurnTime, .chiefTurnText, .chiefName').html('&nbsp;'); $('.chiefTurnTime, .chiefTurnText, .chiefName').html('&nbsp;');
} }
function genChiefTableObj(){ function genChiefTableObj(){
var objTable = { var objTable = {
btns: $('#turnPush,#turnPull,#setCommand') btns: $('#turnPush,#turnPull,#setCommand')
}; };
for(var chiefIdx = 5; chiefIdx <= 12; chiefIdx++){ for(var chiefIdx = 5; chiefIdx <= 12; chiefIdx++){
var $plate = $('#chief_{0}'.format(chiefIdx)); var $plate = $('#chief_{0}'.format(chiefIdx));
var $officerLevelText = $plate.find('.chiefLevelText'); var $officerLevelText = $plate.find('.chiefLevelText');
var $name = $plate.find('.chiefName'); var $name = $plate.find('.chiefName');
var turn = []; var turn = [];
for(var turnIdx=0;turnIdx<maxChiefTurn;turnIdx++){ for(var turnIdx=0;turnIdx<maxChiefTurn;turnIdx++){
var $turn = $plate.find('.turn{0}'.format(turnIdx)); var $turn = $plate.find('.turn{0}'.format(turnIdx));
var $turnTime = $turn.find('.chiefTurnTime'); var $turnTime = $turn.find('.chiefTurnTime');
var $turnPad = $turn.find('.chiefTurnPad'); var $turnPad = $turn.find('.chiefTurnPad');
var $turnText = $turn.find('.chiefTurnText'); var $turnText = $turn.find('.chiefTurnText');
turn.push({turnTime:$turnTime,turnPad:$turnPad,turnText:$turnText}); turn.push({turnTime:$turnTime,turnPad:$turnPad,turnText:$turnText});
} }
objTable[chiefIdx] = { objTable[chiefIdx] = {
officerLevelText: $officerLevelText, officerLevelText: $officerLevelText,
name: $name, name: $name,
turn: turn turn: turn
}; };
} }
return objTable; return objTable;
} }
function clearChief(chiefIdx){ function clearChief(chiefIdx){
var $plate = $('#chief_{0}'.format(chiefIdx)); var $plate = $('#chief_{0}'.format(chiefIdx));
$plate.find('.chiefLevelText').html('-'); $plate.find('.chiefLevelText').html('-');
$plate.find('.chiefTurnTime, .chiefTurnText, .chiefName').html('&nbsp;'); $plate.find('.chiefTurnTime, .chiefTurnText, .chiefName').html('&nbsp;');
} }
function reloadTable(){ function reloadTable(){
$.post({ $.post({
url:'j_getChiefTurn.php', url:'j_getChiefTurn.php',
dataType:'json', dataType:'json',
}).then(function(data){ }).then(function(data){
if(!data.result){ if(!data.result){
alert(data.reason); alert(data.reason);
return; return;
} }
var turnTerm = data.turnTerm; var turnTerm = data.turnTerm;
var tmpFilledChiefList = {}; var tmpFilledChiefList = {};
if(data.isChief){ if(data.isChief){
chiefTableObj.btns.css('visibility', 'visible'); chiefTableObj.btns.css('visibility', 'visible');
} }
else{ else{
chiefTableObj.btns.css('visibility', 'hidden'); chiefTableObj.btns.css('visibility', 'hidden');
} }
$.each(data.nationTurnBrief, function(chiefIdx, chiefInfo){ $.each(data.nationTurnBrief, function(chiefIdx, chiefInfo){
tmpFilledChiefList[chiefIdx] = true; tmpFilledChiefList[chiefIdx] = true;
filledChiefList[chiefIdx] = true; filledChiefList[chiefIdx] = true;
var plateObj = chiefTableObj[chiefIdx]; var plateObj = chiefTableObj[chiefIdx];
var $name = $('<span>{0}</span>'.format(chiefInfo.name)); if(chiefInfo.name){
var nameColor = getNpcColor(chiefInfo.npcType); var $name = $('<span>{0}</span>'.format(chiefInfo.name));
if(nameColor){ var nameColor = getNpcColor(chiefInfo.npcType);
$name.css('color',nameColor); if(nameColor){
} $name.css('color',nameColor);
plateObj.officerLevelText.text(chiefInfo.officerLevelText); }
plateObj.name.html($name); plateObj.name.html($name);
}
var turnTimeObj = moment(chiefInfo.turnTime); else{
var turnList = plateObj.turn; plateObj.name.html('');
$.each(chiefInfo.turn, function(turnIdx, turnText){ }
turnList[turnIdx].turnTime.text(turnTimeObj.format('hh:mm'));
turnList[turnIdx].turnText.html(turnText).css('font-size', '13px'); plateObj.officerLevelText.text(chiefInfo.officerLevelText);
var oWidth = turnList[turnIdx].turnPad.innerWidth();
var iWidth = turnList[turnIdx].turnText.outerWidth(); if(chiefInfo.turnTime){
if(iWidth > oWidth * 0.95){ var turnTimeObj = moment(chiefInfo.turnTime);
var newFontSize = 13 * oWidth / iWidth * 0.9; }
turnList[turnIdx].turnText.css('font-size', '{0}px'.format(newFontSize)); else{
} var turnTimeObj = null;
turnTimeObj = turnTimeObj.add(turnTerm, 'minute'); }
}); var turnList = plateObj.turn;
}); $.each(chiefInfo.turn, function(turnIdx, turnText){
if(turnTimeObj){
for(var idx=5;idx<=12;idx++){ turnList[turnIdx].turnTime.text(turnTimeObj.format('HH:mm'));
if(idx in tmpFilledChiefList){ }
continue; else{
} turnList[turnIdx].turnTime.text('');
if(idx in filledChiefList){ }
clearChief(chiefIdx);
} turnList[turnIdx].turnText.html(turnText).css('font-size', '13px');
} var oWidth = turnList[turnIdx].turnPad.innerWidth();
filledChiefList = tmpFilledChiefList; var iWidth = turnList[turnIdx].turnText.outerWidth();
}, errUnknown); if(iWidth > oWidth * 0.95){
} var newFontSize = 13 * oWidth / iWidth * 0.9;
turnList[turnIdx].turnText.css('font-size', '{0}px'.format(newFontSize));
function reserveTurn(turnList, command){ }
console.log(turnList, command); if(turnTimeObj){
$.post({ turnTimeObj = turnTimeObj.add(turnTerm, 'minute');
url:'j_set_chief_command.php', }
dataType:'json',
data:{ });
action:command, });
turnList:turnList
} for(var idx=5;idx<=12;idx++){
}).then(function(data){ if(idx in tmpFilledChiefList){
if(!data.result){ continue;
alert(data.reason); }
} if(idx in filledChiefList){
reloadTable(); clearChief(chiefIdx);
}, errUnknown); }
} }
filledChiefList = tmpFilledChiefList;
function pushTurn(turnCnt){ }, errUnknown);
$.post({ }
url:'j_chief_turn.php',
dataType:'json', function reserveTurn(turnList, command){
data:{ console.log(turnList, command);
amount:turnCnt $.post({
} url:'j_set_chief_command.php',
}).then(function(data){ dataType:'json',
if(!data.result){ data:{
alert(data.reason); action:command,
} turnList:turnList
reloadTable(); }
}, errUnknown); }).then(function(data){
} if(!data.result){
alert(data.reason);
jQuery(function($){ }
reloadTable();
chiefTableObj= genChiefTableObj(); }, errUnknown);
reloadTable(); }
$('#reloadTable').click(reloadTable);
$('#setCommand').click(function(){ function pushTurn(turnCnt){
var turnList = $('#chiefTurnSelector').val().map(function(v){return parseInt(v);}); $.post({
var $command = $('#chiefCommandList option:selected'); url:'j_chief_turn.php',
if($command.data('reqarg')){ dataType:'json',
$.redirect( data:{
"b_processing.php", { amount:turnCnt
command: $command.val(), }
turnList: turnList.join('_'), }).then(function(data){
is_chief: true if(!data.result){
}, "GET"); alert(data.reason);
} }
else{ reloadTable();
reserveTurn(turnList, $command.val()); }, errUnknown);
} }
return false;
}); jQuery(function($){
$('#turnPush').click(function(){ chiefTableObj= genChiefTableObj();
pushTurn(1); reloadTable();
}); $('#reloadTable').click(reloadTable);
$('#setCommand').click(function(){
$('#turnPull').click(function(){ var turnList = $('#chiefTurnSelector').val().map(function(v){return parseInt(v);});
pushTurn(-1); var $command = $('#chiefCommandList option:selected');
}); if($command.data('reqarg')){
$.redirect(
"b_processing.php", {
command: $command.val(),
turnList: turnList.join('_'),
is_chief: true
}, "GET");
}
else{
reserveTurn(turnList, $command.val());
}
return false;
});
$('#turnPush').click(function(){
pushTurn(1);
});
$('#turnPull').click(function(){
pushTurn(-1);
});
}) })
+16 -16
View File
@@ -1,17 +1,17 @@
$(function(){ $(function() {
var $target = $("#destCityID"); var $target = $("#destCityID");
reloadWorldMap({ reloadWorldMap({
isDetailMap:false, isDetailMap: false,
clickableAll:true, clickableAll: true,
neutralView:true, neutralView: true,
useCachedMap:true, useCachedMap: true,
selectCallback:function(city){ selectCallback: function(city) {
var currVal = $target.val(); var currVal = $target.val();
$target.val(city.id); $target.val(city.id).trigger("change");
if($target.val() === null){ if ($target.val() === null) {
$target.val(currVal); $target.val(currVal).trigger("change");
} }
return false; return false;
} }
}); });
}); });
+16 -16
View File
@@ -1,17 +1,17 @@
$(function(){ $(function() {
var $target = $("#destNationID"); var $target = $("#destNationID");
reloadWorldMap({ reloadWorldMap({
isDetailMap:false, isDetailMap: false,
clickableAll:true, clickableAll: true,
neutralView:true, neutralView: true,
useCachedMap:true, useCachedMap: true,
selectCallback:function(city){ selectCallback: function(city) {
var currVal = $target.val(); var currVal = $target.val();
$target.val(city.nationId); $target.val(city.nationId).trigger("change");
if($target.val() === null){ if ($target.val() === null) {
$target.val(currVal); $target.val(currVal).trigger("change");
} }
return false; return false;
} }
}); });
}); });
+898 -898
View File
@@ -1,899 +1,899 @@
$(function() { $(function() {
var cityList = {}; var cityList = {};
var userList = {}; var userList = {};
var cityGroupOrder = ['하북','중원','서북','서촉','남중','초','오월','동이']; var cityGroupOrder = ['하북','중원','서북','서촉','남중','초','오월','동이'];
var city규모 = {:1,:2,:3,:4,:5,:6,:7,:8}; var city규모 = {:1,:2,:3,:4,:5,:6,:7,:8};
window.cityList = cityList; window.cityList = cityList;
window.userList = userList; window.userList = userList;
var basicPath = document.location.pathname; var basicPath = document.location.pathname;
basicPath = basicPath.substring(0, basicPath.lastIndexOf('/'))+'/'; basicPath = basicPath.substring(0, basicPath.lastIndexOf('/'))+'/';
var mergeSort = function(arr,cmpFunc){ var mergeSort = function(arr,cmpFunc){
if(typeof cmpFunc == "undefined"){ if(typeof cmpFunc == "undefined"){
cmpFunc = function(a,b){ cmpFunc = function(a,b){
if(a<b) return -1; if(a<b) return -1;
if(a>b) return 1; if(a>b) return 1;
return 0; return 0;
} }
} }
var merge = function(left,right){ var merge = function(left,right){
var retVal=[]; var retVal=[];
var leftIdx=0; var leftIdx=0;
var rightIdx=0; var rightIdx=0;
while(leftIdx<left.length && rightIdx<right.length){ while(leftIdx<left.length && rightIdx<right.length){
var cmpVal = cmpFunc(left[leftIdx],right[rightIdx]); var cmpVal = cmpFunc(left[leftIdx],right[rightIdx]);
if(cmpVal<=0){ if(cmpVal<=0){
retVal.push(left[leftIdx]); retVal.push(left[leftIdx]);
leftIdx++; leftIdx++;
} }
else{ else{
retVal.push(right[rightIdx]); retVal.push(right[rightIdx]);
rightIdx++; rightIdx++;
} }
} }
retVal = retVal.concat(left.slice(leftIdx)).concat(right.slice(rightIdx)) retVal = retVal.concat(left.slice(leftIdx)).concat(right.slice(rightIdx))
return retVal; return retVal;
}; };
var _mergeSort = function(arr){ var _mergeSort = function(arr){
if(arr.length<2){ if(arr.length<2){
return arr; return arr;
} }
var middle = Math.floor(arr.length/2); var middle = Math.floor(arr.length/2);
var left = arr.slice(0,middle); var left = arr.slice(0,middle);
var right = arr.slice(middle); var right = arr.slice(middle);
return merge(_mergeSort(left),_mergeSort(right)); return merge(_mergeSort(left),_mergeSort(right));
}; };
return _mergeSort(arr); return _mergeSort(arr);
}; };
window.mergeSort = mergeSort; window.mergeSort = mergeSort;
var extDutyWindow = function(userInfo){ var extDutyWindow = function(userInfo){
window.currUser = userInfo; window.currUser = userInfo;
//도시 순서 재구성 //도시 순서 재구성
var subCityGroupList = {}; var subCityGroupList = {};
var subCityList = {}; var subCityList = {};
var tmpOldVal = 0; var tmpOldVal = 0;
//var callCity = function(num){console.log('city no.'+num+' is clicked!')}; //var callCity = function(num){console.log('city no.'+num+' is clicked!')};
if($('#ext_win').length==0){ if($('#ext_win').length==0){
var $win = $('<div id="ext_win" style="padding:0;" title="관직 임명"><table style="padding:0;margin:0;" cellspacing="0" cellpadding="0" border="0"><tr><td width="700px" style="padding:0;"><iframe id="in_frame" src="map.php?type=1&amp;graphic=1" width="700" height="520" frameborder="0" marginwidth="0" marginheight="0" topmargin="0" scrolling="no"></iframe></td>'+ var $win = $('<div id="ext_win" style="padding:0;" title="관직 임명"><table style="padding:0;margin:0;" cellspacing="0" cellpadding="0" border="0"><tr><td width="700px" style="padding:0;"><iframe id="in_frame" src="map.php?type=1&amp;graphic=1" width="700" height="520" frameborder="0" marginwidth="0" marginheight="0" topmargin="0" scrolling="no"></iframe></td>'+
'<td width="305px" style="padding:0;vertical-align:top;height:520px;"><div style="height:520px;width:305px;overflow-y:scroll;overflow-x:hidden;">'+ '<td width="305px" style="padding:0;vertical-align:top;height:520px;"><div style="height:520px;width:305px;overflow-y:scroll;overflow-x:hidden;">'+
'<table id="inner_table"><thead><tr><th width="35">도시</th><th width="85">태수</th><th width="85">군사</th><th width="85">종사</th></tr></thead><tbody class="content">'+ '<table id="inner_table"><thead><tr><th width="35">도시</th><th width="85">태수</th><th width="85">군사</th><th width="85">종사</th></tr></thead><tbody class="content">'+
'</tbody></table></div></td></tr></table>'+ '</tbody></table></div></td></tr></table>'+
'<form name="form1" id="fake_form"><span id="user_name"></span> : <select name="double" id="city_select"></select>'+ '<form name="form1" id="fake_form"><span id="user_name"></span> : <select name="double" id="city_select"></select>'+
'<div id="duty_radio" style="display:inline;">'+ '<div id="duty_radio" style="display:inline;">'+
'<input type="radio" id="duty_type1" value="4" name="duty_radio"><label for="duty_type1">태수</label>'+ '<input type="radio" id="duty_type1" value="4" name="duty_radio"><label for="duty_type1">태수</label>'+
'<input type="radio" id="duty_type2" value="3" name="duty_radio"><label for="duty_type2">군사</label>'+ '<input type="radio" id="duty_type2" value="3" name="duty_radio"><label for="duty_type2">군사</label>'+
'<input type="radio" id="duty_type3" value="2" name="duty_radio"><label for="duty_type3">종사</label>'+ '<input type="radio" id="duty_type3" value="2" name="duty_radio"><label for="duty_type3">종사</label>'+
'</div></form></div>'); '</div></form></div>');
$win.hide(); $win.hide();
$win.css('font-size','9pt'); $win.css('font-size','9pt');
$('#fake_form').css('display','inline'); $('#fake_form').css('display','inline');
$('body').append($win); $('body').append($win);
$('#inner_table').attr('border','1').attr('cellspacing',"0").attr('cellpadding',"0") $('#inner_table').attr('border','1').attr('cellspacing',"0").attr('cellpadding',"0")
.attr('bordercolordark',"gray").attr('bordercolorlight',"black").attr('align','center') .attr('bordercolordark',"gray").attr('bordercolorlight',"black").attr('align','center')
.css('font-size','13px').css('width','290px'); .css('font-size','13px').css('width','290px');
$('#inner_table thead tr'); $('#inner_table thead tr');
$('#fake_form').submit(function(){ $('#fake_form').submit(function(){
return false; return false;
}); });
$('#in_frame').load(function(){ $('#in_frame').load(function(){
$('#in_frame').contents().find('div').click(function(){$('#city_select').change();}); $('#in_frame').contents().find('div').click(function(){$('#city_select').change();});
}); });
$("#duty_radio").buttonset(); $("#duty_radio").buttonset();
var $city_select = $('#city_select'); var $city_select = $('#city_select');
$city_select.css('color','white').css('background-color','black'); $city_select.css('color','white').css('background-color','black');
$city_select.change(function(event){ $city_select.change(function(event){
if($city_select.val()==null){ if($city_select.val()==null){
$city_select.val(tmpOldVal); $city_select.val(tmpOldVal);
return false; return false;
} }
if($city_select.val() == tmpOldVal){ if($city_select.val() == tmpOldVal){
return false; return false;
} }
tmpOldVal = $city_select.val(); tmpOldVal = $city_select.val();
//console.log(tmpOldVal); //console.log(tmpOldVal);
var newInfo = subCityList[tmpOldVal]; var newInfo = subCityList[tmpOldVal];
var cityInfo = newInfo.city; var cityInfo = newInfo.city;
var p태수 = cityInfo.p태수 && currUser.p태수; var p태수 = cityInfo.p태수 && currUser.p태수;
var p군사 = cityInfo.p군사 && currUser.p군사; var p군사 = cityInfo.p군사 && currUser.p군사;
var p종사 = cityInfo.p종사 && currUser.p종사; var p종사 = cityInfo.p종사 && currUser.p종사;
//console.log(p태수,p군사,p종사); //console.log(p태수,p군사,p종사);
$('#duty_type1').button({disabled:!p태수}); $('#duty_type1').button({disabled:!p태수});
$('#duty_type2').button({disabled:!p군사}); $('#duty_type2').button({disabled:!p군사});
$('#duty_type3').button({disabled:!p종사}); $('#duty_type3').button({disabled:!p종사});
var $태수 = cityInfo.$태수; var $태수 = cityInfo.$태수;
var $군사 = cityInfo.$군사; var $군사 = cityInfo.$군사;
var $종사 = cityInfo.$종사; var $종사 = cityInfo.$종사;
return true; return true;
}); });
$win.dialog({ $win.dialog({
autoOpen:false, autoOpen:false,
width:1005, width:1005,
height:680, height:680,
buttons:{ buttons:{
"임명":function(){ "임명":function(){
//console.log("임명!"); //console.log("임명!");
var $checked = $('#duty_radio :radio:checked'); var $checked = $('#duty_radio :radio:checked');
if($checked.length==0 || $checked.attr('disabled')=='disabled'){ if($checked.length==0 || $checked.attr('disabled')=='disabled'){
alert('직책을 선택해주세요!'); alert('직책을 선택해주세요!');
return false; return false;
} }
var type = $checked.attr('value'); var type = $checked.attr('value');
var text = $checked.next().text(); var text = $checked.next().text();
var userVal = currUser.val; var userVal = currUser.val;
var userName = currUser.name; var userName = currUser.name;
var cityVal = $city_select.val(); var cityVal = $city_select.val();
var cityInfo = subCityList[cityVal].city; var cityInfo = subCityList[cityVal].city;
$.post(basicPath+'j_myBossInfo.php',{ $.post(basicPath+'j_myBossInfo.php',{
destCityID:cityVal, destCityID:cityVal,
destGeneralID:userVal, destGeneralID:userVal,
officerLevel:type, officerLevel:type,
action:'임명' action:'임명'
},function(rawData){ },function(rawData){
cityInfo['p'+text]=false; cityInfo['p'+text]=false;
var $target = cityInfo.users.find('.mode_'+type); var $target = cityInfo.users.find('.mode_'+type);
$target.prop('disabled',true); $target.prop('disabled',true);
$target.css('background','transparent'); $target.css('background','transparent');
$target.css('border','0'); $target.css('border','0');
$target.css('color',''); $target.css('color','');
cityInfo['$'+text].html(userName); cityInfo['$'+text].html(userName);
$win.dialog("close"); $win.dialog("close");
}); });
}, },
"닫기":function(){ "닫기":function(){
$win.dialog("close"); $win.dialog("close");
} }
} }
}); });
//console.log($win.parent()); //console.log($win.parent());
$win.parent().css('font-size','10pt'); $win.parent().css('font-size','10pt');
} }
$('#ext_win').dialog("close").dialog( "option", "position", { my: "center top", at: "center bottom", of: userInfo.$user} ); $('#ext_win').dialog("close").dialog( "option", "position", { my: "center top", at: "center bottom", of: userInfo.$user} );
var $innerContent = $('#inner_table .content'); var $innerContent = $('#inner_table .content');
$innerContent.html(''); $innerContent.html('');
$("#user_name").html(userInfo.name+'['+userInfo.city+']'); $("#user_name").html(userInfo.name+'['+userInfo.city+']');
$('#city_select').html(''); $('#city_select').html('');
$.each(cityList,function(idx,cityInfo){ $.each(cityList,function(idx,cityInfo){
var 지역 = cityInfo.지역; var 지역 = cityInfo.지역;
var p태수 = cityInfo.p태수 && currUser.p태수; var p태수 = cityInfo.p태수 && currUser.p태수;
var p군사 = cityInfo.p군사 && currUser.p군사; var p군사 = cityInfo.p군사 && currUser.p군사;
var p종사 = cityInfo.p종사 && currUser.p종사; var p종사 = cityInfo.p종사 && currUser.p종사;
var newInfo = { var newInfo = {
지역 : 지역, 지역 : 지역,
규모 : cityInfo.규모, 규모 : cityInfo.규모,
이름 : cityInfo.이름, 이름 : cityInfo.이름,
val : cityInfo.val, val : cityInfo.val,
city : cityInfo, city : cityInfo,
p태수 : p태수, p태수 : p태수,
p군사 : p군사, p군사 : p군사,
p종사 : p종사 p종사 : p종사
}; };
//console.log(newInfo); //console.log(newInfo);
if(p태수 || p군사 || p종사){ if(p태수 || p군사 || p종사){
if(typeof subCityGroupList[지역] == 'undefined'){ if(typeof subCityGroupList[지역] == 'undefined'){
subCityGroupList[지역] = []; subCityGroupList[지역] = [];
} }
subCityGroupList[지역].push(newInfo); subCityGroupList[지역].push(newInfo);
subCityList[cityInfo.val] = newInfo; subCityList[cityInfo.val] = newInfo;
} }
}); });
$.each(cityGroupOrder,function(idx,groupName){ $.each(cityGroupOrder,function(idx,groupName){
if(typeof subCityGroupList[groupName] == 'undefined'){ if(typeof subCityGroupList[groupName] == 'undefined'){
return true; return true;
} }
var subList = subCityGroupList[groupName]; var subList = subCityGroupList[groupName];
var $group = $('<tr><td colspan="4" style="color:skyblue;">【 '+groupName+' 】</td></tr>'); var $group = $('<tr><td colspan="4" style="color:skyblue;">【 '+groupName+' 】</td></tr>');
$innerContent.append($group); $innerContent.append($group);
subList.sort(function(a,b){ subList.sort(function(a,b){
var cmp규모 = city규모[a.규모] - city규모[b.규모]; var cmp규모 = city규모[a.규모] - city규모[b.규모];
if(cmp규모 != 0) return cmp규모; if(cmp규모 != 0) return cmp규모;
return a.이름.localeCompare(b.이름); return a.이름.localeCompare(b.이름);
}); });
var $optgroup = $('<optgroup label=" 【 '+groupName+' 】 " style="color:skyblue;"></optgroup>'); var $optgroup = $('<optgroup label=" 【 '+groupName+' 】 " style="color:skyblue;"></optgroup>');
$.each(subList,function(idx,newInfo){ $.each(subList,function(idx,newInfo){
$optgroup.append('<option value="'+newInfo.val+'" style="color:white;">'+newInfo.이름+'</option>'); $optgroup.append('<option value="'+newInfo.val+'" style="color:white;">'+newInfo.이름+'</option>');
var cityInfo = newInfo.city; var cityInfo = newInfo.city;
var $city = $('<tr><td>'+newInfo.이름+'</td></tr>'); var $city = $('<tr><td>'+newInfo.이름+'</td></tr>');
var $태수 = cityInfo.$태수.clone(); var $태수 = cityInfo.$태수.clone();
$city.append($태수); $city.append($태수);
if(!newInfo.p태수){ if(!newInfo.p태수){
$태수.css('color','red'); $태수.css('color','red');
} }
else{ else{
$태수.click(function(){ $태수.click(function(){
$('#duty_radio :radio:eq(0)').attr('checked','checked'); $('#duty_radio :radio:eq(0)').attr('checked','checked');
$('#duty_radio :radio').button('refresh'); $('#duty_radio :radio').button('refresh');
}).css('cursor','pointer'); }).css('cursor','pointer');
} }
var $군사 = cityInfo.$군사.clone(); var $군사 = cityInfo.$군사.clone();
$city.append($군사); $city.append($군사);
if(!newInfo.p군사)$군사.css('color','red'); if(!newInfo.p군사)$군사.css('color','red');
else{ else{
$군사.click(function(){ $군사.click(function(){
$('#duty_radio :radio:eq(1)').attr('checked','checked'); $('#duty_radio :radio:eq(1)').attr('checked','checked');
$('#duty_radio :radio').button('refresh'); $('#duty_radio :radio').button('refresh');
}).css('cursor','pointer'); }).css('cursor','pointer');
} }
var $종사 = cityInfo.$종사.clone(); var $종사 = cityInfo.$종사.clone();
$city.append($종사); $city.append($종사);
if(!newInfo.p종사)$종사.css('color','red'); if(!newInfo.p종사)$종사.css('color','red');
else{ else{
$종사.click(function(){ $종사.click(function(){
$('#duty_radio :radio:eq(2)').attr('checked','checked'); $('#duty_radio :radio:eq(2)').attr('checked','checked');
$('#duty_radio :radio').button('refresh'); $('#duty_radio :radio').button('refresh');
}).css('cursor','pointer'); }).css('cursor','pointer');
} }
$innerContent.append($city); $innerContent.append($city);
$city.click(function(){ $city.click(function(){
$('#city_select').val(newInfo.val).change(); $('#city_select').val(newInfo.val).change();
}); });
}); });
$('#city_select').append($optgroup); $('#city_select').append($optgroup);
}); });
tmpOldVal = $('#city_select').val(); tmpOldVal = $('#city_select').val();
$('#city_select').change(); $('#city_select').change();
$('#ext_win').dialog("open"); $('#ext_win').dialog("open");
}; };
var loadDuty = function(){ var loadDuty = function(){
try{ try{
$('.for_duty').remove(); $('.for_duty').remove();
$.get(basicPath+'b_myBossInfo.php',function(rawData){ $.get(basicPath+'b_myBossInfo.php',function(rawData){
$html = $(rawData); $html = $(rawData);
//window.$html = $html; //window.$html = $html;
var cnt =0; var cnt =0;
var $tmpTable = $html.filter('#officer_list').eq(0); var $tmpTable = $html.filter('#officer_list').eq(0);
$selects = $tmpTable.find("select"); $selects = $tmpTable.find("select");
if($selects.length == 0){ if($selects.length == 0){
alert("수뇌가 아닙니다!"); alert("수뇌가 아닙니다!");
return false; return false;
} }
var setUserAvailable = function($userList,typeName){ var setUserAvailable = function($userList,typeName){
$userList.each(function(idx){ $userList.each(function(idx){
var $this = $(this); var $this = $(this);
var val = $this.val(); var val = $this.val();
var name = $.trim($this.text()); var name = $.trim($this.text());
for(var i=name.length-1;i>0;i--){ for(var i=name.length-1;i>0;i--){
if(name[i]=='【'){ if(name[i]=='【'){
name = $.trim(name.substr(0,i)); name = $.trim(name.substr(0,i));
break; break;
} }
} }
if(val == '0'){ if(val == '0'){
return true; return true;
} }
if(typeof userList[name] != 'undefined'){ if(typeof userList[name] != 'undefined'){
userList[name].val = val; userList[name].val = val;
userList[name][typeName] = true; userList[name][typeName] = true;
} }
}); });
}; };
var setCityAvailiable = function($cityList,typeName){ var setCityAvailiable = function($cityList,typeName){
$cityList.each(function(idx){ $cityList.each(function(idx){
var $this = $(this); var $this = $(this);
var val = $.trim($this.val()); var val = $.trim($this.val());
var name = $.trim($this.text()); var name = $.trim($this.text());
cityList[name].val = val; cityList[name].val = val;
cityList[name][typeName] = true; cityList[name][typeName] = true;
}); });
} }
$.each(cityList,function(idx,cityInfo){ $.each(cityList,function(idx,cityInfo){
cityInfo.p태수=false; cityInfo.p태수=false;
cityInfo.p군사=false; cityInfo.p군사=false;
cityInfo.p종사=false; cityInfo.p종사=false;
}); });
$.each(userList,function(idx,userInfo){ $.each(userList,function(idx,userInfo){
userInfo.p태수=false; userInfo.p태수=false;
userInfo.p군사=false; userInfo.p군사=false;
userInfo.p종사=false; userInfo.p종사=false;
}); });
setUserAvailable($selects.eq(1).find("option"),"p태수"); setUserAvailable($selects.eq(1).find("option"),"p태수");
setUserAvailable($selects.eq(3).find("option"),"p군사"); setUserAvailable($selects.eq(3).find("option"),"p군사");
setUserAvailable($selects.eq(5).find("option"),"p종사"); setUserAvailable($selects.eq(5).find("option"),"p종사");
setCityAvailiable($selects.eq(0).find("option"),"p태수"); setCityAvailiable($selects.eq(0).find("option"),"p태수");
setCityAvailiable($selects.eq(2).find("option"),"p군사"); setCityAvailiable($selects.eq(2).find("option"),"p군사");
setCityAvailiable($selects.eq(4).find("option"),"p종사"); setCityAvailiable($selects.eq(4).find("option"),"p종사");
$.each(cityList,function(idx,cityInfo){ $.each(cityList,function(idx,cityInfo){
//console.log(cityInfo.users.children()); //console.log(cityInfo.users.children());
cityInfo.users.children().each(function(idx){ cityInfo.users.children().each(function(idx){
//console.log(this); //console.log(this);
var $this = $(this); var $this = $(this);
var username = $this.data('username'); var username = $this.data('username');
var userInfo = userList[username]; var userInfo = userList[username];
if(!userInfo){ if(!userInfo){
return true; return true;
} }
if(userInfo.val == '-1'){ if(userInfo.val == '-1'){
return true; return true;
} }
$name = $this.find('.nameplate'); $name = $this.find('.nameplate');
$name.append('<br class="for_duty">'); $name.append('<br class="for_duty">');
var addBtn=function($name,cityInfo,userInfo,type,text,warn){ var addBtn=function($name,cityInfo,userInfo,type,text,warn){
var enabled = cityInfo['p'+text]&&userInfo['p'+text]; var enabled = cityInfo['p'+text]&&userInfo['p'+text];
var cityVal = cityInfo.val; var cityVal = cityInfo.val;
var $btn = $('<button type="button">'+text.substr(0,1)+'</button>'); var $btn = $('<button type="button">'+text.substr(0,1)+'</button>');
$btn.addClass('mode_'+type); $btn.addClass('mode_'+type);
$btn.addClass('for_duty'); $btn.addClass('for_duty');
if(!enabled){ if(!enabled){
$btn.prop('disabled',true); $btn.prop('disabled',true);
$btn.css('background','transparent'); $btn.css('background','transparent');
$btn.css('border','0'); $btn.css('border','0');
} }
else{ else{
if(userInfo.is수뇌){ if(userInfo.is수뇌){
$btn.css('color','red'); $btn.css('color','red');
} }
} }
$btn.css('padding','1px 4px'); $btn.css('padding','1px 4px');
$btn.css('margin','0'); $btn.css('margin','0');
$btn.click(function(){ $btn.click(function(){
if(userInfo.is수뇌){ if(userInfo.is수뇌){
if(!confirm('수뇌입니다. 임명할까요?')){ if(!confirm('수뇌입니다. 임명할까요?')){
return false; return false;
} }
} }
$.post(basicPath+'j_myBossInfo.php',{ $.post(basicPath+'j_myBossInfo.php',{
destCityID:cityVal, destCityID:cityVal,
destGeneralID:userInfo.val, destGeneralID:userInfo.val,
officerLevel:type, officerLevel:type,
action:'임명' action:'임명'
},function(rawData){ },function(rawData){
cityInfo['p'+text]=false; cityInfo['p'+text]=false;
var $target = cityInfo.users.find('.mode_'+type); var $target = cityInfo.users.find('.mode_'+type);
$target.prop('disabled',true); $target.prop('disabled',true);
$target.css('background','transparent'); $target.css('background','transparent');
$target.css('border','0'); $target.css('border','0');
$target.css('color',''); $target.css('color','');
cityInfo['$'+text].html(userInfo.name); cityInfo['$'+text].html(userInfo.name);
}); });
}); });
//console.log($btn); //console.log($btn);
$name.append($btn); $name.append($btn);
}; };
addBtn($name,cityInfo,userInfo,4,'태수'); addBtn($name,cityInfo,userInfo,4,'태수');
addBtn($name,cityInfo,userInfo,3,'군사'); addBtn($name,cityInfo,userInfo,3,'군사');
addBtn($name,cityInfo,userInfo,2,'종사'); addBtn($name,cityInfo,userInfo,2,'종사');
//특수 버튼! //특수 버튼!
if(userInfo.p태수||userInfo.p군사||userInfo.p종사){ if(userInfo.p태수||userInfo.p군사||userInfo.p종사){
var $btn = $('<button type="button">...</button>'); var $btn = $('<button type="button">...</button>');
$btn.addClass('for_duty'); $btn.addClass('for_duty');
if(userInfo.is수뇌){ if(userInfo.is수뇌){
$btn.css('color','red'); $btn.css('color','red');
} }
$btn.css('padding','1px 4px'); $btn.css('padding','1px 4px');
$btn.css('margin','0'); $btn.css('margin','0');
$btn.click(function(){ $btn.click(function(){
if(userInfo.is수뇌){ if(userInfo.is수뇌){
if(!confirm('수뇌입니다. 임명할까요?')){ if(!confirm('수뇌입니다. 임명할까요?')){
return false; return false;
} }
} }
extDutyWindow(userInfo); extDutyWindow(userInfo);
}); });
$btn.css('border','solid 1px Chocolate').css('background-color','#400000').css('margin-left','4px'); $btn.css('border','solid 1px Chocolate').css('background-color','#400000').css('margin-left','4px');
$btn.css('line-hight','20px').css('color','GhostWhite').css('padding','2px 2px').css('height','18px').css('line-height','8px'); $btn.css('line-hight','20px').css('color','GhostWhite').css('padding','2px 2px').css('height','18px').css('line-height','8px');
//$name.append($btn); //$name.append($btn);
} }
}); });
}); });
}); });
} }
catch(a){ catch(a){
console.log(a); console.log(a);
} }
return false; return false;
}; };
var loadUser = function(){ var loadUser = function(){
$.each(cityList,function(idx,val){ $.each(cityList,function(idx,val){
if(typeof val.users == "undefined"){ if(typeof val.users == "undefined"){
val.obj.append('<tr><td colspan="12"><table align="center" class="tb_layout cityUser bg0">'+ val.obj.append('<tr><td colspan="12"><table align="center" class="tb_layout cityUser bg0">'+
'<thead><tr>'+ '<thead><tr>'+
'<td width="100" align="center" class="bg1">이 름</td><td width="100" align="center" class="bg1">통무지</td><td width="100" align="center" class="bg1">부 대</td><td width="60" align="center" class="bg1">자 금</td>'+ '<td width="100" align="center" class="bg1">이 름</td><td width="100" align="center" class="bg1">통무지</td><td width="100" align="center" class="bg1">부 대</td><td width="60" align="center" class="bg1">자 금</td>'+
'<td width="60" align="center" class="bg1">군 량</td><td width="30" align="center" class="bg1">守</td><td width="60" align="center" class="bg1">병 종</td>'+ '<td width="60" align="center" class="bg1">군 량</td><td width="30" align="center" class="bg1">守</td><td width="60" align="center" class="bg1">병 종</td>'+
'<td width="60" align="center" class="bg1">병 사</td><td width="50" align="center" class="bg1">훈련</td><td width="50" align="center" class="bg1">사기</td><td width="150" align="center" class="bg1">명 령</td>'+ '<td width="60" align="center" class="bg1">병 사</td><td width="50" align="center" class="bg1">훈련</td><td width="50" align="center" class="bg1">사기</td><td width="150" align="center" class="bg1">명 령</td>'+
'<td width="60" align="center" class="bg1">삭턴</td><td width="60" align="center" class="bg1">턴</td>'+ '<td width="60" align="center" class="bg1">삭턴</td><td width="60" align="center" class="bg1">턴</td>'+
'</tr></thead>'+ '</tr></thead>'+
'<tbody class="cityUserBody"></tbody></table></td></tr>'); '<tbody class="cityUserBody"></tbody></table></td></tr>');
val.users = val.obj.find(".cityUserBody"); val.users = val.obj.find(".cityUserBody");
} }
else{ else{
val.users.html(""); val.users.html("");
} }
}); });
$.get(basicPath+'b_genList.php',function(rawData){ $.get(basicPath+'b_genList.php',function(rawData){
var cnt =0; var cnt =0;
var $helper = $('#helper_genlist'); var $helper = $('#helper_genlist');
$helper.html('').append($.parseHTML(rawData)); $helper.html('').append($.parseHTML(rawData));
var tmpUsers = $('#general_list tbody tr'); var tmpUsers = $('#general_list tbody tr');
tmpUsers.each(function(idx){ tmpUsers.each(function(idx){
var $this = $(this); var $this = $(this);
var $city = $this.children('.i_city'); var $city = $this.children('.i_city');
$city.remove(); $city.remove();
var cityName = $.trim($city.text()); var cityName = $.trim($city.text());
var $name = $this.children('.i_name'); var $name = $this.children('.i_name');
$name.addClass('nameplate'); $name.addClass('nameplate');
var name = $name.find('.t_name').text(); var name = $name.find('.t_name').text();
var $work = $this.children('.i_action'); var $work = $this.children('.i_action');
var cityInfo = cityList[cityName]; var cityInfo = cityList[cityName];
if(typeof cityInfo == 'undefined'){ if(typeof cityInfo == 'undefined'){
return true; return true;
} }
if(cityInfo.warn주민)$work.html($work.html().split('정착 장려').join('<span style="color:yellow;">정착 장려</span>')); if(cityInfo.warn주민)$work.html($work.html().split('정착 장려').join('<span style="color:yellow;">정착 장려</span>'));
if(cityInfo.warn농업)$work.html($work.html().split('농지 개간').join('<span style="color:yellow;">농지 개간</span>')); if(cityInfo.warn농업)$work.html($work.html().split('농지 개간').join('<span style="color:yellow;">농지 개간</span>'));
if(cityInfo.warn상업)$work.html($work.html().split('상업 투자').join('<span style="color:yellow;">상업 투자</span>')); if(cityInfo.warn상업)$work.html($work.html().split('상업 투자').join('<span style="color:yellow;">상업 투자</span>'));
if(cityInfo.warn치안)$work.html($work.html().split('치안 강화').join('<span style="color:yellow;">치안 강화</span>')); if(cityInfo.warn치안)$work.html($work.html().split('치안 강화').join('<span style="color:yellow;">치안 강화</span>'));
if(cityInfo.warn수비)$work.html($work.html().split('수비 강화').join('<span style="color:yellow;">수비 강화</span>')); if(cityInfo.warn수비)$work.html($work.html().split('수비 강화').join('<span style="color:yellow;">수비 강화</span>'));
if(cityInfo.warn성벽)$work.html($work.html().split('성벽 보수').join('<span style="color:yellow;">성벽 보수</span>')); if(cityInfo.warn성벽)$work.html($work.html().split('성벽 보수').join('<span style="color:yellow;">성벽 보수</span>'));
var $stat = $this.children('.i_stat'); var $stat = $this.children('.i_stat');
var stat = $stat.text(); var stat = $stat.text();
var is수뇌 = stat.indexOf('+')>=0; var is수뇌 = stat.indexOf('+')>=0;
$this.data('username',name); $this.data('username',name);
if(cityList[cityName].$태수.text() == name){ if(cityList[cityName].$태수.text() == name){
cityList[cityName].$태수.css('color','lightgreen'); cityList[cityName].$태수.html('<span style="color:lightgreen">{0}</span>'.format(name));
} }
if(cityList[cityName].$군사.text() == name){ if(cityList[cityName].$군사.text() == name){
cityList[cityName].$군사.css('color','lightgreen'); cityList[cityName].$군사.html('<span style="color:lightgreen">{0}</span>'.format(name));
} }
if(cityList[cityName].$종사.text() == name){ if(cityList[cityName].$종사.text() == name){
cityList[cityName].$종사.css('color','lightgreen'); cityList[cityName].$종사.html('<span style="color:lightgreen">{0}</span>'.format(name));
} }
userList[name]={ userList[name]={
$city:cityInfo, $city:cityInfo,
city:cityName, city:cityName,
$user:$this, $user:$this,
name:name, name:name,
val:'-1', val:'-1',
p태수:false, p태수:false,
p군사:false, p군사:false,
p종사:false, p종사:false,
is수뇌:is수뇌 is수뇌:is수뇌
}; };
if(cityList[cityName]){ if(cityList[cityName]){
cityList[cityName].users.append($this); cityList[cityName].users.append($this);
} }
}); });
}); });
if($("#loadDutyBtn").length == 0){ if($("#loadDutyBtn").length == 0){
var $onBossList = $('<button id="loadDutyBtn">인사부 연동</button>'); var $onBossList = $('<button id="loadDutyBtn">인사부 연동</button>');
$onBossList.click(function(){ $onBossList.click(function(){
loadDuty(); loadDuty();
return false; return false;
}); });
$('form').append($onBossList); $('form').append($onBossList);
} }
$('#by_users').show(); $('#by_users').show();
}; };
var mainFunc = function(){ var mainFunc = function(){
//대상 추출 //대상 추출
window.cityList = {}; window.cityList = {};
window.userList = {}; window.userList = {};
$("form").each(function(){ $("form").each(function(){
var $this = $(this); var $this = $(this);
$this.attr('name','p'+$this.attr('name')); $this.attr('name','p'+$this.attr('name'));
}); });
$("table").each(function(idx,val){ $("table").each(function(idx,val){
$this = $(this); $this = $(this);
if($this.attr('class')=='tb_layout bg2'){ if($this.attr('class')=='tb_layout bg2'){
$this.addClass('cityInfo'); $this.addClass('cityInfo');
} }
else{ else{
return true; return true;
} }
window.$tmpTable = $this; window.$tmpTable = $this;
var cityInfo = {}; var cityInfo = {};
//이름 추출 //이름 추출
{ {
var titleText = $this.find('tr:eq(0)>td:eq(0)').text(); var titleText = $this.find('tr:eq(0)>td:eq(0)').text();
var loc0 = titleText.indexOf("【"); var loc0 = titleText.indexOf("【");
var loc1 = titleText.indexOf("|"); var loc1 = titleText.indexOf("|");
var loc2 = titleText.indexOf("】"); var loc2 = titleText.indexOf("】");
var cityLoc = $.trim(titleText.substring(loc0+1,loc1)); var cityLoc = $.trim(titleText.substring(loc0+1,loc1));
var citySize = $.trim(titleText.substring(loc1+1,loc2)); var citySize = $.trim(titleText.substring(loc1+1,loc2));
var cityName = $.trim(titleText.substring(loc2+1)); var cityName = $.trim(titleText.substring(loc2+1));
cityName = cityName.replace("[",""); cityName = cityName.replace("[","");
cityName = cityName.replace("]",""); cityName = cityName.replace("]","");
$this.data('cityname',cityName); $this.data('cityname',cityName);
cityInfo.지역 = cityLoc; cityInfo.지역 = cityLoc;
cityInfo.규모 = citySize; cityInfo.규모 = citySize;
cityInfo.이름 = cityName; cityInfo.이름 = cityName;
cityInfo.val = '-1'; cityInfo.val = '-1';
cityInfo.p태수 = false; cityInfo.p태수 = false;
cityInfo.p군사 = false; cityInfo.p군사 = false;
cityInfo.p종사 = false; cityInfo.p종사 = false;
} }
//주민, 농상치성수 //주민, 농상치성수
{ {
var $baseTr = $this.find('tr:eq(1)'); var $baseTr = $this.find('tr:eq(1)');
cityInfo.$주민 = $baseTr.find('td:eq(1)'); cityInfo.$주민 = $baseTr.find('td:eq(1)');
cityInfo.$농업 = $baseTr.find('td:eq(3)'); cityInfo.$농업 = $baseTr.find('td:eq(3)');
cityInfo.$상업 = $baseTr.find('td:eq(5)'); cityInfo.$상업 = $baseTr.find('td:eq(5)');
cityInfo.$치안 = $baseTr.find('td:eq(7)'); cityInfo.$치안 = $baseTr.find('td:eq(7)');
cityInfo.$수비 = $baseTr.find('td:eq(9)'); cityInfo.$수비 = $baseTr.find('td:eq(9)');
cityInfo.$성벽 = $baseTr.find('td:eq(11)'); cityInfo.$성벽 = $baseTr.find('td:eq(11)');
var tmpVal; var tmpVal;
tmpVal = cityInfo.$주민.text().split('/'); tmpVal = cityInfo.$주민.text().split('/');
cityInfo.주민 = parseInt(tmpVal[0]); cityInfo.주민 = parseInt(tmpVal[0]);
cityInfo.max주민 = parseInt(tmpVal[1]); cityInfo.max주민 = parseInt(tmpVal[1]);
tmpVal = cityInfo.$농업.text().split('/'); tmpVal = cityInfo.$농업.text().split('/');
cityInfo.농업 = parseInt(tmpVal[0]); cityInfo.농업 = parseInt(tmpVal[0]);
cityInfo.max농업 = parseInt(tmpVal[1]); cityInfo.max농업 = parseInt(tmpVal[1]);
tmpVal = cityInfo.$상업.text().split('/'); tmpVal = cityInfo.$상업.text().split('/');
cityInfo.상업 = parseInt(tmpVal[0]); cityInfo.상업 = parseInt(tmpVal[0]);
cityInfo.max상업 = parseInt(tmpVal[1]); cityInfo.max상업 = parseInt(tmpVal[1]);
tmpVal = cityInfo.$치안.text().split('/'); tmpVal = cityInfo.$치안.text().split('/');
cityInfo.치안 = parseInt(tmpVal[0]); cityInfo.치안 = parseInt(tmpVal[0]);
cityInfo.max치안 = parseInt(tmpVal[1]); cityInfo.max치안 = parseInt(tmpVal[1]);
tmpVal = cityInfo.$수비.text().split('/'); tmpVal = cityInfo.$수비.text().split('/');
cityInfo.수비 = parseInt(tmpVal[0]); cityInfo.수비 = parseInt(tmpVal[0]);
cityInfo.max수비 = parseInt(tmpVal[1]); cityInfo.max수비 = parseInt(tmpVal[1]);
tmpVal = cityInfo.$성벽.text().split('/'); tmpVal = cityInfo.$성벽.text().split('/');
cityInfo.성벽 = parseInt(tmpVal[0]); cityInfo.성벽 = parseInt(tmpVal[0]);
cityInfo.max성벽 = parseInt(tmpVal[1]); cityInfo.max성벽 = parseInt(tmpVal[1]);
if (cityInfo.주민>cityInfo.max주민*0.9){ cityInfo.$주민.css('color','lightgreen');} if (cityInfo.주민>cityInfo.max주민*0.9){ cityInfo.$주민.css('color','lightgreen');}
else if (cityInfo.주민>cityInfo.max주민*0.7){ cityInfo.$주민.css('color','yellow');} else if (cityInfo.주민>cityInfo.max주민*0.7){ cityInfo.$주민.css('color','yellow');}
else { cityInfo.$주민.css('color','orangered');} else { cityInfo.$주민.css('color','orangered');}
if (cityInfo.농업>cityInfo.max농업*0.8){ cityInfo.$농업.css('color','lightgreen');} if (cityInfo.농업>cityInfo.max농업*0.8){ cityInfo.$농업.css('color','lightgreen');}
else if (cityInfo.농업>cityInfo.max농업*0.4){ cityInfo.$농업.css('color','yellow');} else if (cityInfo.농업>cityInfo.max농업*0.4){ cityInfo.$농업.css('color','yellow');}
else { cityInfo.$농업.css('color','orangered');} else { cityInfo.$농업.css('color','orangered');}
if (cityInfo.상업>cityInfo.max상업*0.8){ cityInfo.$상업.css('color','lightgreen');} if (cityInfo.상업>cityInfo.max상업*0.8){ cityInfo.$상업.css('color','lightgreen');}
else if (cityInfo.상업>cityInfo.max상업*0.4){ cityInfo.$상업.css('color','yellow');} else if (cityInfo.상업>cityInfo.max상업*0.4){ cityInfo.$상업.css('color','yellow');}
else { cityInfo.$상업.css('color','orangered');} else { cityInfo.$상업.css('color','orangered');}
if (cityInfo.치안>cityInfo.max치안*0.8){ cityInfo.$치안.css('color','lightgreen');} if (cityInfo.치안>cityInfo.max치안*0.8){ cityInfo.$치안.css('color','lightgreen');}
else if (cityInfo.치안>cityInfo.max치안*0.4){ cityInfo.$치안.css('color','yellow');} else if (cityInfo.치안>cityInfo.max치안*0.4){ cityInfo.$치안.css('color','yellow');}
else { cityInfo.$치안.css('color','orangered');} else { cityInfo.$치안.css('color','orangered');}
if (cityInfo.수비>cityInfo.max수비*0.6){ cityInfo.$수비.css('color','lightgreen');} if (cityInfo.수비>cityInfo.max수비*0.6){ cityInfo.$수비.css('color','lightgreen');}
else if (cityInfo.수비>cityInfo.max수비*0.3){ cityInfo.$수비.css('color','yellow');} else if (cityInfo.수비>cityInfo.max수비*0.3){ cityInfo.$수비.css('color','yellow');}
else { cityInfo.$수비.css('color','orangered');} else { cityInfo.$수비.css('color','orangered');}
if (cityInfo.성벽>cityInfo.max성벽*0.6){ cityInfo.$성벽.css('color','lightgreen');} if (cityInfo.성벽>cityInfo.max성벽*0.6){ cityInfo.$성벽.css('color','lightgreen');}
else if (cityInfo.성벽>cityInfo.max성벽*0.3){ cityInfo.$성벽.css('color','yellow');} else if (cityInfo.성벽>cityInfo.max성벽*0.3){ cityInfo.$성벽.css('color','yellow');}
else { cityInfo.$성벽.css('color','orangered');} else { cityInfo.$성벽.css('color','orangered');}
cityInfo.remain주민 = cityInfo.주민-cityInfo.max주민; cityInfo.remain주민 = cityInfo.주민-cityInfo.max주민;
cityInfo.remain농업 = cityInfo.농업-cityInfo.max농업; cityInfo.remain농업 = cityInfo.농업-cityInfo.max농업;
cityInfo.remain상업 = cityInfo.상업-cityInfo.max상업; cityInfo.remain상업 = cityInfo.상업-cityInfo.max상업;
cityInfo.remain치안 = cityInfo.치안-cityInfo.max치안; cityInfo.remain치안 = cityInfo.치안-cityInfo.max치안;
cityInfo.remain수비 = cityInfo.수비-cityInfo.max수비; cityInfo.remain수비 = cityInfo.수비-cityInfo.max수비;
cityInfo.remain성벽 = cityInfo.성벽-cityInfo.max성벽; cityInfo.remain성벽 = cityInfo.성벽-cityInfo.max성벽;
cityInfo.warn주민 = false; cityInfo.warn주민 = false;
cityInfo.warn농업 = false; cityInfo.warn농업 = false;
cityInfo.warn상업 = false; cityInfo.warn상업 = false;
cityInfo.warn치안 = false; cityInfo.warn치안 = false;
cityInfo.warn수비 = false; cityInfo.warn수비 = false;
cityInfo.warn성벽 = false; cityInfo.warn성벽 = false;
if(cityInfo.remain주민 > -10*2000) cityInfo.warn주민 = true; if(cityInfo.remain주민 > -10*2000) cityInfo.warn주민 = true;
if(cityInfo.주민 > 0.92*cityInfo.max주민) cityInfo.warn주민 = true; if(cityInfo.주민 > 0.92*cityInfo.max주민) cityInfo.warn주민 = true;
if(cityInfo.remain농업 > -10*100) cityInfo.warn농업 = true; if(cityInfo.remain농업 > -10*100) cityInfo.warn농업 = true;
if(cityInfo.remain상업 > -10*100) cityInfo.warn상업 = true; if(cityInfo.remain상업 > -10*100) cityInfo.warn상업 = true;
if(cityInfo.remain치안 > -10*100) cityInfo.warn치안 = true; if(cityInfo.remain치안 > -10*100) cityInfo.warn치안 = true;
if(cityInfo.remain수비 > -10*70) cityInfo.warn수비 = true; if(cityInfo.remain수비 > -10*70) cityInfo.warn수비 = true;
if(cityInfo.remain성벽 > -10*70) cityInfo.warn성벽 = true; if(cityInfo.remain성벽 > -10*70) cityInfo.warn성벽 = true;
if(cityInfo.warn농업) cityInfo.$농업.append('<span class="remain" style="color:yellow;">['+cityInfo.remain농업+']</span>'); if(cityInfo.warn농업) cityInfo.$농업.append('<span class="remain" style="color:yellow;">['+cityInfo.remain농업+']</span>');
if(cityInfo.warn상업) cityInfo.$상업.append('<span class="remain" style="color:yellow;">['+cityInfo.remain상업+']</span>'); if(cityInfo.warn상업) cityInfo.$상업.append('<span class="remain" style="color:yellow;">['+cityInfo.remain상업+']</span>');
if(cityInfo.warn치안) cityInfo.$치안.append('<span class="remain" style="color:yellow;">['+cityInfo.remain치안+']</span>'); if(cityInfo.warn치안) cityInfo.$치안.append('<span class="remain" style="color:yellow;">['+cityInfo.remain치안+']</span>');
if(cityInfo.warn수비) cityInfo.$수비.append('<span class="remain" style="color:yellow;">['+cityInfo.remain수비+']</span>'); if(cityInfo.warn수비) cityInfo.$수비.append('<span class="remain" style="color:yellow;">['+cityInfo.remain수비+']</span>');
if(cityInfo.warn성벽) cityInfo.$성벽.append('<span class="remain" style="color:yellow;">['+cityInfo.remain성벽+']</span>'); if(cityInfo.warn성벽) cityInfo.$성벽.append('<span class="remain" style="color:yellow;">['+cityInfo.remain성벽+']</span>');
} }
//태수,군사,종사 //태수,군사,종사
{ {
var $baseTr = $this.find('tr:eq(2)'); var $baseTr = $this.find('tr:eq(2)');
cityInfo.$태수 = $baseTr.find('td:eq(7)'); cityInfo.$태수 = $baseTr.find('td:eq(7)');
cityInfo.$군사 = $baseTr.find('td:eq(9)'); cityInfo.$군사 = $baseTr.find('td:eq(9)');
cityInfo.$종사 = $baseTr.find('td:eq(11)'); cityInfo.$종사 = $baseTr.find('td:eq(11)');
} }
//기타 //기타
{ {
cityInfo.userCnt = $this.find('tr:eq(3) td:eq(1)').text().split(',').length -1; cityInfo.userCnt = $this.find('tr:eq(3) td:eq(1)').text().split(',').length -1;
} }
cityInfo.obj = $this; cityInfo.obj = $this;
cityList[cityInfo.이름] = cityInfo; cityList[cityInfo.이름] = cityInfo;
}); });
var $onGenList = $('<button type="button">암행부 연동</button>'); var $onGenList = $('<button type="button">암행부 연동</button>');
$onGenList.click(function(){ $onGenList.click(function(){
loadUser(); loadUser();
return false; return false;
}); });
$('form').append($onGenList); $('form').append($onGenList);
$('table:eq(0) tr:last').after('<tr><td id="sort_more"></td></tr>'); $('table:eq(0) tr:last').after('<tr><td id="sort_more"></td></tr>');
$sort_more = $('#sort_more'); $sort_more = $('#sort_more');
$sort_more.html('재 정렬 순서 :'); $sort_more.html('재 정렬 순서 :');
var sortIt = function(callback){ var sortIt = function(callback){
var arCity = []; var arCity = [];
$('.cityInfo').each(function(){ $('.cityInfo').each(function(){
var $this = $(this); var $this = $(this);
var cityName = $this.data('cityname'); var cityName = $this.data('cityname');
var cityInfo = cityList[cityName]; var cityInfo = cityList[cityName];
arCity.push(cityInfo); arCity.push(cityInfo);
}); });
arCity = mergeSort(arCity,callback); arCity = mergeSort(arCity,callback);
//console.log(arCity); //console.log(arCity);
var $anchor = $('.anchor'); var $anchor = $('.anchor');
//console.log($anchor); //console.log($anchor);
$('body > br').remove(); $('body > br').remove();
$('.cityInfo').detach(); $('.cityInfo').detach();
$.each(arCity,function(idx,val){ $.each(arCity,function(idx,val){
$anchor.before('<br>'); $anchor.before('<br>');
$anchor.before(val.obj); $anchor.before(val.obj);
}); });
$anchor.before('<br>'); $anchor.before('<br>');
}; };
var $btn; var $btn;
$btn = $('<button type="button">도시명</button>').click(function(){ $btn = $('<button type="button">도시명</button>').click(function(){
sortIt(function(a,b){ sortIt(function(a,b){
return a.이름.localeCompare(b.이름); return a.이름.localeCompare(b.이름);
}); });
}); });
$sort_more.append($btn); $sort_more.append($btn);
$btn = $('<button type="button">인구율</button>').click(function(){ $btn = $('<button type="button">인구율</button>').click(function(){
sortIt(function(a,b){ sortIt(function(a,b){
return 1.0*a.주민/a.max주민 - 1.0*b.주민/b.max주민; return 1.0*a.주민/a.max주민 - 1.0*b.주민/b.max주민;
}); });
}); });
$sort_more.append($btn); $sort_more.append($btn);
$btn = $('<button type="button">남은 주민</button>').click(function(){ $btn = $('<button type="button">남은 주민</button>').click(function(){
sortIt(function(a,b){ sortIt(function(a,b){
return a.remain주민 - b.remain주민; return a.remain주민 - b.remain주민;
}); });
}); });
$sort_more.append($btn); $sort_more.append($btn);
$btn = $('<button type="button">남은 농업</button>').click(function(){ $btn = $('<button type="button">남은 농업</button>').click(function(){
sortIt(function(a,b){ sortIt(function(a,b){
return a.remain농업 - b.remain농업; return a.remain농업 - b.remain농업;
}); });
}); });
$sort_more.append($btn); $sort_more.append($btn);
$btn = $('<button type="button">남은 상업</button>').click(function(){ $btn = $('<button type="button">남은 상업</button>').click(function(){
sortIt(function(a,b){ sortIt(function(a,b){
return a.remain상업 - b.remain상업; return a.remain상업 - b.remain상업;
}); });
}); });
$sort_more.append($btn); $sort_more.append($btn);
$btn = $('<button type="button">남은 치안</button>').click(function(){ $btn = $('<button type="button">남은 치안</button>').click(function(){
sortIt(function(a,b){ sortIt(function(a,b){
return a.remain치안 - b.remain치안; return a.remain치안 - b.remain치안;
}); });
}); });
$sort_more.append($btn); $sort_more.append($btn);
$btn = $('<button type="button">남은 수비</button>').click(function(){ $btn = $('<button type="button">남은 수비</button>').click(function(){
sortIt(function(a,b){ sortIt(function(a,b){
return a.remain수비 - b.remain수비; return a.remain수비 - b.remain수비;
}); });
}); });
$sort_more.append($btn); $sort_more.append($btn);
$btn = $('<button type="button">남은 성벽</button>').click(function(){ $btn = $('<button type="button">남은 성벽</button>').click(function(){
sortIt(function(a,b){ sortIt(function(a,b){
return a.remain성벽 - b.remain성벽; return a.remain성벽 - b.remain성벽;
}); });
}); });
$sort_more.append($btn); $sort_more.append($btn);
$btn = $('<button type="button">배치 장수 수</button>').click(function(){ $btn = $('<button type="button">배치 장수 수</button>').click(function(){
sortIt(function(a,b){ sortIt(function(a,b){
return b.userCnt - a.userCnt; return b.userCnt - a.userCnt;
}); });
}); });
$sort_more.append($btn); $sort_more.append($btn);
}; };
mainFunc(); mainFunc();
}); });
+81
View File
@@ -82,4 +82,85 @@ jQuery(function($){
}) })
initCustomCSSForm(); initCustomCSSForm();
$('#die_immediately').click(function(){
if(!confirm('정말로 삭제하시겠습니까?')){
return false;
}
$.post({
url:'j_die_immediately.php',
dataType:'json',
}).then(function(data){
if(!data){
return quickReject('실패했습니다.');
}
if(!data.result){
return quickReject(data.reason);
}
location.replace('..');
}, errUnknown)
.fail(function(reason){
alert(reason);
location.reload();
});
return false;
return false;
});
$('#vacation').click(function(){
if(!confirm('휴가 기능을 신청할까요?')){
return false;
}
$.post({
url:'j_vacation.php',
dataType:'json',
}).then(function(data){
if(!data){
return quickReject('실패했습니다.');
}
if(!data.result){
return quickReject(data.reason);
}
location.reload();
}, errUnknown)
.fail(function(reason){
alert(reason);
location.reload();
});
return false;
return false;
});
$('#set_my_setting').click(function(){
$.post({
url:'j_set_my_setting.php',
dataType:'json',
data:{
tnmt:$('.tnmt:checked').val(),
defence_train:$('#defence_train').val(),
use_treatment:$('#use_treatment').val(),
}
}).then(function(data){
if(!data){
return quickReject('실패했습니다.');
}
if(!data.result){
return quickReject(data.reason);
}
location.reload();
}, errUnknown)
.fail(function(reason){
alert(reason);
location.reload();
});
return false;
return false;
});
}); });
+40 -3
View File
@@ -33,6 +33,35 @@ jQuery(function ($) {
var $disabled = $(itemFrameDisabled.format('&lt;비활성화 항목들&gt;')).addClass('filtered'); var $disabled = $(itemFrameDisabled.format('&lt;비활성화 항목들&gt;')).addClass('filtered');
$disabledList.append($disabled); $disabledList.append($disabled);
var lastInfoObj = null;
var lastInfoData = null;
var onChoose = function(evt){
//$(evt.item).find('.help-message').popopver('disable');
if(lastInfoObj){
lastInfoObj.popover('hide');
}
}
var onUnchoose = function(evt){
var $item = $(evt.item);//.find('.help-message').popopver('enable');
var $helpMessage = $item.find('.help-message');
if(!$helpMessage.length){
return;
}
if(lastInfoData != $item.data('value')){
$helpMessage.popover('show')
lastInfoData = $item.data('value');
lastInfoObj = $helpMessage;
}
else{
$helpMessage.popover('hide');
lastInfoData = null;
lastInfoObj = null;
}
}
$.each(availablePriority, function (key, val) { $.each(availablePriority, function (key, val) {
if (val in usedKey) { if (val in usedKey) {
return true; return true;
@@ -45,12 +74,16 @@ jQuery(function ($) {
$disabledList.sortable({ $disabledList.sortable({
group: priorityKey, group: priorityKey,
filter: '.filtered', filter: '.filtered',
onChoose,onChoose,
onUnchoose:onUnchoose,
animation: 150 animation: 150
}); });
$enabledList.sortable({ $enabledList.sortable({
group: priorityKey, group: priorityKey,
filter: '.filtered', filter: '.filtered',
onChoose,onChoose,
onUnchoose:onUnchoose,
animation: 150 animation: 150
}); });
@@ -59,14 +92,18 @@ jQuery(function ($) {
if(!(itemValue in btnHelpMessage)){ if(!(itemValue in btnHelpMessage)){
return true; return true;
} }
var helpText = btnHelpMessage[itemValue]; var helpText = btnHelpMessage[itemValue];
$item.find('.help-message').popover({ var $helpMessage = $item.find('.help-message');
$helpMessage.popover({
content:helpText, content:helpText,
placement:'right', placement:'top',
html:true, html:true,
trigger:'hover' trigger:'hover'
}); });
$item.mouseleave(function(){
$helpMessage.popover('hide');
});
}); });
} }
+242 -101
View File
@@ -1,102 +1,243 @@
function reserveTurn(turnList, command, arg){ function reserveTurn(turnList, command, arg) {
var target; var target;
if(isChiefTurn){ if (isChiefTurn) {
target = 'j_set_chief_command.php'; target = 'j_set_chief_command.php';
} } else {
else{ target = 'j_set_general_command.php';
target = 'j_set_general_command.php'; }
} $.post({
$.post({ url: target,
url:target, dataType: 'json',
dataType:'json', data: {
data:{ action: command,
action:command, turnList: turnList,
turnList:turnList, arg: JSON.stringify(arg)
arg:JSON.stringify(arg) }
} }).then(function(data) {
}).then(function(data){ if (!data.result) {
if(!data.result){ alert(data.reason);
alert(data.reason); return;
return; }
}
if (!isChiefTurn) {
if(!isChiefTurn){ window.location.href = './';
window.location.href = './'; } else {
} window.location.href = 'b_chiefcenter.php';
else{ }
window.location.href = 'b_chiefcenter.php';
} }, errUnknown);
}
}, errUnknown);
} jQuery(function($) {
jQuery(function($){ window.submitAction = function() {
window.submitAction = function(){ //checkCommandArg 참고
var availableArgumentList = {
//checkCommandArg 참고 'string': [
var availableArgumentList = { 'nationName', 'optionText', 'itemType', 'nationType', 'itemCode',
'string':[ ],
'nationName', 'optionText', 'itemType', 'nationType', 'itemCode', 'int': [
], 'crewType', 'destGeneralID', 'destCityID', 'destNationID',
'int':[ 'amount', 'colorType',
'crewType', 'destGeneralID', 'destCityID', 'destNationID', 'year', 'month',
'amount', 'colorType', 'srcArmType', 'destArmType', //숙련전환 전용
'year', 'month', ],
'srcArmType', 'destArmType', //숙련전환 전용 'boolean': [
], 'isGold', 'buyRice',
'boolean':[ ],
'isGold', 'buyRice', 'integerArray': [
], 'destNationIDList', 'destGeneralIDList', 'amountList'
'integerArray':[ ]
'destNationIDList', 'destGeneralIDList', 'amountList' }
]
} var handlerList = {
'string': function($obj) {
var handlerList = { return $.trim($obj.eq(0).val());
'string':function($obj){ },
return $.trim($obj.eq(0).val()); 'int': function($obj) {
}, return parseInt($obj.eq(0).val());
'int':function($obj){ },
return parseInt($obj.eq(0).val()); 'boolean': function($obj) {
}, switch ($obj.eq(0).val().toLowerCase()) {
'boolean':function($obj){ case "true":
switch ($obj.eq(0).val().toLowerCase()) { case "yes":
case "true": case "yes": case "1": case "1":
return true; return true;
case "false": case "no": case "0": case "false":
return false; case "no":
default: case "0":
throw new Error ("Boolean.parse: Cannot convert string to boolean."); return false;
} default:
}, throw new Error("Boolean.parse: Cannot convert string to boolean.");
'integerArray':function($obj){ }
return $obj.map(function(){ },
return parseInt($(this).val()); 'integerArray': function($obj) {
}); return $obj.map(function() {
} return parseInt($(this).val());
} });
}
var argument = {}; }
for (var typeName in availableArgumentList) {
availableArgumentList[typeName].forEach(function(argName){ var argument = {};
var $obj = $('#'+argName); for (var typeName in availableArgumentList) {
if($obj.length == 0){ availableArgumentList[typeName].forEach(function(argName) {
$obj = $('.'+argName); var $obj = $('#' + argName);
if($obj.length == 0){ if ($obj.length == 0) {
return; $obj = $('.' + argName);
} if ($obj.length == 0) {
} return;
}
argument[argName] = handlerList[typeName]($obj); }
});
} argument[argName] = handlerList[typeName]($obj);
});
console.log(argument); }
reserveTurn(turnList, command, argument);
}; console.log(argument);
reserveTurn(turnList, command, argument);
$('#commonSubmit').click(submitAction); };
$('#commonSubmit').click(submitAction);
var $colorType = $('#colorType');
if ($colorType.length) {
$colorType.select2({
theme: 'bootstrap4',
placeholder: "색상을 선택해 주세요.",
language: "ko",
containerCss: {
display: "inline-block !important",
color: 'white !important',
},
templateSelection: function(item) {
if (item.disabled) {
return item.text;
}
var bgcolor = item.element.dataset.color;
var fgcolor = item.element.dataset.fontColor;
return $("<span><span style='background-color:{0};color:{1};'> </span>&nbsp;{2}</span>".format(
bgcolor, fgcolor, item.text
));
},
templateResult: function(item) {
if (item.disabled) {
return item.text;
}
var bgcolor = item.element.dataset.color;
var fgcolor = item.element.dataset.fontColor;
return $("<div style='padding: 0.75rem 0.375rem; background-color:{0};color:{1};'>{2}</div>".format(
bgcolor, fgcolor, item.text
));
},
containerCssClass: 'simple-select2-align-center bg-secondary text-secondary',
dropdownCssClass: 'no-padding simple-select2-align-center bg-secondary text-secondary',
});
}
var $nationType = $('#nationType');
if ($nationType.length) {
$nationType.select2({
theme: 'bootstrap4',
language: "ko",
containerCss: {
display: "inline-block !important",
color: 'white !important',
},
containerCssClass: 'simple-select2-align-center bg-secondary text-secondary',
dropdownCssClass: 'simple-select2-align-center bg-secondary text-secondary',
});
}
var $destCityID = $('#destCityID');
if ($destCityID.length) {
$destCityID.select2({
theme: 'bootstrap4',
placeholder: "도시를 선택해 주세요.",
language: "ko",
containerCss: {
display: "inline-block !important",
color: 'white !important',
},
containerCssClass: 'simple-select2-align-center bg-secondary text-secondary',
dropdownCssClass: 'simple-select2-align-center bg-secondary text-secondary',
});
}
var $destNationID = $('#destNationID');
if ($destNationID.length) {
$destNationID.select2({
theme: 'bootstrap4',
placeholder: "국가를 선택해 주세요.",
language: "ko",
containerCss: {
display: "inline-block !important",
color: 'white !important',
},
containerCssClass: 'simple-select2-align-center bg-secondary text-secondary',
dropdownCssClass: 'simple-select2-align-center bg-secondary text-secondary',
});
}
var $destGeneralID = $('#destGeneralID');
if ($destGeneralID.length) {
$destGeneralID.select2({
theme: 'bootstrap4',
placeholder: "장수를 선택해 주세요.",
language: "ko",
containerCss: {
display: "inline-block !important",
color: 'white !important',
},
containerCssClass: 'simple-select2-align-center bg-secondary text-secondary',
dropdownCssClass: 'simple-select2-align-center bg-secondary text-secondary',
});
}
var $isGold = $('#isGold');
if ($isGold.length) {
$isGold.select2({
theme: 'bootstrap4',
placeholder: "분량을 지정해 주세요.",
language: "ko",
containerCss: {
display: "inline-block !important",
color: 'white !important',
},
minimumResultsForSearch: -1,
containerCssClass: 'simple-select2-align-center bg-secondary text-secondary',
dropdownCssClass: 'simple-select2-align-center bg-secondary text-secondary',
});
}
var $amount = $('#amount:not([type=hidden])');
if ($amount.length) {
$amount.select2({
theme: 'bootstrap4',
placeholder: "분량을 지정해 주세요.",
allowClear: false,
language: "ko",
containerCss: {
display: "inline-block !important",
color: 'white !important',
},
tags: true,
sorter: function(items) {
items.sort(function(lhs, rhs) {
return parseInt(lhs.id) - parseInt(rhs.id);
})
return items;
},
containerCssClass: 'simple-select2-align-center bg-secondary text-secondary',
dropdownCssClass: 'select2-only-number simple-select2-align-center bg-secondary text-secondary',
})
}
$(document).on('keypress', '.select2-only-number .select2-search__field', function() {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
}); });
+1 -1
View File
@@ -23,7 +23,7 @@ $(function(){
var crewtype = parseInt($parent.data('crewtype')); var crewtype = parseInt($parent.data('crewtype'));
calc(crewtype); calc(crewtype);
$formCrewtype.val(crewtype); $formCrewtype.val(crewtype);
$formAmount.val($this.val()); $formAmount.val($this.val()*100);
if(e.which === 13){ if(e.which === 13){
submitAction(); submitAction();
+7 -3
View File
@@ -558,13 +558,17 @@ function ConquerCity(array $admin, General $general, array $city) {
} }
} }
//NPC인 경우 10% 확률로 임관(엔장, 인재, 의병) //NPC인 경우 일정 확률로 임관(엔장, 인재, 의병)
$npcType = $oldGeneral->getNPCType(); $npcType = $oldGeneral->getNPCType();
if($admin['join_mode'] != 'onlyRandom' && 2 <= $npcType && $npcType <= 8 && $npcType != 5 && Util::randBool(0.1)) { if($admin['join_mode'] != 'onlyRandom' && 2 <= $npcType && $npcType <= 8 && $npcType != 5 && Util::randBool(GameConst::$joinRuinedNPCProp)) {
$cmd = buildGeneralCommandClass('che_임관', $oldGeneral, $admin, [ $cmd = buildGeneralCommandClass('che_임관', $oldGeneral, $admin, [
'destNationID'=>$attackerNationID 'destNationID'=>$attackerNationID
]); ]);
_setGeneralCommand($cmd, [0]); $joinTurn = Util::randRangeInt(0, 12);
if($joinTurn){
_setGeneralCommand(buildGeneralCommandClass('che_견문', $oldGeneral, $admin), iterator_to_array(Util::range($joinTurn)));
}
_setGeneralCommand($cmd, [$joinTurn]);
} }
} }
+4
View File
@@ -0,0 +1,4 @@
<?php
require('../vendor/autoload.php');
//ParsedownExtra;
+1 -1
View File
@@ -18,7 +18,7 @@ class che_치료_환약 extends \sammo\BaseItem{
public function getPreTurnExecuteTriggerList(General $general):?GeneralTriggerCaller{ public function getPreTurnExecuteTriggerList(General $general):?GeneralTriggerCaller{
return new GeneralTriggerCaller( return new GeneralTriggerCaller(
new GeneralTrigger\che_아이템치료($general) new GeneralTrigger\che_아이템치료($general, $general->getAuxVar('use_treatment')??10)
); );
} }
@@ -0,0 +1,29 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\WarUnit;
use sammo\WarUnitTriggerCaller;
use sammo\WarUnitTrigger\che_격노시도;
use sammo\WarUnitTrigger\che_격노발동;
class event_전투특기_격노 extends \sammo\BaseItem{
protected $id = 74;
protected $rawName = '비급';
protected $name = '비급(격노)';
protected $info = '[전투] 상대방 필살 및 회피 시도시 일정 확률로 격노(필살) 발동, 공격 시 일정 확률로 진노(1페이즈 추가)';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function getBattlePhaseSkillTriggerList(WarUnit $unit):?WarUnitTriggerCaller{
return new WarUnitTriggerCaller(
new che_격노시도($unit),
new che_격노발동($unit)
);
}
}
@@ -0,0 +1,35 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\GameUnitConst;
use \sammo\WarUnit;
use \sammo\WarUnitCity;
class event_전투특기_공성 extends \sammo\BaseItem{
protected $id = 53;
protected $rawName = '비급';
protected $name = '비급(공성)';
protected $info = '[군사] 차병 계통 징·모병비 -10%<br>[전투] 성벽 공격 시 대미지 +100%';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function onCalcDomestic(string $turnType, string $varType, float $value, $aux=null):float{
if(in_array($turnType, ['징병', '모병'])){
if($varType == 'cost' && $aux['armType'] == GameUnitConst::T_SIEGE) return $value * 0.9;
}
return $value;
}
public function getWarPowerMultiplier(WarUnit $unit):array{
if($unit->getOppose() instanceof WarUnitCity){
return [2, 1];
}
return [1, 1];
}
}
@@ -0,0 +1,34 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\GameUnitConst;
class event_전투특기_궁병 extends \sammo\BaseItem{
protected $id = 51;
protected $rawName = '비급';
protected $name = '비급(궁병)';
protected $info = '[군사] 궁병 계통 징·모병비 -10%<br>[전투] 회피 확률 +20%p';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function onCalcDomestic(string $turnType, string $varType, float $value, $aux=null):float{
if(in_array($turnType, ['징병', '모병'])){
if($varType == 'cost' && $aux['armType'] == GameUnitConst::T_ARCHER) return $value * 0.9;
}
return $value;
}
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if($statName === 'warAvoidRatio'){
return $value + 0.2;
}
return $value;
}
}
@@ -0,0 +1,34 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\GameUnitConst;
use \sammo\WarUnit;
class event_전투특기_귀병 extends \sammo\BaseItem{
protected $id = 40;
protected $rawName = '비급';
protected $name = '비급(귀병)';
protected $info = '[군사] 귀병 계통 징·모병비 -10%<br>[전투] 계략 성공 확률 +20%p';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function onCalcDomestic(string $turnType, string $varType, float $value, $aux=null):float{
if(in_array($turnType, ['징병', '모병'])){
if($varType == 'cost' && $aux['armType'] == GameUnitConst::T_WIZARD) return $value * 0.9;
}
return $value;
}
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if($statName === 'warMagicSuccessProb'){
return $value + 0.2;
}
return $value;
}
}
@@ -0,0 +1,34 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\GameUnitConst;
use \sammo\WarUnit;
class event_전투특기_기병 extends \sammo\BaseItem{
protected $id = 52;
protected $rawName = '비급';
protected $name = '비급(기병)';
protected $info = '[군사] 기병 계통 징·모병비 -10%<br>[전투] 수비 시 대미지 +10%, 공격 시 대미지 +20%';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function onCalcDomestic(string $turnType, string $varType, float $value, $aux=null):float{
if(in_array($turnType, ['징병', '모병'])){
if($varType == 'cost' && $aux['armType'] == GameUnitConst::T_CAVALRY) return $value * 0.9;
}
return $value;
}
public function getWarPowerMultiplier(WarUnit $unit):array{
if($unit->isAttacker()){
return [1.2, 1];
}
return [1.1, 1];
}
}
@@ -0,0 +1,41 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\WarUnit;
use \sammo\BaseWarUnitTrigger;
use \sammo\WarUnitTriggerCaller;
use sammo\WarUnitTrigger\WarActivateSkills;
class event_전투특기_돌격 extends \sammo\BaseItem{
protected $id = 60;
protected $rawName = '비급';
protected $name = '비급(돌격)';
protected $info = '[전투] 상대 회피 불가, 공격 시 전투 페이즈 +1, 공격 시 대미지 +10%';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if($statName === 'initWarPhase'){
return $value + 1;
}
return $value;
}
public function getWarPowerMultiplier(WarUnit $unit):array{
if($unit->isAttacker()){
return [1.1, 1];
}
return [1, 1];
}
public function getBattlePhaseSkillTriggerList(WarUnit $unit):?WarUnitTriggerCaller{
return new WarUnitTriggerCaller(
(new WarActivateSkills($unit, BaseWarUnitTrigger::TYPE_NONE, false, '회피불가'))->setPriority(BaseWarUnitTrigger::PRIORITY_BEGIN + 200)
);
}
}
@@ -0,0 +1,29 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\WarUnit;
class event_전투특기_무쌍 extends \sammo\BaseItem{
protected $id = 61;
protected $rawName = '비급';
protected $name = '비급(무쌍)';
protected $info = '[전투] 대미지 +10%, 공격 시 필살 확률 +10%p';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if($statName === 'warCriticalRatio' && $aux['isAttacker']??false){
return $value += 0.1;
}
return $value;
}
public function getWarPowerMultiplier(WarUnit $unit):array{
return [1.1, 1];
}
}
@@ -0,0 +1,38 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\WarUnit;
use sammo\WarUnitTriggerCaller;
use \sammo\BaseWarUnitTrigger;
use \sammo\WarUnitTrigger\WarActivateSkills;
use \sammo\WarUnitTrigger\che_반계시도;
use \sammo\WarUnitTrigger\che_반계발동;
class event_전투특기_반계 extends \sammo\BaseItem{
protected $id = 45;
protected $rawName = '비급';
protected $name = '비급(반계)';
protected $info = '[전투] 상대의 계략 성공 확률 -10%p, 상대의 계략을 40% 확률로 되돌림, 반목 성공시 대미지 추가(+60% → +100%)';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if($statName === 'warMagicSuccessDamage' && $aux === '반목'){
return $value + 0.4;
}
return $value;
}
public function getBattlePhaseSkillTriggerList(WarUnit $unit):?WarUnitTriggerCaller{
return new WarUnitTriggerCaller(
new WarActivateSkills($unit, BaseWarUnitTrigger::TYPE_ITEM, false, '계략약화'),
new che_반계시도($unit, che_반계시도::TYPE_ITEM),
new che_반계발동($unit)
);
}
}
@@ -0,0 +1,35 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\GameUnitConst;
use \sammo\WarUnit;
class event_전투특기_보병 extends \sammo\BaseItem{
protected $id = 50;
protected $rawName = '비급';
protected $name = '비급(보병)';
protected $info = '[군사] 보병 계통 징·모병비 -10%<br>[전투] 공격 시 아군 피해 -10%, 수비 시 아군 피해 -20%';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function onCalcDomestic(string $turnType, string $varType, float $value, $aux=null):float{
if(in_array($turnType, ['징병', '모병'])){
if($varType == 'cost' && $aux['armType'] == GameUnitConst::T_FOOTMAN) return $value * 0.9;
}
return $value;
}
public function getWarPowerMultiplier(WarUnit $unit):array{
if($unit->isAttacker()){
return [1, 0.9];
}
return [1, 0.8];
}
}
@@ -0,0 +1,36 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\WarUnit;
class event_전투특기_신산 extends \sammo\BaseItem{
protected $id = 41;
protected $rawName = '비급';
protected $name = '비급(신산)';
protected $info = '[계략] 화계·탈취·파괴·선동 : 성공률 +10%p<br>[전투] 계략 시도 확률 +20%p, 계략 성공 확률 +20%p';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function onCalcDomestic(string $turnType, string $varType, float $value, $aux=null):float{
if($turnType == '계략'){
if($varType == 'success') return $value + 0.1;
}
return $value;
}
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if($statName === 'warMagicTrialProb'){
return $value + 0.2;
}
if($statName === 'warMagicSuccessProb'){
return $value + 0.2;
}
return $value;
}
}
@@ -0,0 +1,25 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\WarUnit;
class event_전투특기_신중 extends \sammo\BaseItem{
protected $id = 44;
protected $rawName = '비급';
protected $name = '비급(신중)';
protected $info = '[전투] 계략 성공 확률 100%';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if($statName === 'warMagicSuccessProb'){
return $value + 1;
}
return $value;
}
}
@@ -0,0 +1,31 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\WarUnit;
use sammo\WarUnitTriggerCaller;
use \sammo\WarUnitTrigger\che_위압시도;
use \sammo\WarUnitTrigger\che_위압발동;
class event_전투특기_위압 extends \sammo\BaseItem{
protected $id = 63;
protected $rawName = '비급';
protected $name = '비급(위압)';
protected $info = '[전투] 훈련/사기≥90, 병력≥1,000 일 때 첫 페이즈 위압 발동(적 공격 불가)';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function getBattlePhaseSkillTriggerList(WarUnit $unit):?WarUnitTriggerCaller{
if($unit->getPhase() != 0){
return null;
}
return new WarUnitTriggerCaller(
new che_위압시도($unit),
new che_위압발동($unit)
);
}
}
@@ -0,0 +1,38 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use sammo\BaseGeneralTrigger;
use sammo\SpecialityHelper;
use \sammo\General;
use \sammo\GeneralTrigger;
use \sammo\GeneralTriggerCaller;
use \sammo\WarUnit;
use sammo\WarUnitTrigger\che_전투치료발동;
use sammo\WarUnitTrigger\che_전투치료시도;
use sammo\WarUnitTriggerCaller;
class event_전투특기_의술 extends \sammo\BaseItem{
protected $id = 73;
protected $rawName = '비급';
protected $name = '비급(의술)';
protected $info = '[군사] 매 턴마다 자신(100%)과 소속 도시 장수(적 포함 50%) 부상 회복<br>[전투] 페이즈마다 20% 확률로 치료 발동(아군 피해 1/3 감소)';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function getPreTurnExecuteTriggerList(General $general):?GeneralTriggerCaller{
return new GeneralTriggerCaller(
new GeneralTrigger\che_도시치료($general)
);
}
public function getBattlePhaseSkillTriggerList(\sammo\WarUnit $unit): ?WarUnitTriggerCaller
{
return new WarUnitTriggerCaller(
new che_전투치료시도($unit, che_전투치료시도::TYPE_ITEM),
new che_전투치료발동($unit)
);
}
}
@@ -0,0 +1,28 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\WarUnit;
use sammo\WarUnitTriggerCaller;
use \sammo\WarUnitTrigger\che_저격시도;
use \sammo\WarUnitTrigger\che_저격발동;
class event_전투특기_저격 extends \sammo\BaseItem{
protected $id = 70;
protected $rawName = '비급';
protected $name = '비급(저격)';
protected $info = '[전투] 새로운 상대와 전투 시 1/3 확률로 저격 발동, 성공 시 사기+10';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function getBattlePhaseSkillTriggerList(WarUnit $unit):?WarUnitTriggerCaller{
return new WarUnitTriggerCaller(
new che_저격시도($unit, che_저격시도::TYPE_ITEM, 1/3, 20, 60),
new che_저격발동($unit, che_저격발동::TYPE_ITEM)
);
}
}
@@ -0,0 +1,25 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\WarUnit;
class event_전투특기_집중 extends \sammo\BaseItem{
protected $id = 43;
protected $rawName = '비급';
protected $name = '비급(집중)';
protected $info = '[전투] 계략 성공 시 대미지 +50%';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if($statName === 'warMagicSuccessDamage'){
return $value * 1.5;
}
return $value;
}
}
@@ -0,0 +1,33 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\WarUnit;
class event_전투특기_징병 extends \sammo\BaseItem{
protected $id = 72;
protected $rawName = '비급';
protected $name = '비급(징병)';
protected $info = '[군사] 징·모병비 -50%, 통솔 순수 능력치 보정 +15%';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function onCalcDomestic(string $turnType, string $varType, float $value, $aux=null):float{
if(in_array($turnType, ['징병', '모병'])){
if($varType == 'cost') return $value * 0.5;
}
return $value;
}
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if($statName === 'leadership'){
return $value *= 1.15;
}
return $value;
}
}
@@ -0,0 +1,26 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\WarUnit;
class event_전투특기_척사 extends \sammo\BaseItem{
protected $id = 75;
protected $rawName = '비급';
protected $name = '비급(척사)';
protected $info = '[전투] 지역·도시 병종 상대로 대미지 +10%, 아군 피해 -10%';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function getWarPowerMultiplier(WarUnit $unit):array{
$opposeCrewType = $unit->getOppose()->getCrewType();
if($opposeCrewType->reqCities || $opposeCrewType->reqRegions){
return [1.1, 0.9];
}
return [1, 1];
}
}
@@ -0,0 +1,33 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\WarUnit;
use sammo\WarUnitTriggerCaller;
use sammo\WarUnitTrigger\che_필살강화_회피불가;
class event_전투특기_필살 extends \sammo\BaseItem{
protected $id = 71;
protected $rawName = '비급';
protected $name = '비급(필살)';
protected $info = '[전투] 필살 확률 +20%p, 필살 발동시 대상 회피 불가';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if($statName === 'warCriticalRatio'){
return $value + 0.2;
}
return $value;
}
public function getBattlePhaseSkillTriggerList(WarUnit $unit):?WarUnitTriggerCaller{
return new WarUnitTriggerCaller(
new che_필살강화_회피불가($unit)
);
}
}
@@ -0,0 +1,28 @@
<?php
namespace sammo\ActionItem;
use \sammo\iAction;
use \sammo\General;
use \sammo\SpecialityHelper;
use \sammo\WarUnit;
class event_전투특기_환술 extends \sammo\BaseItem{
protected $id = 42;
protected $rawName = '비급';
protected $name = '비급(환술)';
protected $info = '[전투] 계략 성공 확률 +10%p, 계략 성공 시 대미지 +30%';
protected $cost = 100;
protected $buyable = true;
protected $consumable = false;
protected $reqSecu = 3000;
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if($statName === 'warMagicSuccessProb'){
return $value + 0.1;
}
if($statName === 'warMagicSuccessDamage'){
return $value * 1.3;
}
return $value;
}
}
+4 -4
View File
@@ -29,12 +29,12 @@ class che_덕가 extends \sammo\BaseNation{
return $value; return $value;
} }
public function onCalcNationalIncome(string $type, int $amount):int{ public function onCalcNationalIncome(string $type, $amount){
if($type == 'rice'){ if($type == 'rice'){
return Util::toInt($amount * 0.9); return $amount * 0.9;
} }
if($type == 'pop'){ if($type == 'pop' && $amount > 0){
return Util::toInt($amount * 1.2); return $amount * 1.2;
} }
return $amount; return $amount;
+3 -3
View File
@@ -24,9 +24,9 @@ class che_도가 extends \sammo\BaseNation{
return $value; return $value;
} }
public function onCalcNationalIncome(string $type, int $amount):int{ public function onCalcNationalIncome(string $type, $amount){
if($type == 'pop'){ if($type == 'pop' && $amount > 0){
return Util::toInt($amount * 1.2); return $amount * 1.2;
} }
return $amount; return $amount;
+2 -2
View File
@@ -28,9 +28,9 @@ class che_도적 extends \sammo\BaseNation{
return $value; return $value;
} }
public function onCalcNationalIncome(string $type, int $amount):int{ public function onCalcNationalIncome(string $type, $amount){
if($type == 'gold'){ if($type == 'gold'){
return Util::toInt($amount * 0.9); return $amount * 0.9;
} }
return $amount; return $amount;
+4 -4
View File
@@ -25,12 +25,12 @@ class che_명가 extends \sammo\BaseNation{
return $value; return $value;
} }
public function onCalcNationalIncome(string $type, int $amount):int{ public function onCalcNationalIncome(string $type, $amount){
if($type == 'rice'){ if($type == 'rice'){
return Util::toInt($amount * 0.9); return $amount * 0.9;
} }
if($type == 'pop'){ if($type == 'pop' && $amount > 0){
return Util::toInt($amount * 1.2); return $amount * 1.2;
} }
return $amount; return $amount;
+4 -4
View File
@@ -25,12 +25,12 @@ class che_법가 extends \sammo\BaseNation{
return $value; return $value;
} }
public function onCalcNationalIncome(string $type, int $amount):int{ public function onCalcNationalIncome(string $type, $amount){
if($type == 'gold'){ if($type == 'gold'){
return Util::toInt($amount * 1.1); return $amount * 1.1;
} }
if($type == 'pop'){ if($type == 'pop' && $amount > 0){
return Util::toInt($amount * 0.8); return $amount * 0.8;
} }
return $amount; return $amount;
+3 -3
View File
@@ -29,9 +29,9 @@ class che_병가 extends \sammo\BaseNation{
return $value; return $value;
} }
public function onCalcNationalIncome(string $type, int $amount):int{ public function onCalcNationalIncome(string $type, $amount):int{
if($type == 'pop'){ if($type == 'pop' && $amount > 0){
return Util::toInt($amount * 0.8); return $amount * 0.8;
} }
return $amount; return $amount;
+2 -2
View File
@@ -24,9 +24,9 @@ class che_불가 extends \sammo\BaseNation{
return $value; return $value;
} }
public function onCalcNationalIncome(string $type, int $amount):int{ public function onCalcNationalIncome(string $type, $amount){
if($type == 'gold'){ if($type == 'gold'){
return Util::toInt($amount * 0.9); return $amount * 0.9;
} }
return $amount; return $amount;
@@ -29,12 +29,12 @@ class che_오두미도 extends \sammo\BaseNation{
return $value; return $value;
} }
public function onCalcNationalIncome(string $type, int $amount):int{ public function onCalcNationalIncome(string $type, $amount){
if($type == 'rice'){ if($type == 'rice'){
return Util::toInt($amount * 1.1); return $amount * 1.1;
} }
if($type == 'pop'){ if($type == 'pop' && $amount > 0){
return Util::toInt($amount * 1.2); return $amount * 1.2;
} }
return $amount; return $amount;
+2 -2
View File
@@ -24,9 +24,9 @@ class che_유가 extends \sammo\BaseNation{
return $value; return $value;
} }
public function onCalcNationalIncome(string $type, int $amount):int{ public function onCalcNationalIncome(string $type, $amount){
if($type == 'rice'){ if($type == 'rice'){
return Util::toInt($amount * 0.9); return $amount * 0.9;
} }
return $amount; return $amount;
+3 -3
View File
@@ -25,9 +25,9 @@ class che_음양가 extends \sammo\BaseNation{
return $value; return $value;
} }
public function onCalcNationalIncome(string $type, int $amount):int{ public function onCalcNationalIncome(string $type, $amount){
if($type == 'pop'){ if($type == 'pop' && $amount > 0){
return Util::toInt($amount * 1.2); return $amount * 1.2;
} }
return $amount; return $amount;
+2 -2
View File
@@ -25,9 +25,9 @@ class che_종횡가 extends \sammo\BaseNation{
return $value; return $value;
} }
public function onCalcNationalIncome(string $type, int $amount):int{ public function onCalcNationalIncome(string $type, $amount){
if($type == 'gold'){ if($type == 'gold'){
return Util::toInt($amount * 0.9); return $amount * 0.9;
} }
return $amount; return $amount;
+3 -3
View File
@@ -29,9 +29,9 @@ class che_태평도 extends \sammo\BaseNation{
return $value; return $value;
} }
public function onCalcNationalIncome(string $type, int $amount):int{ public function onCalcNationalIncome(string $type, $amount){
if($type == 'pop'){ if($type == 'pop' && $amount > 0){
return Util::toInt($amount * 1.2); return $amount * 1.2;
} }
return $amount; return $amount;
@@ -8,7 +8,7 @@ class che_축성 extends \sammo\BaseSpecial{
protected $id = 10; protected $id = 10;
protected $name = '축성'; protected $name = '축성';
protected $info = '[내정] 기술 연구 : 기본 보정 +10%, 성공률 +10%p, 비용 -20%'; protected $info = '[내정] 성벽 보수 : 기본 보정 +10%, 성공률 +10%p, 비용 -20%';
static $selectWeightType = SpecialityHelper::WEIGHT_NORM; static $selectWeightType = SpecialityHelper::WEIGHT_NORM;
static $selectWeight = 1; static $selectWeight = 1;
+1 -1
View File
@@ -15,7 +15,7 @@ class che_궁병 extends \sammo\BaseSpecial{
static $selectWeightType = SpecialityHelper::WEIGHT_NORM; static $selectWeightType = SpecialityHelper::WEIGHT_NORM;
static $selectWeight = 1; static $selectWeight = 1;
static $type = [ static $type = [
SpecialityHelper::STAT_LEADERSHIP | SpecialityHelper::REQ_DEXTERITY | SpecialityHelper::ARMY_ARCHER, SpecialityHelper::STAT_LEADERSHIP | SpecialityHelper::REQ_DEXTERITY | SpecialityHelper::ARMY_ARCHER | SpecialityHelper::STAT_NOT_INTEL,
SpecialityHelper::STAT_STRENGTH | SpecialityHelper::REQ_DEXTERITY | SpecialityHelper::ARMY_ARCHER SpecialityHelper::STAT_STRENGTH | SpecialityHelper::REQ_DEXTERITY | SpecialityHelper::ARMY_ARCHER
]; ];
+1 -1
View File
@@ -15,7 +15,7 @@ class che_귀병 extends \sammo\BaseSpecial{
static $selectWeightType = SpecialityHelper::WEIGHT_NORM; static $selectWeightType = SpecialityHelper::WEIGHT_NORM;
static $selectWeight = 1; static $selectWeight = 1;
static $type = [ static $type = [
SpecialityHelper::STAT_INTEL | SpecialityHelper::ARMY_WIZARD | SpecialityHelper::REQ_DEXTERITY SpecialityHelper::STAT_INTEL | SpecialityHelper::ARMY_WIZARD | SpecialityHelper::REQ_DEXTERITY | SpecialityHelper::STAT_NOT_STRENGTH
]; ];
public function onCalcDomestic(string $turnType, string $varType, float $value, $aux=null):float{ public function onCalcDomestic(string $turnType, string $varType, float $value, $aux=null):float{
+1 -1
View File
@@ -15,7 +15,7 @@ class che_기병 extends \sammo\BaseSpecial{
static $selectWeightType = SpecialityHelper::WEIGHT_NORM; static $selectWeightType = SpecialityHelper::WEIGHT_NORM;
static $selectWeight = 1; static $selectWeight = 1;
static $type = [ static $type = [
SpecialityHelper::STAT_LEADERSHIP | SpecialityHelper::REQ_DEXTERITY | SpecialityHelper::ARMY_CAVALRY, SpecialityHelper::STAT_LEADERSHIP | SpecialityHelper::REQ_DEXTERITY | SpecialityHelper::ARMY_CAVALRY | SpecialityHelper::STAT_NOT_INTEL,
SpecialityHelper::STAT_STRENGTH | SpecialityHelper::REQ_DEXTERITY | SpecialityHelper::ARMY_CAVALRY SpecialityHelper::STAT_STRENGTH | SpecialityHelper::REQ_DEXTERITY | SpecialityHelper::ARMY_CAVALRY
]; ];
+1 -1
View File
@@ -15,7 +15,7 @@ class che_보병 extends \sammo\BaseSpecial{
static $selectWeightType = SpecialityHelper::WEIGHT_NORM; static $selectWeightType = SpecialityHelper::WEIGHT_NORM;
static $selectWeight = 1; static $selectWeight = 1;
static $type = [ static $type = [
SpecialityHelper::STAT_LEADERSHIP | SpecialityHelper::REQ_DEXTERITY | SpecialityHelper::ARMY_FOOTMAN, SpecialityHelper::STAT_LEADERSHIP | SpecialityHelper::REQ_DEXTERITY | SpecialityHelper::ARMY_FOOTMAN | SpecialityHelper::STAT_NOT_INTEL,
SpecialityHelper::STAT_STRENGTH | SpecialityHelper::REQ_DEXTERITY | SpecialityHelper::ARMY_FOOTMAN SpecialityHelper::STAT_STRENGTH | SpecialityHelper::REQ_DEXTERITY | SpecialityHelper::ARMY_FOOTMAN
]; ];
+1 -1
View File
@@ -68,7 +68,7 @@ class AutorunGeneralPolicy{
public $can징병 = true; public $can징병 = true;
public $can모병 = false; public $can모병 = false;
public $can한계징병 = true; public $can한계징병 = false;
public $can고급병종 = false; public $can고급병종 = false;
public $can전투준비 = true; public $can전투준비 = true;
public $can소집해제 = true; public $can소집해제 = true;
+2 -2
View File
@@ -240,10 +240,10 @@ class AutorunNationPolicy {
} }
if($this->reqHumanWarRecommandGold === 0){ if($this->reqHumanWarRecommandGold === 0){
$this->reqHumanWarRecommandGold = Util::round($this->reqHumanWarUrgentGold * 3, -2); $this->reqHumanWarRecommandGold = Util::round($this->reqHumanWarUrgentGold * 2, -2);
} }
if($this->reqHumanWarRecommandRice === 0){ if($this->reqHumanWarRecommandRice === 0){
$this->reqHumanWarRecommandRice = Util::round($this->reqHumanWarUrgentRice * 3, -2); $this->reqHumanWarRecommandRice = Util::round($this->reqHumanWarUrgentRice * 2, -2);
} }
if($general->getNPCType() >= 2){ if($general->getNPCType() >= 2){
+1 -1
View File
@@ -6,7 +6,7 @@ abstract class BaseWarUnitTrigger extends ObjectTrigger{
const TYPE_NONE = 0; const TYPE_NONE = 0;
const TYPE_ITEM = 1; const TYPE_ITEM = 1;
const TYPE_CONSUMABLE_ITEM = 2; const TYPE_CONSUMABLE_ITEM = 1 | 2;
protected $raiseType = self::TYPE_NONE; protected $raiseType = self::TYPE_NONE;
+1 -1
View File
@@ -455,7 +455,7 @@ abstract class BaseCommand{
} }
public function setResultTurn(LastTurn $lastTurn){ public function setResultTurn(LastTurn $lastTurn){
$this->generalObj->setResultTurn($lastTurn); $this->generalObj->_setResultTurn($lastTurn);
} }
public function getResultTurn():LastTurn{ public function getResultTurn():LastTurn{
+1 -1
View File
@@ -95,7 +95,7 @@ class che_NPC능동 extends Command\GeneralCommand{
$logger->pushGeneralActionLog("NPC 전용 명령을 이용해 {$cityName}{$josaRo} 이동했습니다."); $logger->pushGeneralActionLog("NPC 전용 명령을 이용해 {$cityName}{$josaRo} 이동했습니다.");
$general->setVar('city', $destCityID); $general->setVar('city', $destCityID);
$general->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
} }
$general->applyDB($db); $general->applyDB($db);
+1 -1
View File
@@ -165,7 +165,7 @@ class che_강행 extends Command\GeneralCommand
$general->increaseVarWithLimit('gold', -$reqGold, 0); $general->increaseVarWithLimit('gold', -$reqGold, 0);
$general->addExperience($exp); $general->addExperience($exp);
$general->increaseVar('leadership_exp', 1); $general->increaseVar('leadership_exp', 1);
$general->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->checkStatChange(); $general->checkStatChange();
$general->applyDB($db); $general->applyDB($db);
+1 -1
View File
@@ -172,7 +172,7 @@ class che_거병 extends Command\GeneralCommand{
$general->setVar('officer_city', 0); $general->setVar('officer_city', 0);
$general->setVar('nation', $nationID); $general->setVar('nation', $nationID);
$general->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->checkStatChange(); $general->checkStatChange();
$general->applyDB($db); $general->applyDB($db);
+287 -287
View File
@@ -1,287 +1,287 @@
<?php <?php
namespace sammo\Command\General; namespace sammo\Command\General;
use\sammo\{ use\sammo\{
DB, DB,
Util, Util,
JosaUtil, JosaUtil,
General, General,
ActionLogger, ActionLogger,
GameConst, GameConst,
GameUnitConst, GameUnitConst,
LastTurn, LastTurn,
Command, Command,
Json Json
}; };
use function\sammo\{ use function\sammo\{
tryUniqueItemLottery, tryUniqueItemLottery,
getAllNationStaticInfo getAllNationStaticInfo
}; };
use \sammo\Constraint\Constraint; use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper; use \sammo\Constraint\ConstraintHelper;
use sammo\CityConst; use sammo\CityConst;
use function sammo\buildNationTypeClass; use function sammo\buildNationTypeClass;
use function sammo\refreshNationStaticInfo; use function sammo\refreshNationStaticInfo;
use function sammo\GetNationColors; use function sammo\GetNationColors;
use function sammo\newColor; use function sammo\newColor;
class che_건국 extends Command\GeneralCommand class che_건국 extends Command\GeneralCommand
{ {
static protected $actionName = '건국'; static protected $actionName = '건국';
static public $reqArg = true; static public $reqArg = true;
protected function argTest(): bool protected function argTest(): bool
{ {
if ($this->arg === null) { if ($this->arg === null) {
return false; return false;
} }
$nationName = $this->arg['nationName'] ?? null; $nationName = $this->arg['nationName'] ?? null;
$nationType = $this->arg['nationType'] ?? null; $nationType = $this->arg['nationType'] ?? null;
$colorType = $this->arg['colorType'] ?? null; $colorType = $this->arg['colorType'] ?? null;
if ($nationName === null || $nationType === null || $colorType === null) { if ($nationName === null || $nationType === null || $colorType === null) {
return false; return false;
} }
if (!is_string($nationName) || !is_string($nationType) || !is_int($colorType)) { if (!is_string($nationName) || !is_string($nationType) || !is_int($colorType)) {
return false; return false;
} }
if (mb_strwidth($nationName) > 18 || $nationName == '') { if (mb_strwidth($nationName) > 18 || $nationName == '') {
return false; return false;
} }
if (!key_exists($colorType, GetNationColors())) { if (!key_exists($colorType, GetNationColors())) {
return false; return false;
} }
try { try {
$nationTypeClass = buildNationTypeClass($nationType); $nationTypeClass = buildNationTypeClass($nationType);
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
return false; return false;
} }
$this->arg = [ $this->arg = [
'nationName' => $nationName, 'nationName' => $nationName,
'nationType' => $nationType, 'nationType' => $nationType,
'colorType' => $colorType 'colorType' => $colorType
]; ];
return true; return true;
} }
protected function init() protected function init()
{ {
$env = $this->env; $env = $this->env;
$this->setCity(); $this->setCity();
$this->setNation(['gennum', 'aux']); $this->setNation(['gennum', 'aux']);
$relYear = $env['year'] - $env['startyear']; $relYear = $env['year'] - $env['startyear'];
$this->minConditionConstraints = [ $this->minConditionConstraints = [
ConstraintHelper::BeOpeningPart($relYear + 1), ConstraintHelper::BeOpeningPart($relYear + 1),
ConstraintHelper::ReqNationValue('level', '국가규모', '==', 0, '정식 국가가 아니어야합니다.') ConstraintHelper::ReqNationValue('level', '국가규모', '==', 0, '정식 국가가 아니어야합니다.')
]; ];
} }
protected function initWithArg() protected function initWithArg()
{ {
$env = $this->env; $env = $this->env;
$relYear = $env['year'] - $env['startyear']; $relYear = $env['year'] - $env['startyear'];
$nationName = $this->arg['nationName']; $nationName = $this->arg['nationName'];
$nationType = $this->arg['nationType']; $nationType = $this->arg['nationType'];
$colorType = $this->arg['colorType']; $colorType = $this->arg['colorType'];
$this->fullConditionConstraints = [ $this->fullConditionConstraints = [
ConstraintHelper::BeLord(), ConstraintHelper::BeLord(),
ConstraintHelper::WanderingNation(), ConstraintHelper::WanderingNation(),
ConstraintHelper::ReqNationValue('gennum', '수하 장수', '>=', 2), ConstraintHelper::ReqNationValue('gennum', '수하 장수', '>=', 2),
ConstraintHelper::BeOpeningPart($relYear + 1), ConstraintHelper::BeOpeningPart($relYear + 1),
ConstraintHelper::CheckNationNameDuplicate($nationName), ConstraintHelper::CheckNationNameDuplicate($nationName),
ConstraintHelper::AllowJoinAction(), ConstraintHelper::AllowJoinAction(),
ConstraintHelper::ConstructableCity(), ConstraintHelper::ConstructableCity(),
]; ];
} }
public function getBrief(): string public function getBrief(): string
{ {
$nationName = $this->arg['nationName']; $nationName = $this->arg['nationName'];
$josaUl = JosaUtil::pick($nationName, '을'); $josaUl = JosaUtil::pick($nationName, '을');
return "{$nationName}{$josaUl} 건국"; return "{$nationName}{$josaUl} 건국";
} }
public function getCost(): array public function getCost(): array
{ {
return [0, 0]; return [0, 0];
} }
public function getPreReqTurn(): int public function getPreReqTurn(): int
{ {
return 0; return 0;
} }
public function getPostReqTurn(): int public function getPostReqTurn(): int
{ {
return 0; return 0;
} }
public function run(): bool public function run(): bool
{ {
if (!$this->hasFullConditionMet()) { if (!$this->hasFullConditionMet()) {
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도'); throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
} }
$db = DB::db(); $db = DB::db();
$env = $this->env; $env = $this->env;
$general = $this->generalObj; $general = $this->generalObj;
$date = $general->getTurnTime($general::TURNTIME_HM); $date = $general->getTurnTime($general::TURNTIME_HM);
$generalName = $general->getName(); $generalName = $general->getName();
$josaYi = JosaUtil::pick($generalName, '이'); $josaYi = JosaUtil::pick($generalName, '이');
$nationName = $this->arg['nationName']; $nationName = $this->arg['nationName'];
$nationType = $this->arg['nationType']; $nationType = $this->arg['nationType'];
$colorType = GetNationColors()[$this->arg['colorType']]; $colorType = GetNationColors()[$this->arg['colorType']];
$cityName = $this->city['name']; $cityName = $this->city['name'];
$josaUl = JosaUtil::pick($nationName, '을'); $josaUl = JosaUtil::pick($nationName, '을');
$logger = $general->getLogger(); $logger = $general->getLogger();
$nationTypeClass = buildNationTypeClass($nationType); $nationTypeClass = buildNationTypeClass($nationType);
$nationTypeName = $nationTypeClass->getName(); $nationTypeName = $nationTypeClass->getName();
$logger->pushGeneralActionLog("<D><b>{$nationName}</b></>{$josaUl} 건국하였습니다. <1>$date</>"); $logger->pushGeneralActionLog("<D><b>{$nationName}</b></>{$josaUl} 건국하였습니다. <1>$date</>");
$logger->pushGlobalActionLog("<Y>{$generalName}</>{$josaYi} <G><b>{$cityName}</b></>에 국가를 건설하였습니다."); $logger->pushGlobalActionLog("<Y>{$generalName}</>{$josaYi} <G><b>{$cityName}</b></>에 국가를 건설하였습니다.");
$josaNationYi = JosaUtil::pick($nationName, '이'); $josaNationYi = JosaUtil::pick($nationName, '이');
$logger->pushGlobalHistoryLog("<Y><b>【건국】</b></>{$nationTypeName} <D><b>{$nationName}</b></>{$josaNationYi} 새로이 등장하였습니다."); $logger->pushGlobalHistoryLog("<Y><b>【건국】</b></>{$nationTypeName} <D><b>{$nationName}</b></>{$josaNationYi} 새로이 등장하였습니다.");
$logger->pushGeneralHistoryLog("<D><b>{$nationName}</b></>{$josaUl} 건국"); $logger->pushGeneralHistoryLog("<D><b>{$nationName}</b></>{$josaUl} 건국");
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <D><b>{$nationName}</b></>{$josaUl} 건국"); $logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <D><b>{$nationName}</b></>{$josaUl} 건국");
$exp = 1000; $exp = 1000;
$ded = 1000; $ded = 1000;
$general->addExperience($exp); $general->addExperience($exp);
$general->addDedication($ded); $general->addDedication($ded);
$aux = Json::decode($this->nation['aux'])??[]; $aux = Json::decode($this->nation['aux'])??[];
$aux['can_국기변경'] = 1; $aux['can_국기변경'] = 1;
$db->update('city', [ $db->update('city', [
'nation' => $general->getNationID(), 'nation' => $general->getNationID(),
'conflict' => '{}' 'conflict' => '{}'
], 'city=%i', $general->getCityID()); ], 'city=%i', $general->getCityID());
$db->update('nation', [ $db->update('nation', [
'name' => $nationName, 'name' => $nationName,
'color' => $colorType, 'color' => $colorType,
'level' => 1, 'level' => 1,
'type' => $nationType, 'type' => $nationType,
'capital' => $general->getCityID(), 'capital' => $general->getCityID(),
'aux' => Json::encode($aux) 'aux' => Json::encode($aux)
], 'nation=%i', $general->getNationID()); ], 'nation=%i', $general->getNationID());
refreshNationStaticInfo(); refreshNationStaticInfo();
$general->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->checkStatChange(); $general->checkStatChange();
tryUniqueItemLottery($general, '건국'); tryUniqueItemLottery($general, '건국');
$general->applyDB($db); $general->applyDB($db);
return true; return true;
} }
public function getJSFiles(): array public function getJSFiles(): array
{ {
return [ return [
'js/colorSelect.js' 'js/colorSelect.js'
]; ];
} }
public function getForm(): string public function getForm(): string
{ {
if (count(getAllNationStaticInfo()) >= $this->env['maxnation']) { if (count(getAllNationStaticInfo()) >= $this->env['maxnation']) {
return '더 이상 건국은 불가능합니다.'; return '더 이상 건국은 불가능합니다.';
} }
//NOTE: 새로운 방법이 생기기 전까진 아무색이나 선택 가능하도록 하자. //NOTE: 새로운 방법이 생기기 전까진 아무색이나 선택 가능하도록 하자.
/* /*
foreach(GetNationColors() as $color){ foreach(GetNationColors() as $color){
$colorUsed[$color] = 0; $colorUsed[$color] = 0;
} }
foreach(getAllNationStaticInfo() as $nation){ foreach(getAllNationStaticInfo() as $nation){
if($nation['level'] <= 0){ if($nation['level'] <= 0){
continue; continue;
} }
$colorUsed[$nation['color']]++; $colorUsed[$nation['color']]++;
} }
$colorUsedCnt = 0; $colorUsedCnt = 0;
foreach($colorUsed as $color=>$used){ foreach($colorUsed as $color=>$used){
if($used){ if($used){
continue; continue;
} }
$colorUsedCnt += 1; $colorUsedCnt += 1;
} }
//색깔이 다 쓰였으면 그냥 모두 허용 //색깔이 다 쓰였으면 그냥 모두 허용
if($colorUsedCnt === count($colorUsed)){ if($colorUsedCnt === count($colorUsed)){
foreach(array_keys($colorUsed) as $color){ foreach(array_keys($colorUsed) as $color){
$colorUsed[$color] = 0; $colorUsed[$color] = 0;
} }
} }
*/ */
ob_start(); ob_start();
?> ?>
현재 도시에서 나라를 세웁니다. 중, 소도시에서만 가능합니다.<br> 현재 도시에서 나라를 세웁니다. 중, 소도시에서만 가능합니다.<br>
<?php foreach (GameConst::$availableNationType as $nationType) : <?php foreach (GameConst::$availableNationType as $nationType) :
$nationClass = buildNationTypeClass($nationType); $nationClass = buildNationTypeClass($nationType);
[$name, $pros, $cons] = [$nationClass->getName(), $nationClass::$pros, $nationClass::$cons]; [$name, $pros, $cons] = [$nationClass->getName(), $nationClass::$pros, $nationClass::$cons];
?> ?>
- <?= $name ?> : <span style='color:cyan;'><?= $pros ?></span> <span style='color:magenta;'><?= $cons ?></span><br> - <?= $name ?> : <span style='color:cyan;'><?= $pros ?></span> <span style='color:magenta;'><?= $cons ?></span><br>
<?php endforeach; ?> <?php endforeach; ?>
<br> <br>
국명 : <input type='text' class='formInput' name="nationName" id="nationName" size='18' maxlength='18' style='color:white;background-color:black;'> 국명 : <input type='text' class='formInput' name="nationName" id="nationName" size='18' maxlength='18' style='color:white;background-color:black;'>
색상 : <select class='formInput' name='colorType' id='colorType' size='1'> 색상 : <select class='formInput' name='colorType' id='colorType' size='1'>
<?php foreach (GetNationColors() as $idx => $color) : <?php foreach (GetNationColors() as $idx => $color) :
/* /*
if($colorUsed[$color] > 0){ if($colorUsed[$color] > 0){
continue; continue;
} }
*/ */
?> ?>
<option value="<?= $idx ?>" style='background-color:<?= $color ?>;color:<?= newColor($color) ?>;'>국가명(<?=$color?>)</option> <option value="<?= $idx ?>" data-color="<?= $color ?>" data-font-color="<?=newColor($color)?>" style='background-color:<?= $color ?>;color:<?= newColor($color) ?>;'>국가명(<?=$color?>)</option>
<?php endforeach; ?> <?php endforeach; ?>
</select> </select>
성향 : <select class='formInput' name='nationType' id='nationType' size='1'> 성향 : <select class='formInput' name='nationType' id='nationType' size='1'>
<?php foreach (GameConst::$availableNationType as $nationType) : <?php foreach (GameConst::$availableNationType as $nationType) :
$nationTypeName = buildNationTypeClass($nationType)->getName(); $nationTypeName = buildNationTypeClass($nationType)->getName();
?> ?>
<option value='<?= $nationType ?>' style=background-color:black;color:white;><?= $nationTypeName ?></option> <option value='<?= $nationType ?>' style=background-color:black;color:white;><?= $nationTypeName ?></option>
<?php endforeach; ?> <?php endforeach; ?>
</select> </select>
<input type=button id="commonSubmit" value="<?= $this->getName() ?>"> <input type=button id="commonSubmit" value="<?= $this->getName() ?>">
<?php <?php
return ob_get_clean(); return ob_get_clean();
} }
} }
+1 -1
View File
@@ -114,7 +114,7 @@ class che_견문 extends Command\GeneralCommand{
$logger->pushGeneralActionLog("{$text} <1>$date</>"); $logger->pushGeneralActionLog("{$text} <1>$date</>");
$general->addExperience($exp); $general->addExperience($exp);
$general->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->checkStatChange(); $general->checkStatChange();
$general->applyDB($db); $general->applyDB($db);
@@ -179,7 +179,7 @@ class che_군량매매 extends Command\GeneralCommand{
$general->addDedication($ded); $general->addDedication($ded);
$general->increaseVar($incStat, 1); $general->increaseVar($incStat, 1);
$general->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->checkStatChange(); $general->checkStatChange();
$general->applyDB($db); $general->applyDB($db);
+1 -1
View File
@@ -99,7 +99,7 @@ class che_귀환 extends Command\GeneralCommand{
$general->addExperience($exp); $general->addExperience($exp);
$general->addDedication($ded); $general->addDedication($ded);
$general->increaseVar('leadership_exp', 1); $general->increaseVar('leadership_exp', 1);
$general->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->checkStatChange(); $general->checkStatChange();
$general->applyDB($db); $general->applyDB($db);
@@ -125,7 +125,7 @@ class che_기술연구 extends che_상업투자{
$general->addDedication($ded); $general->addDedication($ded);
$general->increaseVar(static::$statKey.'_exp', 1); $general->increaseVar(static::$statKey.'_exp', 1);
$general->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->checkStatChange(); $general->checkStatChange();
tryUniqueItemLottery($general); tryUniqueItemLottery($general);
$general->applyDB($db); $general->applyDB($db);
+1 -1
View File
@@ -126,7 +126,7 @@ class che_단련 extends Command\GeneralCommand{
$general->increaseVarWithLimit('rice', -$reqRice, 0); $general->increaseVarWithLimit('rice', -$reqRice, 0);
$general->addExperience($exp); $general->addExperience($exp);
$general->increaseVar($incStat, 1); $general->increaseVar($incStat, 1);
$general->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->checkStatChange(); $general->checkStatChange();
tryUniqueItemLottery($general); tryUniqueItemLottery($general);
$general->applyDB($db); $general->applyDB($db);
+6 -7
View File
@@ -18,7 +18,8 @@ use function \sammo\{
CriticalScoreEx, CriticalScoreEx,
tryUniqueItemLottery, tryUniqueItemLottery,
getAllNationStaticInfo, getAllNationStaticInfo,
getNationStaticInfo getNationStaticInfo,
newColor
}; };
use \sammo\Constraint\Constraint; use \sammo\Constraint\Constraint;
@@ -70,7 +71,6 @@ class che_등용 extends Command\GeneralCommand{
$this->minConditionConstraints=[ $this->minConditionConstraints=[
ConstraintHelper::ReqEnvValue('join_mode', '!=', 'onlyRandom', '랜덤 임관만 가능합니다'), ConstraintHelper::ReqEnvValue('join_mode', '!=', 'onlyRandom', '랜덤 임관만 가능합니다'),
ConstraintHelper::NotBeNeutral(), ConstraintHelper::NotBeNeutral(),
ConstraintHelper::NotOpeningPart($relYear),
ConstraintHelper::OccupiedCity(), ConstraintHelper::OccupiedCity(),
ConstraintHelper::SuppliedCity(), ConstraintHelper::SuppliedCity(),
]; ];
@@ -87,7 +87,6 @@ class che_등용 extends Command\GeneralCommand{
$this->fullConditionConstraints=[ $this->fullConditionConstraints=[
ConstraintHelper::ReqEnvValue('join_mode', '!=', 'onlyRandom', '랜덤 임관만 가능합니다'), ConstraintHelper::ReqEnvValue('join_mode', '!=', 'onlyRandom', '랜덤 임관만 가능합니다'),
ConstraintHelper::NotBeNeutral(), ConstraintHelper::NotBeNeutral(),
ConstraintHelper::NotOpeningPart($relYear),
ConstraintHelper::OccupiedCity(), ConstraintHelper::OccupiedCity(),
ConstraintHelper::SuppliedCity(), ConstraintHelper::SuppliedCity(),
ConstraintHelper::ExistsDestGeneral(), ConstraintHelper::ExistsDestGeneral(),
@@ -169,7 +168,7 @@ class che_등용 extends Command\GeneralCommand{
$general->increaseVar('leadership_exp', 1); $general->increaseVar('leadership_exp', 1);
$general->increaseVarWithLimit('gold', -$reqGold, 0); $general->increaseVarWithLimit('gold', -$reqGold, 0);
$general->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->checkStatChange(); $general->checkStatChange();
$general->applyDB($db); $general->applyDB($db);
@@ -187,7 +186,7 @@ class che_등용 extends Command\GeneralCommand{
if(!key_exists($destNationID, $destGenerals)){ if(!key_exists($destNationID, $destGenerals)){
$destGenerals[$destNationID] = []; $destGenerals[$destNationID] = [];
} }
$destGenerals[$destNationID] = [$destGeneral]; $destGenerals[$destNationID][] = $destGeneral;
} }
$nationList = array_merge([0=>getNationStaticInfo(0)], getAllNationStaticInfo()); $nationList = array_merge([0=>getNationStaticInfo(0)], getAllNationStaticInfo());
@@ -199,14 +198,14 @@ class che_등용 extends Command\GeneralCommand{
등용할 장수를 목록에서 선택하세요.<br> 등용할 장수를 목록에서 선택하세요.<br>
<select class='formInput' name="destGeneralID" id="destGeneralID" size='1' style='color:white;background-color:black;'> <select class='formInput' name="destGeneralID" id="destGeneralID" size='1' style='color:white;background-color:black;'>
<?php foreach($nationList as $destNation): ?> <?php foreach($nationList as $destNation): ?>
<optgroup style='color:<?=$destNation['color']?>'>【<?=$destNation['name']?>】 <optgroup style='background-color:<?=$destNation['color']?>;color:<?=newColor($destNation['color'])?>;' label="【<?=$destNation['name']?>】" >
<?php foreach($destGenerals[$destNation['nation']]??[] as $destGeneral): <?php foreach($destGenerals[$destNation['nation']]??[] as $destGeneral):
$nameColor = \sammo\getNameColor($destGeneral['npc']); $nameColor = \sammo\getNameColor($destGeneral['npc']);
if($nameColor){ if($nameColor){
$nameColor = " style='color:{$nameColor}'"; $nameColor = " style='color:{$nameColor}'";
} }
?> ?>
<option value='<?=$destGeneral['no']?>' <?=$nameColor?>><?=$destGeneral['name']?></option> <option style="background-color:black;color:white" value='<?=$destGeneral['no']?>' <?=$nameColor?>><?=$destGeneral['name']?></option>
<?php endforeach; ?> <?php endforeach; ?>
</optgroup> </optgroup>
<?php endforeach; ?> <?php endforeach; ?>
@@ -91,7 +91,6 @@ class che_등용수락 extends Command\GeneralCommand{
$this->fullConditionConstraints=[ $this->fullConditionConstraints=[
ConstraintHelper::ReqEnvValue('join_mode', '!=', 'onlyRandom', '랜덤 임관만 가능합니다'), ConstraintHelper::ReqEnvValue('join_mode', '!=', 'onlyRandom', '랜덤 임관만 가능합니다'),
ConstraintHelper::NotOpeningPart($relYear),
ConstraintHelper::ExistsDestNation(), ConstraintHelper::ExistsDestNation(),
ConstraintHelper::AllowJoinDestNation($relYear), ConstraintHelper::AllowJoinDestNation($relYear),
ConstraintHelper::ReqDestNationValue('level', '국가규모', '>', 0, '방랑군에는 임관할 수 없습니다.'), ConstraintHelper::ReqDestNationValue('level', '국가규모', '>', 0, '방랑군에는 임관할 수 없습니다.'),

Some files were not shown because too many files have changed in this diff Show More