| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007 |
- <?php
- namespace App\Module\Game\AdminControllers;
- use App\Module\Game\DCache\ChestJsonConfig;
- use App\Module\Game\DCache\DismantleJsonConfig;
- use App\Module\Game\DCache\FarmHouseJsonConfig;
- use App\Module\Game\DCache\FarmLandJsonConfig;
- use App\Module\Game\DCache\FundCurrencyJsonConfig;
- use App\Module\Game\DCache\ItemJsonConfig;
- use App\Module\Game\DCache\PetJsonConfig;
- use App\Module\Game\DCache\RecipeJsonConfig;
- use App\Module\GameItems\AdminControllers\Tools\RefreshCheckTool;
- use App\Module\GameItems\AdminControllers\Tools\SyncChetsJsonTool;
- use App\Module\GameItems\AdminControllers\Tools\SyncDismantleJsonTool;
- use App\Module\GameItems\AdminControllers\Tools\SyncItemsJsonTool;
- use App\Module\GameItems\AdminControllers\Tools\SyncRecipeJsonTool;
- use Carbon\Carbon;
- use Dcat\Admin\Layout\Content;
- use Dcat\Admin\Layout\Row;
- use Dcat\Admin\Widgets\Card;
- use Dcat\Admin\Widgets\Table;
- use Dcat\Admin\Http\Controllers\AdminController;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Artisan;
- use Spatie\RouteAttributes\Attributes\Resource;
- use Spatie\RouteAttributes\Attributes\Get;
- use Spatie\RouteAttributes\Attributes\Post;
- use UCore\Helper\Datetime;
- /**
- * 游戏配置表管理控制器
- *
- * 用于显示和管理游戏中的各种配置表
- */
- #[Resource('game-jsonconfigs', names: 'dcat.admin.game-jsonconfigs')]
- class GameConfigController extends AdminController
- {
- /**
- * 刷新货币配置表
- *
- * @return \Illuminate\Http\JsonResponse
- */
- #[Get('game-jsonconfigs/refresh-currencies')]
- public function refreshCurrencies()
- {
- try {
- // 调用命令生成JSON
- $process = new \Symfony\Component\Process\Process(['php', 'artisan', 'fund:generate-currency-json']);
- $process->setWorkingDirectory(base_path());
- $process->run();
- if (!$process->isSuccessful()) {
- return response()->json([
- 'status' => 'error',
- 'message' => '刷新失败: ' . $process->getErrorOutput()
- ]);
- }
- // 强制刷新缓存
- FundCurrencyJsonConfig::getData([], true);
- return response()->json([
- 'status' => 'success',
- 'message' => '刷新成功'
- ]);
- } catch (\Exception $e) {
- return response()->json([
- 'status' => 'error',
- 'message' => '刷新失败: ' . $e->getMessage()
- ]);
- }
- }
- /**
- * 刷新土地配置表
- *
- * @return \Illuminate\Http\JsonResponse
- */
- #[Get('game-jsonconfigs/refresh-farm-land')]
- public function refreshFarmLand()
- {
- try {
- // 调用命令生成JSON
- $process = new \Symfony\Component\Process\Process(['php', 'artisan', 'farm:generate-land-json']);
- $process->setWorkingDirectory(base_path());
- $process->run();
- if (!$process->isSuccessful()) {
- return response()->json([
- 'status' => 'error',
- 'message' => '刷新失败: ' . $process->getErrorOutput()
- ]);
- }
- // 强制刷新缓存
- FarmLandJsonConfig::getData([], true);
- return response()->json([
- 'status' => 'success',
- 'message' => '刷新成功'
- ]);
- } catch (\Exception $e) {
- return response()->json([
- 'status' => 'error',
- 'message' => '刷新失败: ' . $e->getMessage()
- ]);
- }
- }
- /**
- * 页面标题
- *
- * @var string
- */
- protected $title = '游戏配置表管理';
- /**
- * 页面描述
- *
- * @var string
- */
- protected $description = '查看和刷新游戏中的各种配置表';
- /**
- * 配置表首页
- *
- * @param Content $content
- * @return Content
- */
- public function index(Content $content)
- {
- return $content
- ->title($this->title)
- ->description($this->description)
- ->body(function (Row $row) {
- // 物品配置表卡片
- $row->column(6, $this->createConfigCard(
- '物品配置表',
- 'items.json',
- 'gameitems:generate-json',
- SyncItemsJsonTool::make(),
- $this->getItemConfigInfo()
- ));
- // 宝箱配置表卡片
- $row->column(6, $this->createConfigCard(
- '宝箱配置表',
- 'chest.json',
- 'gameitems:generate-chest-json',
- SyncChetsJsonTool::make(),
- $this->getChestConfigInfo()
- ));
- })
- ->body(function (Row $row) {
- // 合成配方配置表卡片
- $row->column(6, $this->createConfigCard(
- '物品合成配方配置表',
- 'recipe.json',
- 'gameitems:generate-recipe-json',
- SyncRecipeJsonTool::make(),
- $this->getRecipeConfigInfo()
- ));
- // 分解配方配置表卡片
- $row->column(6, $this->createConfigCard(
- '物品分解配方配置表',
- 'dismantle.json',
- 'gameitems:generate-dismantle-json',
- SyncDismantleJsonTool::make(),
- $this->getDismantleConfigInfo()
- ));
- })
- ->body(function (Row $row) {
- // 宠物配置表卡片
- $row->column(6, $this->createConfigCard(
- '宠物配置表',
- 'pet_config.json, pet_level_config.json, pet_skill_config.json',
- 'pet:generate-json',
- 'game-jsonconfigs/refresh-pets',
- $this->getPetConfigInfo()
- ));
- // 农场房屋配置表卡片
- $row->column(6, $this->createConfigCard(
- '农场房屋配置表',
- 'farm_house.json',
- 'farm:generate-house-json',
- 'game-jsonconfigs/refresh-farm-house',
- $this->getFarmHouseConfigInfo()
- ));
- })
- ->body(function (Row $row) {
- // 土地配置表卡片
- $row->column(6, $this->createConfigCard(
- '土地配置表',
- 'farm_land.json',
- 'farm:generate-land-json',
- 'game-jsonconfigs/refresh-farm-land',
- $this->getFarmLandConfigInfo()
- ));
- // 货币配置表卡片
- $row->column(6, $this->createConfigCard(
- '货币配置表',
- 'currencies.json',
- 'fund:generate-currency-json',
- 'game-jsonconfigs/refresh-currencies',
- $this->getFundCurrencyConfigInfo()
- ));
- });
- }
- /**
- * 创建配置表信息卡片
- *
- * @param string $title 卡片标题
- * @param string $filename 文件名
- * @param string $command 生成命令
- * @param string $refreshUrl 刷新URL
- * @param array $info 配置信息
- * @return Card
- */
- protected function createConfigCard($title, $filename, $command, $refresh, $info)
- {
- $headers = [ '属性', '值' ];
- $rows = [];
- foreach ($info as $key => $value) {
- $rows[] = [ $key, $value ];
- }
- $card = new Card($title, Table::make($headers, $rows));
- $card->tool($refresh);
- // 处理文件名,获取第一个文件名(如果有多个文件,只取第一个)
- $firstFilename = explode(',', $filename)[0];
- $firstFilename = trim($firstFilename);
- // 特殊处理各种配置表的映射关系
- if (strpos($filename, 'pet_config.json') !== false) {
- $key = 'pets';
- } elseif ($firstFilename === 'farm_house.json') {
- $key = 'farm_house';
- } elseif ($firstFilename === 'farm_land.json') {
- $key = 'farm_land';
- } elseif ($firstFilename === 'currencies.json') {
- $key = 'currencies';
- } elseif ($firstFilename === 'chest.json') {
- $key = 'chest';
- } elseif ($firstFilename === 'items.json') {
- $key = 'items';
- } else {
- // 从文件名中提取key(去掉.json后缀)
- $key = str_replace('.json', '', $firstFilename);
- }
- // 构建查看JSON文件的链接
- $jsonViewLink = "<a href='game-jsonconfigs/view-json/{$key}' target='_blank' class='btn btn-sm btn-primary' style='margin-top:8px;'>查看JSON内容</a>";
- $card->footer("<code>文件: {$filename}</code><br><code>命令: php artisan {$command}</code><br>{$jsonViewLink}");
- return $card;
- }
- /**
- * 获取物品配置表信息
- *
- * @return array
- */
- protected function getItemConfigInfo()
- {
- $data = ItemJsonConfig::getData();
- $info = [
- '生成时间' => Datetime::ts2string($data['generated_ts']),
- '物品数量' => isset($data['items']) ? count($data['items']) : 0,
- ];
- return $info;
- }
- /**
- * 获取物品合成配方配置表信息
- *
- * @return array
- */
- protected function getRecipeConfigInfo()
- {
- $data = RecipeJsonConfig::getData();
- $info = [
- '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
- '配方数量' => isset($data['recipes']) ? count($data['recipes']) : 0,
- ];
- return $info;
- }
- /**
- * 获取物品分解配方配置表信息
- *
- * @return array
- */
- protected function getDismantleConfigInfo()
- {
- $data = DismantleJsonConfig::getData();
- $info = [
- '生成时间' => isset($data['generated_ts']) ? Datetime::ts2string($data['generated_ts']) : '未生成',
- '规则数量' => isset($data['dismantle_rules']) ? count($data['dismantle_rules']) : 0,
- ];
- return $info;
- }
- /**
- * 获取宝箱配置表信息
- *
- * @return array
- */
- protected function getChestConfigInfo()
- {
- $data = ChestJsonConfig::getData();
- $info = [
- '生成时间' => Datetime::ts2string($data['generated_ts']),
- '宝箱数量' => isset($data['chest']) ? count($data['chest']) : 0,
- ];
- return $info;
- }
- /**
- * 获取宠物配置表信息
- *
- * @return array
- */
- protected function getPetConfigInfo()
- {
- $data = PetJsonConfig::getData();
- $petConfig = $data['pet_config'] ?? [];
- $petLevelConfig = $data['pet_level_config'] ?? [];
- $petSkillConfig = $data['pet_skill_config'] ?? [];
- $info = [
- '生成时间' => Datetime::ts2string($data['generated_ts']),
- '宠物数量' => isset($petConfig['pets']) ? count($petConfig['pets']) : 0,
- '等级配置数量' => isset($petLevelConfig['pet_levels']) ? count($petLevelConfig['pet_levels']) : 0,
- '技能配置数量' => isset($petSkillConfig['pet_skills']) ? count($petSkillConfig['pet_skills']) : 0,
- ];
- return $info;
- }
- /**
- * 获取农场房屋配置表信息
- *
- * @return array
- */
- protected function getFarmHouseConfigInfo()
- {
- $data = FarmHouseJsonConfig::getData();
- $info = [
- '生成时间' => Datetime::ts2string($data['generated_ts']),
- '房屋配置数量' => isset($data['house_configs']) ? count($data['house_configs']) : 0,
- ];
- return $info;
- }
- /**
- * 获取土地配置表信息
- *
- * @return array
- */
- protected function getFarmLandConfigInfo()
- {
- $data = FarmLandJsonConfig::getData();
- $info = [
- '生成时间' => Datetime::ts2string($data['generated_ts']),
- '土地类型数量' => isset($data['land_types']) ? count($data['land_types']) : 0,
- '升级路径数量' => isset($data['upgrade_paths']) ? count($data['upgrade_paths']) : 0,
- ];
- return $info;
- }
- /**
- * 获取货币配置表信息
- *
- * @return array
- */
- protected function getFundCurrencyConfigInfo()
- {
- $data = FundCurrencyJsonConfig::getData();
- // 计算有关联币种的账户种类数量
- $linkedAccountsCount = 0;
- if (isset($data['fund_configs'])) {
- foreach ($data['fund_configs'] as $fundConfig) {
- if (!empty($fundConfig['currency_id'])) {
- $linkedAccountsCount++;
- }
- }
- }
- $info = [
- '生成时间' => Datetime::ts2string($data['generated_ts']),
- '币种数量' => isset($data['currencies']) ? count($data['currencies']) : 0,
- '账户种类数量' => isset($data['fund_configs']) ? count($data['fund_configs']) : 0,
- '已关联币种的账户数量' => $linkedAccountsCount,
- ];
- return $info;
- }
- /**
- * 友好地显示JSON配置数据
- *
- * @param string $key 配置表键名
- * @return Content
- */
- #[Get('game-jsonconfigs/view-json/{key}')]
- public function viewJson($key, Content $content)
- {
- // 配置表映射关系
- $map = [
- 'items' => [ItemJsonConfig::class, '物品配置表'],
- 'chest' => [ChestJsonConfig::class, '宝箱配置表'],
- 'recipe' => [RecipeJsonConfig::class, '物品合成配方配置表'],
- 'dismantle' => [DismantleJsonConfig::class, '物品分解配方配置表'],
- 'pets' => [PetJsonConfig::class, '宠物配置表'],
- 'farm_house' => [FarmHouseJsonConfig::class, '农场房屋配置表'],
- 'farm_land' => [FarmLandJsonConfig::class, '土地配置表'],
- 'currencies' => [FundCurrencyJsonConfig::class, '货币配置表'],
- ];
- // 检查请求的配置表是否存在
- if (!isset($map[$key])) {
- return $content
- ->title('错误')
- ->description('配置表查看')
- ->body(new Card('错误', '配置表不存在'));
- }
- try {
- // 获取配置表数据
- $configClass = $map[$key][0];
- $title = $map[$key][1];
- $data = $configClass::getData();
- // 如果数据为空,返回错误
- if (empty($data)) {
- return $content
- ->title('错误')
- ->description('配置表查看')
- ->body(new Card('错误', '配置表数据为空'));
- }
- // 创建JSON查看器
- $jsonViewerId = 'json-viewer-' . uniqid();
- // 格式化JSON数据
- $formattedJson = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
- if ($formattedJson === false) {
- $formattedJson = json_encode(["error" => "无法解析JSON数据"], JSON_PRETTY_PRINT);
- }
- // 转义HTML特殊字符
- $escapedJson = htmlspecialchars($formattedJson, ENT_QUOTES, 'UTF-8');
- $html = <<<HTML
- <div>
- <style>
- .json-viewer {
- max-height: 80vh;
- overflow: auto;
- background-color: #f8f9fa;
- border-radius: 4px;
- padding: 15px;
- font-family: monospace;
- white-space: pre;
- font-size: 14px;
- line-height: 1.5;
- }
- .json-key { color: #a52a2a; }
- .json-string { color: #008000; }
- .json-number { color: #0000ff; }
- .json-boolean { color: #b22222; }
- .json-null { color: #808080; }
- </style>
- <div class="mb-2">
- <div class="input-group" style="margin-bottom: 10px;">
- <input type="text" class="form-control" id="search-{$jsonViewerId}" placeholder="搜索...">
- <div class="input-group-append">
- <button class="btn btn-default" id="search-btn-{$jsonViewerId}">搜索</button>
- </div>
- </div>
- <div class="btn-group">
- <button class="btn btn-sm btn-default" id="toggle-{$jsonViewerId}">折叠/展开</button>
- <button class="btn btn-sm btn-default" id="copy-{$jsonViewerId}">复制JSON</button>
- </div>
- </div>
- <pre id="{$jsonViewerId}" class="json-viewer">{$escapedJson}</pre>
- <script>
- $(document).ready(function() {
- // 高亮JSON语法
- function highlightJson() {
- var jsonContent = document.getElementById('{$jsonViewerId}');
- var jsonText = jsonContent.textContent;
- // 使用简单的正则表达式进行高亮
- var highlighted = jsonText
- // 高亮键
- .replace(/"([^"]+)"(?=\s*:)/g, '<span class="json-key">"$1"</span>')
- // 高亮字符串值
- .replace(/:\s*"([^"]*)"/g, ': <span class="json-string">"$1"</span>')
- // 高亮数字
- .replace(/:\s*(-?\d+(\.\d+)?)/g, ': <span class="json-number">$1</span>')
- // 高亮布尔值和null
- .replace(/:\s*(true|false|null)/g, ': <span class="json-boolean">$1</span>');
- jsonContent.innerHTML = highlighted;
- }
- // 复制JSON按钮
- document.getElementById('copy-{$jsonViewerId}').addEventListener('click', function() {
- var jsonContent = document.getElementById('{$jsonViewerId}');
- var jsonText = jsonContent.textContent;
- var tempTextarea = document.createElement('textarea');
- tempTextarea.value = jsonText;
- document.body.appendChild(tempTextarea);
- tempTextarea.select();
- document.execCommand('copy');
- document.body.removeChild(tempTextarea);
- alert('JSON已复制到剪贴板');
- });
- // 折叠/展开功能
- document.getElementById('toggle-{$jsonViewerId}').addEventListener('click', function() {
- var jsonViewer = document.getElementById('{$jsonViewerId}');
- var isCollapsed = jsonViewer.classList.contains('collapsed');
- if (isCollapsed) {
- // 展开
- jsonViewer.classList.remove('collapsed');
- jsonViewer.style.maxHeight = '80vh';
- this.textContent = '折叠';
- } else {
- // 折叠
- jsonViewer.classList.add('collapsed');
- jsonViewer.style.maxHeight = '200px';
- this.textContent = '展开';
- }
- });
- // 初始化
- highlightJson();
- // 搜索功能
- document.getElementById('search-btn-{$jsonViewerId}').addEventListener('click', function() {
- var searchText = document.getElementById('search-{$jsonViewerId}').value.trim();
- if (!searchText) return;
- // 展开JSON查看器
- var jsonViewer = document.getElementById('{$jsonViewerId}');
- jsonViewer.classList.remove('collapsed');
- jsonViewer.style.maxHeight = '80vh';
- document.getElementById('toggle-{$jsonViewerId}').textContent = '折叠';
- // 移除之前的高亮
- var content = jsonViewer.innerHTML;
- content = content.replace(/<mark class="highlight">(.*?)<\/mark>/g, '$1');
- // 高亮搜索文本
- if (searchText) {
- var regex = new RegExp('(' + searchText.replace(/[.*+?^$\{\}()|[\]\\]/g, '\\$&') + ')', 'gi');
- content = content.replace(regex, '<mark class="highlight" style="background-color: yellow; padding: 2px;">$1</mark>');
- }
- jsonViewer.innerHTML = content;
- // 滚动到第一个匹配项
- var firstHighlight = jsonViewer.querySelector('mark.highlight');
- if (firstHighlight) {
- firstHighlight.scrollIntoView({
- behavior: 'smooth',
- block: 'center'
- });
- } else {
- alert('未找到匹配项');
- }
- });
- // 绑定回车键搜索
- document.getElementById('search-{$jsonViewerId}').addEventListener('keypress', function(e) {
- if (e.key === 'Enter') {
- document.getElementById('search-btn-{$jsonViewerId}').click();
- }
- });
- // 默认折叠
- document.getElementById('toggle-{$jsonViewerId}').textContent = '展开';
- document.getElementById('{$jsonViewerId}').classList.add('collapsed');
- document.getElementById('{$jsonViewerId}').style.maxHeight = '200px';
- });
- </script>
- </div>
- HTML;
- // 创建卡片
- $card = new Card($title, $html);
- // 添加原始JSON链接
- $card->tool('<a href="/json/'.$key.'.json" target="_blank" class="btn btn-sm btn-default">查看原始JSON</a>');
- return $content
- ->title('配置表查看')
- ->description($title)
- ->body($card);
- } catch (\Exception $e) {
- // 返回错误响应
- return $content
- ->title('错误')
- ->description('配置表查看')
- ->body(new Card('错误', '获取配置表数据失败: ' . $e->getMessage()));
- }
- }
- /**
- * 创建JSON查看器
- *
- * @param mixed $data 要显示的数据(数组或对象)
- * @return string
- */
- protected function createJsonViewer($data)
- {
- // 生成唯一ID,避免多个查看器冲突
- $viewerId = 'json-viewer-' . uniqid();
- // 确保数据是格式化的JSON字符串
- $jsonString = is_string($data) ? $data : json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
- // 转义HTML特殊字符
- $escapedJson = htmlspecialchars($jsonString, ENT_QUOTES, 'UTF-8');
- // 使用简单的方式显示JSON数据
- $html = <<<HTML
- <div id="{$viewerId}" class="json-viewer">
- <style>
- .json-viewer {
- font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
- font-size: 14px;
- line-height: 1.5;
- background-color: #f8f9fa;
- border-radius: 4px;
- padding: 15px;
- overflow: auto;
- max-height: 80vh;
- }
- .json-viewer pre {
- margin: 0;
- padding: 0;
- white-space: pre-wrap;
- word-wrap: break-word;
- }
- /* 工具栏样式 */
- .json-toolbar {
- margin-bottom: 10px;
- display: flex;
- gap: 10px;
- }
- .json-toolbar button {
- padding: 5px 10px;
- background-color: #f0f0f0;
- border: 1px solid #ddd;
- border-radius: 4px;
- cursor: pointer;
- }
- .json-toolbar button:hover {
- background-color: #e0e0e0;
- }
- /* JSON语法高亮 */
- .json-key { color: #a52a2a; }
- .json-string { color: #008000; }
- .json-number { color: #0000ff; }
- .json-boolean { color: #b22222; }
- .json-null { color: #808080; }
- /* 搜索高亮 */
- .json-highlight {
- background-color: #ffff00;
- padding: 2px;
- border-radius: 2px;
- }
- /* 折叠/展开控件样式 */
- .json-toggle {
- cursor: pointer;
- user-select: none;
- }
- .json-toggle:before {
- content: "▼";
- display: inline-block;
- margin-right: 5px;
- color: #555;
- font-size: 10px;
- }
- .json-toggle.collapsed:before {
- content: "►";
- }
- .json-collapsed {
- display: none;
- }
- .json-placeholder {
- color: #777;
- font-style: italic;
- }
- </style>
- <div class="json-toolbar">
- <input type="text" id="{$viewerId}-search" placeholder="搜索..." style="padding: 5px; margin-right: 10px; width: 200px;">
- <button id="{$viewerId}-expand-all-btn">展开全部</button>
- <button id="{$viewerId}-collapse-all-btn">折叠全部</button>
- <button id="{$viewerId}-copy-json-btn">复制JSON</button>
- </div>
- <pre id="{$viewerId}-content">{$escapedJson}</pre>
- <script>
- $(document).ready(function() {
- // 获取当前查看器的ID
- var viewerId = '{$viewerId}';
- // 解析JSON并添加折叠功能
- function processJSON() {
- try {
- // 获取原始JSON文本
- var jsonContent = document.getElementById(viewerId + '-content');
- var jsonText = jsonContent.textContent;
- var jsonObj = JSON.parse(jsonText);
- // 将JSON对象转换为HTML
- var html = formatJSON(jsonObj, 0);
- jsonContent.innerHTML = html;
- // 添加折叠/展开事件处理
- $('#' + viewerId + ' .json-toggle').click(function() {
- $(this).toggleClass('collapsed');
- var target = $(this).next('.json-collapsible');
- target.toggleClass('json-collapsed');
- // 如果折叠,显示占位符
- var placeholder = $(this).next().next('.json-placeholder');
- if (placeholder.length) {
- placeholder.toggle();
- }
- });
- // 默认折叠所有嵌套超过1层的对象
- collapseLevel(2);
- } catch (e) {
- console.error('JSON解析错误:', e);
- // 如果解析失败,回退到简单的语法高亮
- simpleHighlight();
- }
- }
- // 简单的语法高亮(作为备选方案)
- function simpleHighlight() {
- var jsonContent = document.getElementById(viewerId + '-content');
- var jsonText = jsonContent.textContent;
- // 使用简单的正则表达式进行高亮
- var highlighted = jsonText
- // 高亮键
- .replace(/"([^"]+)"(?=\s*:)/g, '<span class="json-key">"$1"</span>')
- // 高亮字符串值
- .replace(/:\s*"([^"]*)"/g, ': <span class="json-string">"$1"</span>')
- // 高亮数字
- .replace(/:\s*(-?\d+(\.\d+)?)/g, ': <span class="json-number">$1</span>')
- // 高亮布尔值和null
- .replace(/:\s*(true|false|null)/g, ': <span class="json-boolean">$1</span>');
- jsonContent.innerHTML = highlighted;
- }
- // 格式化JSON对象为HTML
- function formatJSON(obj, level) {
- var indent = Array(level + 1).join(' '); // 兼容性更好的缩进方法
- var html = '';
- if (obj === null) {
- return '<span class="json-null">null</span>';
- }
- if (typeof obj === 'boolean') {
- return '<span class="json-boolean">' + obj + '</span>';
- }
- if (typeof obj === 'number') {
- return '<span class="json-number">' + obj + '</span>';
- }
- if (typeof obj === 'string') {
- return '<span class="json-string">"' + escapeHTML(obj) + '"</span>';
- }
- if (Array.isArray(obj)) {
- if (obj.length === 0) {
- return '[]';
- }
- html += '<span class="json-toggle"></span>[<span class="json-collapsible">';
- for (var i = 0; i < obj.length; i++) {
- html += '\\n' + indent + ' ' + formatJSON(obj[i], level + 1);
- if (i < obj.length - 1) {
- html += ',';
- }
- }
- html += '\\n' + indent + '</span>]<span class="json-placeholder json-collapsed"> [...] </span>';
- return html;
- }
- if (typeof obj === 'object') {
- var keys = Object.keys(obj);
- if (keys.length === 0) {
- return '{}';
- }
- html += '<span class="json-toggle"></span>{<span class="json-collapsible">';
- for (var i = 0; i < keys.length; i++) {
- var key = keys[i];
- html += '\\n' + indent + ' <span class="json-key">"' + escapeHTML(key) + '"</span>: ' + formatJSON(obj[key], level + 1);
- if (i < keys.length - 1) {
- html += ',';
- }
- }
- html += '\\n' + indent + '</span>}<span class="json-placeholder json-collapsed"> {...} </span>';
- return html;
- }
- return String(obj);
- }
- // 转义HTML特殊字符
- function escapeHTML(str) {
- return str
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- }
- // 折叠指定层级以下的所有元素
- function collapseLevel(level) {
- $('#' + viewerId + ' .json-toggle').each(function() {
- // 计算当前元素的嵌套层级
- var currentLevel = $(this).parents('.json-collapsible').length;
- if (currentLevel >= level - 1) {
- if (!$(this).hasClass('collapsed')) {
- $(this).addClass('collapsed');
- $(this).next('.json-collapsible').addClass('json-collapsed');
- $(this).next().next('.json-placeholder').show();
- }
- }
- });
- }
- // 展开所有元素
- function expandAll() {
- $('#' + viewerId + ' .json-toggle').removeClass('collapsed');
- $('#' + viewerId + ' .json-collapsible').removeClass('json-collapsed');
- $('#' + viewerId + ' .json-placeholder').hide();
- }
- // 折叠所有元素
- function collapseAll() {
- $('#' + viewerId + ' .json-toggle').addClass('collapsed');
- $('#' + viewerId + ' .json-collapsible').addClass('json-collapsed');
- $('#' + viewerId + ' .json-placeholder').show();
- }
- // 搜索并高亮匹配的文本
- function searchAndHighlight(searchText) {
- try {
- // 创建正则表达式,忽略大小写
- var regex = new RegExp(searchText, 'gi');
- // 搜索所有文本节点
- $('#' + viewerId + ' .json-collapsible').each(function() {
- var $this = $(this);
- var content = $this.text();
- if (content.match(regex)) {
- // 展开包含匹配文本的节点
- var $toggle = $this.prev('.json-toggle');
- if ($toggle.hasClass('collapsed')) {
- $toggle.removeClass('collapsed');
- $this.removeClass('json-collapsed');
- $this.next('.json-placeholder').hide();
- }
- // 展开所有父节点
- $this.parents('.json-collapsible').each(function() {
- var $parentToggle = $(this).prev('.json-toggle');
- if ($parentToggle.hasClass('collapsed')) {
- $parentToggle.removeClass('collapsed');
- $(this).removeClass('json-collapsed');
- $(this).next('.json-placeholder').hide();
- }
- });
- }
- });
- // 高亮匹配的文本
- $('#' + viewerId + ' .json-key, #' + viewerId + ' .json-string, #' + viewerId + ' .json-number, #' + viewerId + ' .json-boolean, #' + viewerId + ' .json-null').each(function() {
- var $this = $(this);
- var content = $this.text();
- if (content.match(regex)) {
- var highlightedContent = content.replace(regex, function(match) {
- return '<span class="json-highlight">' + match + '</span>';
- });
- $this.html(highlightedContent);
- }
- });
- // 滚动到第一个匹配项
- var $firstHighlight = $('#' + viewerId + ' .json-highlight').first();
- if ($firstHighlight.length) {
- var container = document.getElementById(viewerId);
- var highlightOffset = $firstHighlight.offset().top;
- var containerOffset = $(container).offset().top;
- var scrollTop = highlightOffset - containerOffset - 100;
- $(container).animate({
- scrollTop: scrollTop
- }, 300);
- }
- } catch (e) {
- console.error('搜索错误:', e);
- }
- }
- // 初始化
- processJSON();
- // 绑定工具栏按钮事件
- $('#' + viewerId + '-expand-all-btn').click(expandAll);
- $('#' + viewerId + '-collapse-all-btn').click(collapseAll);
- // 搜索功能
- $('#' + viewerId + '-search').on('input', function() {
- var searchText = $(this).val().trim();
- // 移除所有高亮
- $('#' + viewerId + ' .json-highlight').removeClass('json-highlight');
- if (searchText.length > 0) {
- // 搜索并高亮匹配的文本
- searchAndHighlight(searchText);
- }
- });
- // 复制JSON按钮
- $('#' + viewerId + '-copy-json-btn').click(function() {
- var jsonContent = document.getElementById(viewerId + '-content');
- var jsonText = jsonContent.textContent || jsonContent.innerText;
- // 创建一个临时元素来存储纯文本JSON
- var tempTextarea = $('<textarea>');
- $('body').append(tempTextarea);
- // 尝试解析和格式化JSON
- try {
- var jsonObj = JSON.parse(jsonText.replace(/[\u0000-\u001F]+/g, ' '));
- tempTextarea.val(JSON.stringify(jsonObj, null, 4));
- } catch (e) {
- // 如果解析失败,使用原始文本
- tempTextarea.val(jsonText);
- }
- tempTextarea.select();
- document.execCommand('copy');
- tempTextarea.remove();
- alert('JSON已复制到剪贴板');
- });
- });
- </script>
- </div>
- HTML;
- return $html;
- }
- }
|