47 Commits

Author SHA1 Message Date
ccdf8971d8 set v 1.1.0 2026-01-02 19:53:44 +05:00
c265c29425 Merge branch 'voice_test' into feat/VersionsExplorer 2026-01-02 19:52:44 +05:00
f617940c44 add head avatar to voice 2026-01-02 19:50:06 +05:00
53879dfaac Merge branch 'voice_test' of https://git.popa-popa.ru/DIKER/popa-launcher into voice_test 2026-01-02 19:22:20 +05:00
8520f2120d voice v2 2026-01-02 19:22:11 +05:00
4944a18076 add voice button in TopBar 2026-01-02 17:23:23 +05:00
a76a8b5656 voice v1.1 2026-01-02 16:23:26 +05:00
d90ef2e535 voice test 2026-01-02 15:54:58 +05:00
6f5793a9fd set v1.0.7 2026-01-01 22:44:07 +05:00
1348b39a4c fix 2026-01-01 22:43:07 +05:00
c77d173fce set v1.0.6 2026-01-01 19:42:52 +05:00
687e2db51b add neoforge modpacks support 2026-01-01 17:45:11 +05:00
5dc1744cfd add set description in sell item 2025-12-29 22:31:20 +05:00
614f6d0a25 set v1.0.5 2025-12-29 20:31:55 +05:00
8d9f55f601 fix marketplace 2025-12-29 20:21:46 +05:00
c449e99542 set v1.0.4 2025-12-29 19:17:50 +05:00
dc4fe3b18e add info for item 2025-12-29 19:17:08 +05:00
e0889cfaea add essential tooltip 2025-12-29 16:54:05 +05:00
b1f378c5a8 v1.0.3(add quick launch, redesign shop, add new directory game) 2025-12-29 16:49:27 +05:00
287116103d redesign minor 2025-12-29 10:04:58 +05:00
2777e9b008 minor redesign shop(завтра доделаю) 2025-12-29 00:04:23 +05:00
1a78b95524 add icon 2025-12-28 14:36:29 +05:00
4efa8c4437 stylize Notifier update 2025-12-28 14:32:39 +05:00
a4a10c164e Merge branch 'feat/VersionsExplorer' of https://git.popa-popa.ru/DIKER/popa-launcher into feat/VersionsExplorer 2025-12-28 14:12:09 +05:00
8003e3567a add commands tab in shop 2025-12-28 14:12:07 +05:00
c5ea4ca38f fix build 2025-12-22 19:45:03 +05:00
7fbb9fa78a fix tray 2025-12-22 18:29:47 +05:00
6caa563b41 add websocket 2025-12-22 16:42:37 +05:00
4b8e535c58 redesign login/registration. add autologin from registration. add 'continue' register from accept acc 2025-12-21 01:15:53 +05:00
779f8f779d add promo to News 2025-12-20 21:12:52 +05:00
f8b358d9bd add new page promocode 2025-12-20 20:49:49 +05:00
5f23adc9ae add secret page 2025-12-20 19:32:47 +05:00
b1d369e49d Merge branch 'feat/VersionsExplorer' of https://git.popa-popa.ru/DIKER/popa-launcher into feat/VersionsExplorer 2025-12-20 17:45:19 +05:00
acd46bb31c fix qr code auth 2025-12-20 17:45:16 +05:00
26f0865d2e minorfix 2025-12-20 17:32:22 +05:00
d25cda62df Merge branch 'feat/VersionsExplorer' of https://git.popa-popa.ru/DIKER/popa-launcher into feat/VersionsExplorer 2025-12-20 17:11:25 +05:00
64b6129713 add qr code auth 2025-12-20 17:11:23 +05:00
6edf7ca7d0 redesign marketplace + fix marketplace 2025-12-20 17:06:46 +05:00
3aa99e7262 fix registration on production 2025-12-19 21:45:24 +05:00
fef89513c2 круто 2025-12-17 13:16:59 +05:00
24423173a6 minor redesign inventory + add functions 2025-12-17 00:12:23 +05:00
70ec57d6fb test fix authorization 2025-12-16 17:09:51 +05:00
c15c36891e add inventory and change cases 2025-12-16 15:30:40 +05:00
6db213d602 add tray and add settings 2025-12-16 00:30:00 +05:00
cd7ad5039e add settings, redesign settings panel 2025-12-15 22:41:38 +05:00
6adc64dab8 Merge branch 'feat/VersionsExplorer' of https://git.popa-popa.ru/DIKER/popa-launcher into feat/VersionsExplorer 2025-12-15 00:47:20 +05:00
11a203cb8f new function settings 2025-12-15 00:37:45 +05:00
64 changed files with 10028 additions and 1814 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 361 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

164
package-lock.json generated
View File

@ -8,7 +8,6 @@
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
"@electron/notarize": "^3.0.0",
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1",
"@mui/icons-material": "^7.2.0",
@ -28,10 +27,12 @@
"qr-code-styling": "^1.9.2",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-icons": "^5.5.0",
"react-markdown": "^10.1.0",
"react-router-dom": "^7.3.0",
"remark-gfm": "^4.0.1",
"skinview3d": "^3.4.1",
"socket.io-client": "^4.8.1",
"stream-browserify": "^3.0.0",
"three": "^0.178.0",
"util": "^0.12.5",
@ -2273,19 +2274,6 @@
"node": ">=12.13.0"
}
},
"node_modules/@electron/notarize": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/@electron/notarize/-/notarize-3.1.1.tgz",
"integrity": "sha512-uQQSlOiJnqRkTL1wlEBAxe90nVN/Fc/hEmk0bqpKk8nKjV1if/tXLHKUPePtv9Xsx90PtZU8aidx5lAiOpjkQQ==",
"license": "MIT",
"dependencies": {
"debug": "^4.4.0",
"promise-retry": "^2.0.1"
},
"engines": {
"node": ">= 22.12.0"
}
},
"node_modules/@electron/osx-sign": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/@electron/osx-sign/-/osx-sign-1.3.1.tgz",
@ -4464,6 +4452,12 @@
"@sinonjs/commons": "^3.0.0"
}
},
"node_modules/@socket.io/component-emitter": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==",
"license": "MIT"
},
"node_modules/@svgr/babel-plugin-add-jsx-attribute": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/@svgr/babel-plugin-add-jsx-attribute/-/babel-plugin-add-jsx-attribute-8.0.0.tgz",
@ -10615,6 +10609,66 @@
"once": "^1.4.0"
}
},
"node_modules/engine.io-client": {
"version": "6.6.3",
"resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.3.tgz",
"integrity": "sha512-T0iLjnyNWahNyv/lcjS2y4oE358tVS/SYQNxYXGAJ9/GLgH4VCvOQ/mhTjqU88mLZCQgiG8RIegFHYCdVC+j5w==",
"license": "MIT",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.3.1",
"engine.io-parser": "~5.2.1",
"ws": "~8.17.1",
"xmlhttprequest-ssl": "~2.1.1"
}
},
"node_modules/engine.io-client/node_modules/debug": {
"version": "4.3.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
"integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/engine.io-client/node_modules/ws": {
"version": "8.17.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz",
"integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/engine.io-parser": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz",
"integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/enhanced-resolve": {
"version": "0.9.1",
"resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-0.9.1.tgz",
@ -10678,6 +10732,7 @@
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/err-code/-/err-code-2.0.3.tgz",
"integrity": "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==",
"dev": true,
"license": "MIT"
},
"node_modules/error-ex": {
@ -20087,6 +20142,7 @@
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/promise-retry/-/promise-retry-2.0.1.tgz",
"integrity": "sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==",
"dev": true,
"license": "MIT",
"dependencies": {
"err-code": "^2.0.2",
@ -20357,6 +20413,15 @@
"react": "^19.2.1"
}
},
"node_modules/react-icons": {
"version": "5.5.0",
"resolved": "https://registry.npmjs.org/react-icons/-/react-icons-5.5.0.tgz",
"integrity": "sha512-MEFcXdkP3dLo8uumGI5xN3lDFNsRtrjbOEKDLD7yv76v4wpnEq2Lt2qeHaQOr34I/wPN3s3+N08WkQ+CW37Xiw==",
"license": "MIT",
"peerDependencies": {
"react": "*"
}
},
"node_modules/react-is": {
"version": "19.2.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.1.tgz",
@ -20988,6 +21053,7 @@
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",
"integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 4"
@ -22094,6 +22160,68 @@
"tslib": "^2.0.3"
}
},
"node_modules/socket.io-client": {
"version": "4.8.1",
"resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.1.tgz",
"integrity": "sha512-hJVXfu3E28NmzGk8o1sHhN3om52tRvwYeidbj7xKy2eIIse5IoKX3USlS6Tqt3BHAtflLIkCQBkzVrEEfWUyYQ==",
"license": "MIT",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.3.2",
"engine.io-client": "~6.6.1",
"socket.io-parser": "~4.2.4"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/socket.io-client/node_modules/debug": {
"version": "4.3.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
"integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/socket.io-parser": {
"version": "4.2.4",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz",
"integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==",
"license": "MIT",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.3.1"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/socket.io-parser/node_modules/debug": {
"version": "4.3.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
"integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/sockjs": {
"version": "0.3.24",
"resolved": "https://registry.npmjs.org/sockjs/-/sockjs-0.3.24.tgz",
@ -25073,6 +25201,14 @@
"dev": true,
"license": "MIT"
},
"node_modules/xmlhttprequest-ssl": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz",
"integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",

View File

@ -105,7 +105,6 @@
}
},
"dependencies": {
"@electron/notarize": "^3.0.0",
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1",
"@mui/icons-material": "^7.2.0",
@ -125,10 +124,12 @@
"qr-code-styling": "^1.9.2",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-icons": "^5.5.0",
"react-markdown": "^10.1.0",
"react-router-dom": "^7.3.0",
"remark-gfm": "^4.0.1",
"skinview3d": "^3.4.1",
"socket.io-client": "^4.8.1",
"stream-browserify": "^3.0.0",
"three": "^0.178.0",
"util": "^0.12.5",
@ -205,7 +206,6 @@
"productName": "popa-launcher",
"appId": "org.erb.ElectronReact",
"asar": true,
"afterSign": ".erb/scripts/notarize.js",
"asarUnpack": "**\\*.{node,dll}",
"files": [
"dist",
@ -262,7 +262,7 @@
],
"publish": {
"provider": "generic",
"url": "https://git.popa-popa.ru/DIKER/popa-launcher/releases/download/v${version}",
"url": "https://git.popa-popa.ru/DIKER/popa-launcher/releases/download/latest",
"channel": "latest",
"requestHeaders": {
"Authorization": "token ${env.GH_TOKEN}"

View File

@ -1,12 +1,12 @@
{
"name": "popa-launcher",
"version": "1.0.0",
"version": "1.1.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "popa-launcher",
"version": "1.0.0",
"version": "1.1.0",
"hasInstallScript": true,
"license": "MIT"
}

View File

@ -1,6 +1,6 @@
{
"name": "popa-launcher",
"version": "1.0.0",
"version": "1.1.0",
"description": "Popa Launcher",
"license": "MIT",
"author": {

View File

@ -35,8 +35,14 @@ export class AuthService {
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Ошибка авторизации: ${response.status} ${errorText}`);
let detail = '';
try {
const data = await response.json(); // FastAPI: { detail: "..." }
detail = data?.detail || '';
} catch {
detail = await response.text();
}
throw new Error(detail || `HTTP ${response.status}`);
}
const auth = await response.json();

View File

@ -9,7 +9,7 @@
* `./src/main.js` using webpack. This gives us some performance wins.
*/
import path from 'path';
import { app, BrowserWindow, shell, ipcMain } from 'electron';
import { app, BrowserWindow, shell, ipcMain, Tray, Menu, nativeImage, type MenuItemConstructorOptions } from 'electron';
import { autoUpdater } from 'electron-updater';
import log from 'electron-log';
import MenuBuilder from './menu';
@ -58,8 +58,128 @@ class AppUpdater {
}
}
let launcherSettings = {
autoLaunch: false,
startInTray: false,
closeToTray: true,
};
const ensureTray = () => {
if (tray) return;
const RESOURCES_PATH = app.isPackaged
? path.join(process.resourcesPath, 'assets')
: path.join(__dirname, '../../assets');
const getAssetPath = (...paths: string[]) => path.join(RESOURCES_PATH, ...paths);
const trayIconPath = getAssetPath('pop-popa.png'); // или 'Icons/popa-popa.png'
const trayImage = nativeImage.createFromPath(trayIconPath);
tray = new Tray(trayImage);
tray.setToolTip('popa-launcher');
tray.on('click', () => {
if (!mainWindow) return;
mainWindow.show();
mainWindow.focus();
});
const menu = Menu.buildFromTemplate([
{
label: 'Открыть',
click: () => {
if (!mainWindow) return;
mainWindow.show();
mainWindow.focus();
},
},
{ type: 'separator' },
{
label: 'Выход',
click: () => {
isQuitting = true;
if (mainWindow) {
mainWindow.removeAllListeners('close');
mainWindow.destroy(); // ⬅ КЛЮЧЕВО
}
app.quit();
},
},
]);
tray.setContextMenu(menu);
tray.on('double-click', () => {
if (!mainWindow) return;
mainWindow.show();
mainWindow.focus();
});
};
const applyLoginItemSettings = () => {
// Работает на Windows/macOS. На Linux зависит от окружения.
app.setLoginItemSettings({
openAtLogin: launcherSettings.autoLaunch,
openAsHidden: launcherSettings.startInTray, // чтобы стартовал скрытым
});
};
let tray: Tray | null = null;
let isAuthed = false;
let isQuitting = false;
let mainWindow: BrowserWindow | null = null;
function buildTrayMenu() {
const icon = nativeImage.createFromPath(
app.isPackaged
? path.join(__dirname, '../../assets/popa-popa.png')
: path.join(process.resourcesPath, 'assets', 'popa-popa.png'),
);
const template: MenuItemConstructorOptions[] = [
{ label: 'popa-popa', enabled: false, icon },
{ type: 'separator' },
...(isAuthed
? ([
{ label: 'Новости', click: () => mainWindow?.webContents.send('tray-navigate', '/news') },
{ label: 'Версии', click: () => mainWindow?.webContents.send('tray-navigate', '/') },
{ label: 'Магазин', click: () => mainWindow?.webContents.send('tray-navigate', '/shop') },
{ label: 'Рынок', click: () => mainWindow?.webContents.send('tray-navigate', '/marketplace') },
{ label: 'Профиль', click: () => mainWindow?.webContents.send('tray-navigate', '/profile') },
{ label: 'Настройки', click: () => mainWindow?.webContents.send('tray-navigate', '/settings') },
{ label: 'Ежедневная награда', click: () => mainWindow?.webContents.send('tray-navigate', '/daily') },
{ label: 'Ежедневные квесты', click: () => mainWindow?.webContents.send('tray-navigate', '/dailyquests') },
{ type: 'separator' },
{ label: 'Выйти', click: () => mainWindow?.webContents.send('tray-logout') },
] as MenuItemConstructorOptions[])
: ([
{ label: 'Войти', click: () => mainWindow?.webContents.send('tray-navigate', '/login') },
] as MenuItemConstructorOptions[])),
{ type: 'separator' },
{ label: 'Показать', click: () => { mainWindow?.show(); mainWindow?.focus(); } },
{
label: 'Выход',
click: () => {
isQuitting = true;
if (mainWindow) {
mainWindow.removeAllListeners('close');
mainWindow.destroy(); // ⬅ КЛЮЧЕВО
}
app.quit();
},
},
];
tray?.setContextMenu(Menu.buildFromTemplate(template));
}
ipcMain.on('ipc-example', async (event, arg) => {
const msgTemplate = (pingPong: string) => `IPC test: ${pingPong}`;
console.log(msgTemplate(arg));
@ -101,6 +221,34 @@ const installExtensions = async () => {
.catch(console.log);
};
ipcMain.handle('apply-launcher-settings', (_e, payload) => {
launcherSettings = {
...launcherSettings,
autoLaunch: Boolean(payload?.autoLaunch),
startInTray: Boolean(payload?.startInTray),
closeToTray: payload?.closeToTray === false ? false : true,
};
applyLoginItemSettings();
// если попросили трей — убедимся что он есть
if (launcherSettings.startInTray || launcherSettings.closeToTray) {
ensureTray();
}
// если окно уже создано и ещё не показано — решаем, показывать или нет
if (mainWindow) {
if (launcherSettings.startInTray) {
// оставляем скрытым
mainWindow.hide();
} else {
mainWindow.show();
}
}
return { ok: true };
});
const createWindow = async () => {
if (isDebug) {
await installExtensions();
@ -110,6 +258,8 @@ const createWindow = async () => {
? path.join(process.resourcesPath, 'assets')
: path.join(__dirname, '../../assets');
ensureTray();
const getAssetPath = (...paths: string[]): string => {
return path.join(RESOURCES_PATH, ...paths);
};
@ -119,9 +269,9 @@ const createWindow = async () => {
width: 1024,
height: 850,
autoHideMenuBar: true,
resizable: true,
resizable: false,
frame: false,
icon: getAssetPath('icon.png'),
icon: getAssetPath('popa-popa.png'),
webPreferences: {
webSecurity: false,
preload: app.isPackaged
@ -130,6 +280,13 @@ const createWindow = async () => {
},
});
mainWindow.on('close', (e) => {
if (!isQuitting && launcherSettings.closeToTray) {
e.preventDefault();
mainWindow?.hide();
}
});
mainWindow.loadURL(resolveHtmlPath('index.html'));
mainWindow.on('ready-to-show', () => {
@ -139,7 +296,10 @@ const createWindow = async () => {
if (process.env.START_MINIMIZED) {
mainWindow.minimize();
} else {
mainWindow.show();
setTimeout(() => {
if (!mainWindow) return;
if (!launcherSettings.startInTray) mainWindow.show();
}, 2000);
}
});
@ -178,6 +338,10 @@ app.on('window-all-closed', () => {
}
});
app.on('before-quit', () => {
isQuitting = true;
});
app
.whenReady()
.then(() => {
@ -193,3 +357,9 @@ app
ipcMain.handle('install-update', () => {
autoUpdater.quitAndInstall();
});
ipcMain.handle('auth-changed', (_e, payload: { isAuthed: boolean }) => {
isAuthed = Boolean(payload?.isAuthed);
buildTrayMenu();
return true;
});

View File

@ -6,19 +6,19 @@ import extract from 'extract-zip';
import { launch, Version, diagnose } from '@xmcl/core';
import { execSync } from 'child_process';
import {
installDependencies,
installFabric,
getFabricLoaders,
getVersionList,
install,
installTask,
installDependenciesTask,
installNeoForged,
} from '@xmcl/installer';
import { Dispatcher, Agent } from 'undici';
import { Agent } from 'undici';
import { spawn } from 'child_process';
import { AuthService } from './auth-service';
import { API_BASE_URL } from '../renderer/api';
app.setName('.popa-popa');
// const CDN = 'https://cdn.minecraft.popa-popa.ru';
// const DOWNLOAD_OPTIONS = {
@ -413,8 +413,8 @@ export function initMinecraftHandlers() {
preserveFiles = [], // Новый параметр: список файлов/папок для сохранения
} = options || {};
const appPath = path.dirname(app.getPath('exe'));
const minecraftDir = path.join(appPath, '.minecraft');
const userDataPath = app.getPath('userData');
const minecraftDir = path.join(app.getPath('userData'), 'minecraft');
const versionsDir = path.join(minecraftDir, 'versions');
const versionFilePath = path.join(minecraftDir, versionFileName);
@ -437,7 +437,7 @@ export function initMinecraftHandlers() {
};
}
const tempDir = path.join(appPath, 'temp');
const tempDir = path.join(userDataPath, 'temp');
const packDir = path.join(versionsDir, packName); // Директория пакета
// Создаем/очищаем временную директорию
@ -544,22 +544,24 @@ export function initMinecraftHandlers() {
username,
memory = 4096,
baseVersion = '1.21.4',
fabricVersion = '0.16.14',
fabricVersion = null,
neoForgeVersion = null,
packName = 'Comfort', // имя сборки (папка с модами)
versionToLaunchOverride = '', // переопределение версии для запуска (например, 1.21.10 для ванили)
serverIp = 'popa-popa.ru',
serverPort,
isVanillaVersion = false,
loaderType = 'fabric',
} = gameConfig || {};
const appPath = path.dirname(app.getPath('exe'));
const minecraftDir = path.join(appPath, '.minecraft');
const userDataPath = app.getPath('userData');
const minecraftDir = path.join(app.getPath('userData'), 'minecraft');
const versionsDir = path.join(minecraftDir, 'versions');
fs.mkdirSync(versionsDir, { recursive: true });
// gamePath:
// - ваниль → .minecraft
// - модпак → .minecraft/versions/Comfort (или другое packName)
// - ваниль → .popa-popa
// - модпак → .popa-popa/versions/Comfort (или другое packName)
const packDir = isVanillaVersion
? minecraftDir
: path.join(versionsDir, packName);
@ -588,23 +590,47 @@ export function initMinecraftHandlers() {
// Ваниль — запускаем baseVersion (или override)
versionToLaunch = effectiveBaseVersion;
} else {
// Модпак — запускаем именно fabric-версию
const fabricId = `${effectiveBaseVersion}-fabric${fabricVersion}`;
if (versionsContents.includes(fabricId)) {
versionToLaunch = fabricId;
// Определяем ID версии в зависимости от типа загрузчика
if (loaderType === 'neoforge' && neoForgeVersion) {
// NeoForge создает версию с ID "neoforge-{version}"
const neoForgeId = `neoforge-${neoForgeVersion}`;
// Проверяем, существует ли такая версия
if (versionsContents.includes(neoForgeId)) {
versionToLaunch = neoForgeId;
} else {
// Если не существует, пробуем комбинированный ID для совместимости
const combinedId = `${effectiveBaseVersion}-neoforge${neoForgeVersion}`;
versionToLaunch = combinedId;
// Логируем для отладки
console.log(
'NeoForge версия не найдена, используем комбинированный ID:',
combinedId,
);
}
} else if (fabricVersion) {
// Fabric создает версию с ID "{minecraftVersion}-fabric{fabricVersion}"
const fabricId = `${effectiveBaseVersion}-fabric${fabricVersion}`;
if (versionsContents.includes(fabricId)) {
versionToLaunch = fabricId;
} else {
versionToLaunch = fabricId;
}
} else {
// даже если папки нет — installFabric её создаст
versionToLaunch = fabricId;
versionToLaunch = effectiveBaseVersion;
}
}
}
console.log('isVanillaVersion:', isVanillaVersion);
console.log('baseVersion:', baseVersion);
console.log('effectiveBaseVersion:', effectiveBaseVersion);
console.log('fabricVersion:', fabricVersion);
console.log('versionToLaunch:', versionToLaunch);
console.log('packDir:', packDir);
console.log('Конфигурация:', {
loaderType,
neoForgeVersion,
fabricVersion,
effectiveBaseVersion,
versionToLaunch,
versionsContents,
});
// --- Поиск Java ---
event.sender.send('installation-status', {
@ -703,35 +729,77 @@ export function initMinecraftHandlers() {
}
// --- 2. Установка Fabric (только для модпаков) ---
if (!isVanillaVersion && fabricVersion) {
try {
event.sender.send('installation-status', {
step: 'fabric-install',
message: `Установка Fabric ${fabricVersion}...`,
});
if (!isVanillaVersion) {
if (loaderType === 'neoforge' && neoForgeVersion) {
try {
event.sender.send('installation-status', {
step: 'neoforge-install',
message: `Установка NeoForge ${neoForgeVersion}...`,
});
event.sender.send(
'overall-progress',
getGlobalProgress('fabric-install', 0),
);
event.sender.send(
'overall-progress',
getGlobalProgress('fabric-install', 0),
);
console.log('installFabric:', {
minecraftVersion: effectiveBaseVersion,
fabricVersion,
minecraftDir,
});
console.log('installNeoForged:', {
project: 'neoforge',
version: neoForgeVersion,
minecraftVersion: effectiveBaseVersion,
minecraftDir,
});
await installFabric({
minecraftVersion: effectiveBaseVersion,
version: fabricVersion,
minecraft: minecraftDir,
});
event.sender.send(
'overall-progress',
getGlobalProgress('fabric-install', 1),
);
} catch (error) {
console.log('Ошибка при установке Fabric, продолжаем:', error);
// Установка NeoForge
await installNeoForged('neoforge', neoForgeVersion, minecraftDir, {
minecraft: effectiveBaseVersion,
java: javaPath,
side: 'client',
});
console.log('NeoForge установлен успешно!');
event.sender.send(
'overall-progress',
getGlobalProgress('fabric-install', 1),
);
} catch (error) {
console.error('Ошибка при установке NeoForge:', error);
event.sender.send('installation-status', {
step: 'neoforge-error',
message: `Ошибка установки NeoForge: ${error.message}`,
});
}
} else if (fabricVersion) {
// Существующий код для Fabric
try {
event.sender.send('installation-status', {
step: 'fabric-install',
message: `Установка Fabric ${fabricVersion}...`,
});
event.sender.send(
'overall-progress',
getGlobalProgress('fabric-install', 0),
);
console.log('installFabric:', {
minecraftVersion: effectiveBaseVersion,
fabricVersion,
minecraftDir,
});
await installFabric({
minecraftVersion: effectiveBaseVersion,
version: fabricVersion,
minecraft: minecraftDir,
});
event.sender.send(
'overall-progress',
getGlobalProgress('fabric-install', 1),
);
} catch (error) {
console.log('Ошибка при установке Fabric, продолжаем:', error);
}
}
}
@ -802,7 +870,7 @@ export function initMinecraftHandlers() {
}
// --- authlib-injector ---
const authlibPath = await ensureAuthlibInjectorExists(appPath);
const authlibPath = await ensureAuthlibInjectorExists(userDataPath);
console.log('authlibPath:', authlibPath);
event.sender.send('installation-status', {
@ -930,8 +998,8 @@ export function initMinecraftHandlers() {
// Добавьте в функцию initMinecraftHandlers или создайте новую
ipcMain.handle('get-pack-files', async (event, packName) => {
try {
const appPath = path.dirname(app.getPath('exe'));
const minecraftDir = path.join(appPath, '.minecraft');
const userDataPath = app.getPath('userData');
const minecraftDir = path.join(app.getPath('userData'), 'minecraft');
const packDir = path.join(minecraftDir, 'versions', packName);
if (!fs.existsSync(packDir)) {
@ -974,8 +1042,8 @@ export function initMinecraftHandlers() {
// Сначала создаем общую функцию для получения установленных версий
function getInstalledVersions() {
try {
const appPath = path.dirname(app.getPath('exe'));
const minecraftDir = path.join(appPath, '.minecraft');
const userDataPath = app.getPath('userData');
const minecraftDir = path.join(app.getPath('userData'), 'minecraft');
const versionsDir = path.join(minecraftDir, 'versions');
if (!fs.existsSync(versionsDir)) {
@ -989,12 +1057,17 @@ export function initMinecraftHandlers() {
const versionPath = path.join(versionsDir, item);
if (!fs.statSync(versionPath).isDirectory()) continue;
// ❗ Прячем технические fabric-версии типа 1.21.10-fabric0.18.1
if (item.includes('-fabric')) {
// ❗ Прячем технические версии загрузчиков
if (item.includes('-fabric') || item.includes('neoforge')) {
continue;
}
const versionJsonPath = path.join(versionPath, `${item}.json`);
const files = fs.readdirSync(versionPath);
const jsonFile = files.find((f) => f.endsWith('.json'));
if (!jsonFile) continue;
const versionJsonPath = path.join(versionPath, jsonFile);
let versionInfo = {
id: item,
name: item,
@ -1170,8 +1243,8 @@ export function initPackConfigHandlers() {
// Обработчик для сохранения настроек сборки
ipcMain.handle('save-pack-config', async (event, { packName, config }) => {
try {
const appPath = path.dirname(app.getPath('exe'));
const minecraftDir = path.join(appPath, '.minecraft');
const userDataPath = app.getPath('userData');
const minecraftDir = path.join(app.getPath('userData'), 'minecraft');
const packDir = path.join(minecraftDir, 'versions', packName);
// Создаем папку для сборки, если она не существует
@ -1201,8 +1274,8 @@ export function initPackConfigHandlers() {
// Обработчик для загрузки настроек сборки
ipcMain.handle('load-pack-config', async (event, { packName }) => {
try {
const appPath = path.dirname(app.getPath('exe'));
const minecraftDir = path.join(appPath, '.minecraft');
const userDataPath = app.getPath('userData');
const minecraftDir = path.join(app.getPath('userData'), 'minecraft');
const packDir = path.join(minecraftDir, 'versions', packName);
const configPath = path.join(packDir, CONFIG_FILENAME);
@ -1246,8 +1319,8 @@ export function initPackConfigHandlers() {
// Добавляем после обработчика get-available-versions
ipcMain.handle('get-version-config', async (event, { versionId }) => {
try {
const appPath = path.dirname(app.getPath('exe'));
const minecraftDir = path.join(appPath, '.minecraft');
const userDataPath = app.getPath('userData');
const minecraftDir = path.join(app.getPath('userData'), 'minecraft');
const versionsDir = path.join(minecraftDir, 'versions');
const versionPath = path.join(versionsDir, versionId);
@ -1268,7 +1341,9 @@ ipcMain.handle('get-version-config', async (event, { versionId }) => {
memory: 4096,
baseVersion: '1.21.10',
serverIp: 'popa-popa.ru',
fabricVersion: '0.18.1',
fabricVersion: null,
neoForgeVersion: null,
loaderType: 'fabric', // 'fabric', 'neoforge', 'vanilla'
preserveFiles: ['popa-launcher-config.json'],
};
@ -1280,6 +1355,20 @@ ipcMain.handle('get-version-config', async (event, { versionId }) => {
'https://api.github.com/repos/DIKER0K/Comfort/releases/latest';
config.baseVersion = '1.21.10';
config.fabricVersion = '0.18.1';
config.loaderType = 'fabric';
}
// Если это NeoForge сборка, добавьте соответствующие настройки
if (versionId === 'MyNeoForgePack') {
config.downloadUrl =
'https://github.com/YOUR_USERNAME/YOUR_NEOFORGE_PACK/releases/latest/download/MyNeoForgePack.zip';
config.apiReleaseUrl =
'https://api.github.com/repos/YOUR_USERNAME/YOUR_NEOFORGE_PACK/releases/latest';
config.baseVersion = '1.21.1';
config.fabricVersion = null;
config.neoForgeVersion = '20.6.2';
config.loaderType = 'neoforge';
config.memory = 6144; // NeoForge может требовать больше памяти
}
// Если есть конфигурационный файл, загружаем из него

View File

@ -19,6 +19,10 @@ export type Channels =
| 'overall-progress'
| 'stop-minecraft'
| 'minecraft-started'
| 'apply-launcher-settings'
| 'tray-navigate'
| 'tray-logout'
| 'auth-changed'
| 'minecraft-stopped';
const electronHandler = {
@ -41,6 +45,9 @@ const electronHandler = {
invoke(channel: Channels, ...args: unknown[]): Promise<any> {
return ipcRenderer.invoke(channel, ...args);
},
removeAllListeners(channel: Channels) {
ipcRenderer.removeAllListeners(channel);
},
},
};

View File

@ -12,19 +12,52 @@
url('../../assets/fonts/benzin-bold.svg#benzin-bold') format('svg'); /* Chrome < 4, Legacy iOS */
}
:root {
--ui-scale: 1;
/* SETTINGS NO-BLUR */
.glass {
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
#root {
transform: scale(var(--ui-scale));
transform-origin: top left;
/* компенсация, чтобы после scale не появлялись пустые области/скроллы */
width: calc(100% / var(--ui-scale));
height: calc(100% / var(--ui-scale));
.glass-ui {
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
}
.glass--soft { backdrop-filter: blur(6px); }
.glass--hard { backdrop-filter: blur(20px); }
body.no-blur .glass,
body.no-blur .glass-ui {
backdrop-filter: none;
-webkit-backdrop-filter: none;
}
/* SETTINGS NO-BLUR */
/* SETTINGS REDUCE-MOTION */
/* @media (prefers-reduced-motion: reduce) {
* {
animation-duration: 0.001ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.001ms !important;
}
} */
body.reduce-motion *,
body.reduce-motion *::before,
body.reduce-motion *::after {
animation-duration: 0.001ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.001ms !important;
scroll-behavior: auto !important;
}
/* опционально: убрать ховер-скейлы (если ты их часто используешь) */
body.reduce-motion .no-motion-hover,
body.reduce-motion .no-motion-hover:hover {
transform: none !important;
}
/* SETTINGS REDUCE-MOTION */
body {
position: relative;
color: white;

View File

@ -25,6 +25,12 @@ import { useLocation } from 'react-router-dom';
import DailyReward from './pages/DailyReward';
import DailyQuests from './pages/DailyQuests';
import Settings from './pages/Settings';
import Inventory from './pages/Inventory';
import FakePaymentPage from './pages/FakePaymentPage';
import { TrayBridge } from './utils/TrayBridge';
import { API_BASE_URL } from './api';
import { PromoRedeem } from './pages/PromoRedeem';
import VoicePage from './pages/VoicePage';
const AuthCheck = ({ children }: { children: ReactNode }) => {
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null);
@ -33,18 +39,53 @@ const AuthCheck = ({ children }: { children: ReactNode }) => {
const checkAuth = async () => {
try {
const savedConfig = localStorage.getItem('launcher_config');
if (savedConfig) {
const config = JSON.parse(savedConfig);
if (config.accessToken) {
// Можно добавить дополнительную проверку токена
const isValid = await validateToken(
config.accessToken,
config.clientToken,
);
setIsAuthenticated(isValid);
return;
}
if (!savedConfig) {
setIsAuthenticated(false);
return;
}
const config = JSON.parse(savedConfig);
if (config.accessToken && config.clientToken) {
// 1. Проверяем валидность токена через ваш API
const response = await fetch(`${API_BASE_URL}/auth/validate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
accessToken: config.accessToken,
clientToken: config.clientToken,
}),
});
const isValid = response.ok;
// 2. ДОПОЛНИТЕЛЬНО: проверяем доступ к API через /auth/me
if (isValid) {
try {
const meResponse = await fetch(
`${API_BASE_URL}/auth/me?${new URLSearchParams({
accessToken: config.accessToken,
clientToken: config.clientToken,
})}`,
);
if (!meResponse.ok) {
// Токен валиден для Yggdrasil, но нет доступа к API
console.warn('Токен валиден, но нет доступа к API лаунчера');
setIsAuthenticated(false);
return;
}
} catch (error) {
console.error('Ошибка проверки доступа к API:', error);
setIsAuthenticated(false);
return;
}
}
setIsAuthenticated(isValid);
return;
}
setIsAuthenticated(false);
} catch (error) {
console.error('Ошибка проверки авторизации:', error);
@ -93,27 +134,115 @@ const AuthCheck = ({ children }: { children: ReactNode }) => {
};
if (isAuthenticated === null) {
return <FullScreenLoader message="Загрузка..." />;
return <FullScreenLoader message="Проверка авторизации..." />;
}
return isAuthenticated ? children : <Navigate to="/login" replace />;
};
const App = () => {
const getInitialRoute = () => {
try {
const settingsRaw = localStorage.getItem('launcher_settings');
const settings = settingsRaw ? JSON.parse(settingsRaw) : null;
if (!settings?.rememberLastRoute) return ['/'];
const saved = localStorage.getItem('last_route');
return [saved || '/'];
} catch {
return ['/'];
}
};
return (
<Router>
<Router initialEntries={getInitialRoute()}>
<AppLayout />
</Router>
);
};
const AppLayout = () => {
const location = useLocation();
useEffect(() => {
try {
const settingsRaw = localStorage.getItem('launcher_settings');
const settings = settingsRaw ? JSON.parse(settingsRaw) : null;
if (!settings?.rememberLastRoute) return;
localStorage.setItem('last_route', location.pathname);
} catch {}
}, [location.pathname]);
useEffect(() => {
const applySettings = () => {
try {
const raw = localStorage.getItem('launcher_settings');
if (!raw) return;
const settings = JSON.parse(raw);
document.body.classList.toggle(
'reduce-motion',
Boolean(settings.reduceMotion),
);
document.body.classList.toggle(
'no-blur',
settings.blurEffects === false,
);
const ui = document.getElementById('app-ui');
if (ui && typeof settings.uiScale === 'number') {
const scale = settings.uiScale / 100;
ui.style.transform = `scale(${scale})`;
ui.style.transformOrigin = 'top left';
ui.style.width = `${100 / scale}%`;
ui.style.height = `${100 / scale}%`;
}
} catch (e) {
console.error('Failed to apply UI settings', e);
}
};
const pushLauncherSettingsToMain = async () => {
try {
const raw = localStorage.getItem('launcher_settings');
const s = raw ? JSON.parse(raw) : null;
await window.electron.ipcRenderer.invoke('apply-launcher-settings', {
autoLaunch: Boolean(s?.autoLaunch),
startInTray: Boolean(s?.startInTray),
closeToTray: s?.closeToTray !== false,
});
} catch (e) {
console.error('Failed to push launcher settings to main', e);
}
};
// применяем при загрузке
applySettings();
pushLauncherSettingsToMain();
// применяем после сохранения настроек
window.addEventListener('settings-updated', applySettings);
window.addEventListener('settings-updated', pushLauncherSettingsToMain);
return () => {
window.removeEventListener('settings-updated', applySettings);
window.removeEventListener(
'settings-updated',
pushLauncherSettingsToMain,
);
};
}, []);
// Просто используйте window.open без useNavigate
const handleRegister = () => {
window.open('https://account.ely.by/register', '_blank');
};
const [username, setUsername] = useState<string | null>(null);
const location = useLocation();
const path = location.pathname;
useEffect(() => {
@ -126,105 +255,179 @@ const AppLayout = () => {
}
}, []);
useEffect(() => {
const raw = localStorage.getItem('launcher_config');
const isAuthed = !!raw && !!JSON.parse(raw).accessToken;
window.electron.ipcRenderer.invoke('auth-changed', { isAuthed });
}, []);
return (
<Box
sx={{
height: '100vh',
width: '100vw',
height: '100vh',
position: 'relative',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: location.pathname === '/profile' || location.pathname.startsWith('/launch') || location.pathname === '/login' || location.pathname === '/registration'
? 'center'
: 'flex-start',
overflowX: 'hidden',
overflow: 'hidden',
}}
>
{/* ФОН — НЕ масштабируется */}
<Box
sx={{ position: 'fixed', inset: 0, zIndex: 0, pointerEvents: 'none' }}
>
<MinecraftBackground />
<TopBar onRegister={handleRegister} username={username || ''} />
<PageHeader />
<Notifier />
</Box>
<Routes>
<Route
path="/login"
element={<Login onLoginSuccess={setUsername} />}
/>
<Route path="/registration" element={<Registration />} />
<Route
path="/"
element={
<AuthCheck>
<VersionsExplorer />
</AuthCheck>
}
/>
<Route
path="/launch/:versionId"
element={
<AuthCheck>
<LaunchPage />
</AuthCheck>
}
/>
<Route
path="/profile"
element={
<AuthCheck>
<Profile />
</AuthCheck>
}
/>
<Route
path="/daily"
element={
<AuthCheck>
<DailyReward />
</AuthCheck>
}
/>
<Route
path="/dailyquests"
element={
<AuthCheck>
<DailyQuests />
</AuthCheck>
}
/>
<Route
path="/settings"
element={
<AuthCheck>
<Settings />
</AuthCheck>
}
/>
<Route
path="/shop"
element={
<AuthCheck>
<Shop />
</AuthCheck>
}
/>
<Route
path="/marketplace"
element={
<AuthCheck>
<Marketplace />
</AuthCheck>
}
/>
<Route
path="/news"
element={
<AuthCheck>
<News />
</AuthCheck>
}
/>
</Routes>
{/* UI — масштабируется */}
<Box
id="app-scroll"
sx={{
position: 'relative',
zIndex: 1,
height: '100%',
width: '100%',
overflowY: 'hidden',
overflowX: 'hidden',
}}
>
<Box
id="app-ui"
sx={{
position: 'relative',
zIndex: 1,
height: '100vh',
width: '100vw',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent:
path === '/profile' ||
path.startsWith('/launch') ||
path === '/login' ||
path === '/registration'
? 'center'
: 'flex-start',
overflowX: 'hidden',
}}
>
<TopBar onRegister={handleRegister} username={username || ''} />
<PageHeader />
<Notifier />
<TrayBridge />
<Routes>
<Route
path="/login"
element={<Login onLoginSuccess={setUsername} />}
/>
<Route path="/registration" element={<Registration />} />
<Route
path="/"
element={
<AuthCheck>
<VersionsExplorer />
</AuthCheck>
}
/>
<Route
path="/launch/:versionId"
element={
<AuthCheck>
<LaunchPage />
</AuthCheck>
}
/>
<Route
path="/profile"
element={
<AuthCheck>
<Profile />
</AuthCheck>
}
/>
<Route
path="/inventory"
element={
<AuthCheck>
<Inventory />
</AuthCheck>
}
/>
<Route
path="/daily"
element={
<AuthCheck>
<DailyReward />
</AuthCheck>
}
/>
<Route
path="/dailyquests"
element={
<AuthCheck>
<DailyQuests />
</AuthCheck>
}
/>
<Route
path="/settings"
element={
<AuthCheck>
<Settings />
</AuthCheck>
}
/>
<Route
path="/voice"
element={
<AuthCheck>
<VoicePage />
</AuthCheck>
}
/>
<Route
path="/shop"
element={
<AuthCheck>
<Shop />
</AuthCheck>
}
/>
<Route
path="/marketplace"
element={
<AuthCheck>
<Marketplace />
</AuthCheck>
}
/>
<Route
path="/news"
element={
<AuthCheck>
<News />
</AuthCheck>
}
/>
<Route
path="/fakepaymentpage"
element={
<AuthCheck>
<FakePaymentPage />
</AuthCheck>
}
/>
<Route
path="/promocode"
element={
<AuthCheck>
<PromoRedeem />
</AuthCheck>
}
/>
</Routes>
</Box>
</Box>
</Box>
);
};

View File

@ -1,5 +1,95 @@
export const API_BASE_URL = 'https://minecraft.api.popa-popa.ru';
// АВТОРИЗАЦИЯ \\
export interface AuthSession {
accessToken: string;
clientToken: string;
selectedProfile: {
id: string; // UUID пользователя
name: string; // Имя игрока
};
user?: {
id: string;
properties?: Array<{
name: string;
value: string;
}>;
};
}
export async function authenticate(
username: string,
password: string,
): Promise<AuthSession> {
const clientToken = Math.random().toString(36).substring(2);
const response = await fetch(`${API_BASE_URL}/auth/authenticate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username,
password,
clientToken,
requestUser: true,
}),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Ошибка авторизации: ${errorText}`);
}
return await response.json();
}
// Валидация токена
export async function validateToken(
accessToken: string,
clientToken: string,
): Promise<boolean> {
const response = await fetch(`${API_BASE_URL}/auth/validate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ accessToken, clientToken }),
});
return response.ok;
}
// Обновление токена
export async function refreshToken(
accessToken: string,
clientToken: string,
): Promise<AuthSession | null> {
const response = await fetch(`${API_BASE_URL}/auth/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ accessToken, clientToken }),
});
if (!response.ok) return null;
return await response.json();
}
// Получение информации о себе (проверяет, что токен валидный И есть доступ к API)
export async function getMe(): Promise<MeResponse> {
const { accessToken, clientToken } = getAuthTokens();
if (!accessToken || !clientToken) {
throw new Error('Нет токенов авторизации');
}
const params = new URLSearchParams({ accessToken, clientToken });
const response = await fetch(`${API_BASE_URL}/auth/me?${params.toString()}`);
if (!response.ok) {
throw new Error('Не удалось получить данные пользователя');
}
return await response.json();
}
export interface Player {
uuid: string;
username: string;
@ -75,26 +165,7 @@ export interface OnlinePlayersResponse {
}
export interface MarketplaceResponse {
items: [
{
_id: string;
id: string;
material: string;
amount: number;
price: number;
seller_name: string;
server_ip: string;
display_name: string | null;
lore: string | null;
enchants: string | null;
item_data: {
slot: number;
material: string;
amount: number;
};
created_at: string;
},
];
items: MarketplaceItemResponse[];
total: number;
page: number;
pages: number;
@ -103,6 +174,7 @@ export interface MarketplaceResponse {
export interface MarketplaceItemResponse {
_id: string;
id: string;
description: string;
material: string;
amount: number;
price: number;
@ -115,6 +187,10 @@ export interface MarketplaceItemResponse {
slot: number;
material: string;
amount: number;
meta?: {
enchants?: Record<string, number>;
[key: string]: any;
};
};
created_at: string;
}
@ -421,11 +497,66 @@ export async function toggleBonusActivation(
return await response.json();
}
// ===== QR AUTH =====
export type QrInitResponse = {
token: string;
qr_url: string;
expires_at: string; // ISO
};
export type QrStatusPending = {
status: 'pending' | 'approved' | 'expired' | 'consumed';
};
export type QrStatusOk = {
status: 'ok';
accessToken: string;
clientToken: string;
selectedProfile: { id: string; name: string };
};
export type QrStatusResponse = QrStatusPending | QrStatusOk;
export async function qrInit(device_id?: string): Promise<QrInitResponse> {
const url = device_id
? `${API_BASE_URL}/auth/qr/init?device_id=${encodeURIComponent(device_id)}`
: `${API_BASE_URL}/auth/qr/init`;
const response = await fetch(url, { method: 'POST' });
if (!response.ok) {
throw new Error('Не удалось создать QR-логин');
}
return await response.json();
}
export async function qrStatus(
token: string,
device_id?: string,
): Promise<QrStatusResponse> {
const qs = new URLSearchParams({ token });
if (device_id) qs.set('device_id', device_id);
const response = await fetch(
`${API_BASE_URL}/auth/qr/status?${qs.toString()}`,
);
if (!response.ok) {
throw new Error('Не удалось проверить статус QR-логина');
}
return await response.json();
}
// ===== КЕЙСЫ =====
export interface CaseItemMeta {
display_name?: string | null;
lore?: string[] | null;
enchants?: Record<string, number> | null;
durability?: number | null;
}
export interface CaseItem {
@ -443,7 +574,7 @@ export interface Case {
description?: string;
price: number;
image_url?: string;
server_ids?: string[];
server_ips?: string[];
items_count?: number;
items?: CaseItem[];
}
@ -457,52 +588,34 @@ export interface OpenCaseResponse {
}
export async function fetchCases(): Promise<Case[]> {
const response = await fetch(`${API_BASE_URL}/cases`);
if (!response.ok) {
throw new Error('Не удалось получить список кейсов');
}
const response = await fetch(`${API_BASE_URL}/cases/`);
if (!response.ok) throw new Error('Не удалось получить список кейсов');
return await response.json();
}
// Если у тебя есть отдельный эндпоинт деталей кейса, можно использовать это:
export async function fetchCase(case_id: string): Promise<Case> {
const response = await fetch(`${API_BASE_URL}/cases/${case_id}`);
if (!response.ok) {
throw new Error('Не удалось получить информацию о кейсе');
}
if (!response.ok) throw new Error('Не удалось получить информацию о кейсе');
return await response.json();
}
export async function openCase(
case_id: string,
username: string,
server_id: string,
server_ip: string,
): Promise<OpenCaseResponse> {
// Формируем URL с query-параметрами, как любит текущий бэкенд
const url = new URL(`${API_BASE_URL}/cases/${case_id}/open`);
url.searchParams.append('username', username);
url.searchParams.append('server_id', server_id);
url.searchParams.set('username', username);
url.searchParams.set('server_ip', server_ip);
const response = await fetch(url.toString(), {
method: 'POST',
});
const response = await fetch(url.toString(), { method: 'POST' });
if (!response.ok) {
let msg = 'Не удалось открыть кейс';
try {
const errorData = await response.json();
if (errorData.message) {
msg = errorData.message;
} else if (Array.isArray(errorData.detail)) {
msg = errorData.detail.map((d: any) => d.msg).join(', ');
} else if (typeof errorData.detail === 'string') {
msg = errorData.detail;
}
} catch {
// если бэкенд вернул не-JSON, оставляем дефолтное сообщение
}
msg = errorData.message || errorData.detail || msg;
} catch {}
throw new Error(msg);
}
@ -511,6 +624,91 @@ export async function openCase(
// ===== КЕЙСЫ ===== \\
// ===== Инвентарь =====
export interface InventoryRawItem {
_id: string;
id: string; // item_id для withdraw
username: string;
server_ip: string;
item_data: {
material: string;
amount: number;
meta?: {
display_name?: string | null;
lore?: string[] | null;
enchants?: Record<string, number> | null;
durability?: number | null;
};
};
source?: {
type: string;
case_id?: string;
case_name?: string;
};
status: 'stored' | 'delivered' | string;
created_at: string;
delivered_at?: string | null;
withdraw_operation_id?: string | null;
}
export interface InventoryItemsResponse {
items: InventoryRawItem[];
page: number;
limit: number;
total: number;
}
export async function fetchInventoryItems(
username: string,
server_ip: string,
page = 1,
limit = 28,
): Promise<InventoryItemsResponse> {
const url = new URL(`${API_BASE_URL}/inventory/items`);
url.searchParams.set('username', username);
url.searchParams.set('server_ip', server_ip);
url.searchParams.set('page', String(page));
url.searchParams.set('limit', String(limit));
const response = await fetch(url.toString());
if (!response.ok) {
let msg = 'Не удалось получить инвентарь';
try {
const err = await response.json();
msg = err.message || err.detail || msg;
} catch {}
throw new Error(msg);
}
return await response.json();
}
export async function withdrawInventoryItem(payload: {
username: string;
item_id: string;
server_ip: string;
}): Promise<{ status: string; message?: string }> {
const response = await fetch(`${API_BASE_URL}/inventory/withdraw`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
if (!response.ok) {
let msg = 'Не удалось выдать предмет';
try {
const err = await response.json();
msg = err.message || err.detail || msg;
} catch {}
throw new Error(msg);
}
return await response.json();
}
// ===== ИНВЕНТАРЬ ===== \\
// ===== Ежедневная награда =====
export interface DailyStatusResponse {
ok: boolean;
@ -535,7 +733,9 @@ export interface DailyDaysResponse {
count: number;
}
export async function fetchDailyClaimDays(limit = 120): Promise<DailyDaysResponse> {
export async function fetchDailyClaimDays(
limit = 120,
): Promise<DailyDaysResponse> {
const { accessToken, clientToken } = getAuthTokens();
if (!accessToken || !clientToken) {
@ -626,14 +826,20 @@ export async function fetchDailyQuestsStatus(): Promise<DailyQuestsStatusRespons
return await response.json();
}
export async function claimDailyQuest(questKey: string): Promise<DailyQuestClaimResponse> {
export async function claimDailyQuest(
questKey: string,
): Promise<DailyQuestClaimResponse> {
const { accessToken, clientToken } = getAuthTokens();
if (!accessToken || !clientToken) {
throw new Error('Нет токенов авторизации');
}
const params = new URLSearchParams({ accessToken, clientToken, quest_key: questKey });
const params = new URLSearchParams({
accessToken,
clientToken,
quest_key: questKey,
});
const response = await fetch(
`${API_BASE_URL}/users/daily-quests/claim?${params.toString()}`,
{ method: 'POST' },
@ -813,6 +1019,57 @@ export async function RequestPlayerInventory(
return await response.json();
}
// ===== Marketplace: мои лоты (изменить цену / снять с продажи) =====
export async function updateMarketplaceItemPrice(
username: string,
item_id: string,
new_price: number,
): Promise<{ status: string; message?: string }> {
const response = await fetch(
`${API_BASE_URL}/api/marketplace/items/${encodeURIComponent(item_id)}/price`,
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, new_price }),
},
);
if (!response.ok) {
let msg = 'Не удалось изменить цену';
try {
const err = await response.json();
msg = err.message || err.detail || msg;
} catch {}
throw new Error(msg);
}
return await response.json();
}
export async function cancelMarketplaceItemSale(
username: string,
item_id: string,
): Promise<{ status: string; message?: string }> {
const url = new URL(
`${API_BASE_URL}/api/marketplace/items/${encodeURIComponent(item_id)}`,
);
url.searchParams.set('username', username);
const response = await fetch(url.toString(), { method: 'DELETE' });
if (!response.ok) {
let msg = 'Не удалось снять товар с продажи';
try {
const err = await response.json();
msg = err.message || err.detail || msg;
} catch {}
throw new Error(msg);
}
return await response.json();
}
export async function buyItem(
buyer_username: string,
item_id: string,
@ -898,6 +1155,7 @@ export async function sellItem(
amount: number,
price: number,
server_ip: string,
description: string,
): Promise<{ status: string; operation_id: string }> {
const response = await fetch(`${API_BASE_URL}/api/marketplace/items/sell`, {
method: 'POST',
@ -910,6 +1168,7 @@ export async function sellItem(
amount,
price,
server_ip,
description,
}),
});
@ -955,6 +1214,40 @@ export async function fetchMarketplace(
return await response.json();
}
export async function fetchMyMarketplaceItems(
username: string,
server_ip?: string | null,
page = 1,
limit = 20,
): Promise<MarketplaceResponse> {
// вместо /items/me используем /items/by-seller/{username}
const url = new URL(`${API_BASE_URL}/api/marketplace/items/by-seller/${encodeURIComponent(username)}`);
if (server_ip) url.searchParams.set('server_ip', server_ip);
url.searchParams.set('page', String(page));
url.searchParams.set('limit', String(limit));
const response = await fetch(url.toString());
// если на бэке “нет предметов” возвращают 404 — можно трактовать как пустой список
if (response.status === 404) {
return { items: [], total: 0, page, pages: 1 };
}
if (!response.ok) {
let msg = 'Не удалось получить ваши товары';
try {
const err = await response.json();
msg = err.message || err.detail || msg;
} catch {}
throw new Error(msg);
}
return await response.json();
}
// ===== Marketplace ===== \\
// Исправьте тип возвращаемого значения
export async function fetchActiveServers(): Promise<Server[]> {
const response = await fetch(`${API_BASE_URL}/api/pranks/servers`);

View File

@ -0,0 +1,60 @@
import { API_BASE_URL } from '../api';
export interface PrankCommand {
id: string;
name: string;
description: string;
price: number;
command_template: string;
server_ids: string[]; // ["*"] или конкретные id
targetDescription: string;
globalDescription: string;
material: string;
}
export interface PrankServer {
id: string;
name: string;
ip: string;
online_players: number;
max_players: number;
}
export const fetchPrankCommands = async (): Promise<PrankCommand[]> => {
const res = await fetch(`${API_BASE_URL}/api/pranks/commands`);
if (!res.ok) throw new Error('Failed to load prank commands');
return res.json();
};
export const fetchPrankServers = async (): Promise<PrankServer[]> => {
const res = await fetch(`${API_BASE_URL}/api/pranks/servers`);
if (!res.ok) throw new Error('Failed to load prank servers');
return res.json();
};
export const executePrank = async (
username: string,
commandId: string,
targetPlayer: string,
serverId: string,
) => {
const res = await fetch(
`${API_BASE_URL}/api/pranks/execute?username=${username}`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
command_id: commandId,
target_player: targetPlayer,
server_id: serverId,
}),
},
);
if (!res.ok) {
const err = await res.text();
throw new Error(err);
}
return res.json();
};

View File

@ -0,0 +1,32 @@
import { API_BASE_URL } from '../api';
export interface RedeemPromoResponse {
code: string;
reward_coins: number;
new_balance: number;
}
export async function redeemPromoCode(
username: string,
code: string,
): Promise<RedeemPromoResponse> {
const formData = new FormData();
formData.append('username', username);
formData.append('code', code);
const response = await fetch(`${API_BASE_URL}/promo/redeem`, {
method: 'POST',
body: formData,
});
if (!response.ok) {
let msg = 'Не удалось активировать промокод';
try {
const errorData = await response.json();
msg = errorData.message || errorData.detail || msg;
} catch {}
throw new Error(msg);
}
return await response.json();
}

View File

@ -0,0 +1,62 @@
const API_BASE = 'https://minecraft.api.popa-popa.ru';
export type ApiRoom = {
id: string;
name: string;
public: boolean;
owner: string;
max_users: number;
usernames: string[];
users: number;
created_at: string;
};
export async function fetchRooms(): Promise<ApiRoom[]> {
const res = await fetch(`${API_BASE}/api/voice/rooms`);
if (!res.ok) {
const text = await res.text();
throw new Error(text);
}
return res.json();
}
export async function fetchRoomDetails(roomId: string): Promise<RoomDetails> {
const res = await fetch(`${API_BASE}/api/voice/rooms/${roomId}`);
if (!res.ok) throw new Error(await res.text());
return res.json();
}
export async function createPublicRoom(
name: string,
owner: string,
isPublic: boolean,
) {
const res = await fetch(`${API_BASE}/api/voice/rooms`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
public: isPublic,
owner,
}),
});
return res.json();
}
export async function joinPrivateRoom(code: string): Promise<ApiRoom> {
const res = await fetch(`${API_BASE}/api/voice/rooms/join`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code }),
});
if (!res.ok) {
const text = await res.text();
throw new Error(text);
}
return res.json();
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 80 KiB

View File

@ -82,7 +82,7 @@ export const BonusShopItem: React.FC<BonusShopItemProps> = ({
sx={{
position: 'relative',
width: '100%',
maxWidth: 220,
maxWidth: '27.5vw',
height: 440,
display: 'flex',
flexDirection: 'column',
@ -96,8 +96,9 @@ export const BonusShopItem: React.FC<BonusShopItemProps> = ({
transition: 'transform 0.35s ease, box-shadow 0.35s ease',
'&:hover': {
transform: 'scale(1.01)',
boxShadow: '0 10px 20px rgba(242,113,33,0.1)',
// transform: 'scale(1.01)',
borderColor: 'rgba(200, 33, 242, 0.35)',
boxShadow: '0 1.2vw 3.2vw rgba(53, 3, 66, 0.75)',
},
}}
>
@ -107,8 +108,10 @@ export const BonusShopItem: React.FC<BonusShopItemProps> = ({
position: 'absolute',
inset: 0,
pointerEvents: 'none',
// background:
// 'radial-gradient(circle at top, rgba(242,113,33,0.25), transparent 60%)',
background:
'radial-gradient(circle at top, rgba(242,113,33,0.25), transparent 60%)',
'radial-gradient(circle at 10% 10%, rgba(242,113,33,0.10), transparent 55%), radial-gradient(circle at 90% 20%, rgba(233,64,205,0.16), transparent 55%)',
}}
/>

View File

@ -67,9 +67,9 @@ export default function CapeCard({
transition:
'transform 0.18s ease, border-color 0.18s ease, box-shadow 0.18s ease',
'&:hover': {
transform: 'scale(1.01)',
borderColor: 'rgba(242,113,33,0.35)',
boxShadow: '0 1.4vw 3.8vw rgba(0,0,0,0.60)',
// transform: 'scale(1.01)',
borderColor: 'rgba(200, 33, 242, 0.35)',
boxShadow: '0 1.2vw 3.2vw rgba(53, 3, 66, 0.75)',
},
}}
>
@ -135,8 +135,8 @@ export default function CapeCard({
{/* Здесь показываем ЛЕВУЮ половину текстуры (лицевую часть) */}
<Box
sx={{
width: '44vw',
height: '36vw',
width: '46.2vw',
height: '39.2vw',
minWidth: '462px',
minHeight: '380px',
imageRendering: 'pixelated',

View File

@ -0,0 +1,260 @@
import React, { useEffect, useMemo, useState } from 'react';
import {
Dialog,
DialogTitle,
DialogContent,
Box,
Typography,
Grid,
Paper,
CircularProgress,
} from '@mui/material';
import type { Case, CaseItem } from '../api';
import { fetchCase } from '../api';
import CloseIcon from '@mui/icons-material/Close';
import IconButton from '@mui/material/IconButton';
const CARD_BG =
'radial-gradient(circle at 10% 10%, rgba(242,113,33,0.14), transparent 55%), radial-gradient(circle at 90% 20%, rgba(233,64,205,0.12), transparent 55%), rgba(10,10,20,0.86)';
const CardFacePaperSx = {
borderRadius: '1.2vw',
background: CARD_BG,
border: '1px solid rgba(255,255,255,0.08)',
boxShadow: '0 1.2vw 3.2vw rgba(0,0,0,0.55)',
color: 'white',
} as const;
const GLASS_PAPER_SX = {
borderRadius: '1.2vw',
overflow: 'hidden',
background:
'radial-gradient(circle at 10% 10%, rgba(242,113,33,0.14), transparent 55%), radial-gradient(circle at 90% 20%, rgba(233,64,205,0.12), transparent 55%), rgba(10,10,20,0.86)',
border: '1px solid rgba(255,255,255,0.08)',
boxShadow: '0 1.2vw 3.2vw rgba(0,0,0,0.55)',
color: 'white',
backdropFilter: 'blur(16px)',
} as const;
function stripMinecraftColors(text?: string | null): string {
if (!text) return '';
return text.replace(/§[0-9A-FK-ORa-fk-or]/g, '');
}
function getChancePercent(itemWeight: number, total: number) {
if (!total || total <= 0) return 0;
return (itemWeight / total) * 100;
}
function getRarityByWeight(weight?: number): 'common' | 'rare' | 'epic' | 'legendary' {
if (weight === undefined || weight === null) return 'common';
if (weight <= 5) return 'legendary';
if (weight <= 20) return 'epic';
if (weight <= 50) return 'rare';
return 'common';
}
function getRarityColor(weight?: number): string {
const rarity = getRarityByWeight(weight);
switch (rarity) {
case 'legendary':
return 'rgba(255, 215, 0, 1)'; // gold
case 'epic':
return 'rgba(186, 85, 211, 1)'; // purple
case 'rare':
return 'rgba(65, 105, 225, 1)'; // blue
default:
return 'rgba(255, 255, 255, 0.75)';
}
}
type Props = {
open: boolean;
onClose: () => void;
caseId: string;
caseName?: string;
};
export default function CaseItemsDialog({ open, onClose, caseId, caseName }: Props) {
const [loading, setLoading] = useState(false);
const [caseData, setCaseData] = useState<Case | null>(null);
const items: CaseItem[] = useMemo(() => {
const list = caseData?.items ?? [];
return [...list].sort((a, b) => {
const wa = a.weight ?? Infinity;
const wb = b.weight ?? Infinity;
return wa - wb; // 🔥 по возрастанию weight (легендарки сверху)
});
}, [caseData]);
const totalWeight = useMemo(() => {
return items.reduce((sum, it) => sum + (Number(it.weight) || 0), 0);
}, [items]);
useEffect(() => {
if (!open) return;
let cancelled = false;
(async () => {
try {
setLoading(true);
const full = await fetchCase(caseId);
if (!cancelled) setCaseData(full);
} catch (e) {
console.error('Ошибка при загрузке предметов кейса:', e);
if (!cancelled) setCaseData(null);
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => {
cancelled = true;
};
}, [open, caseId]);
return (
<Dialog
open={open}
onClose={onClose}
fullWidth
maxWidth="md"
PaperProps={{
sx: GLASS_PAPER_SX,
}}
>
<DialogTitle
sx={{
fontFamily: 'Benzin-Bold',
pr: 6, // место под крестик
position: 'relative',
}}
>
Предметы кейса{caseName ? `${caseName}` : ''}
<IconButton
onClick={onClose}
sx={{
position: 'absolute',
top: 10,
right: 10,
color: 'rgba(255,255,255,0.9)',
border: '1px solid rgba(255,255,255,0.12)',
background: 'rgba(255,255,255,0.06)',
backdropFilter: 'blur(12px)',
'&:hover': { transform: 'scale(1.05)', background: 'rgba(255,255,255,0.10)' },
transition: 'all 0.2s ease',
}}
>
<CloseIcon fontSize="small" />
</IconButton>
</DialogTitle>
<DialogContent dividers sx={{ borderColor: 'rgba(255,255,255,0.10)' }}>
{loading ? (
<Box sx={{ py: 6, display: 'flex', justifyContent: 'center' }}>
<CircularProgress />
</Box>
) : !items.length ? (
<Typography sx={{ color: 'rgba(255,255,255,0.75)' }}>
Предметы не найдены (или кейс временно недоступен).
</Typography>
) : (
<>
<Grid container spacing={2}>
{items.map((it) => {
const w = Number(it.weight) || 0;
const chance = getChancePercent(w, totalWeight);
const displayNameRaw = it.meta?.display_name ?? it.name ?? it.material ?? 'Предмет';
const displayName = stripMinecraftColors(displayNameRaw);
const texture = it.material
? `https://cdn.minecraft.popa-popa.ru/textures/${it.material.toLowerCase()}.png`
: '';
return (
<Grid item xs={3} key={it.id}>
<Paper
elevation={0}
sx={{
...CardFacePaperSx,
width: '12vw',
height: '12vw',
minWidth: 110,
minHeight: 110,
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
overflow: 'hidden',
position: 'relative',
}}
>
{/* верхняя плашка (редкость) */}
<Box
sx={{
px: 1,
py: 0.7,
borderBottom: '1px solid rgba(255,255,255,0.08)',
color: getRarityColor(it.weight),
fontFamily: 'Benzin-Bold',
fontSize: '0.75rem',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
title={displayName}
>
{displayName}
</Box>
{/* иконка */}
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', flexGrow: 1 }}>
{texture ? (
<Box
component="img"
src={texture}
alt={displayName}
draggable={false}
sx={{
width: '5vw',
height: '5vw',
minWidth: 40,
minHeight: 40,
objectFit: 'contain',
imageRendering: 'pixelated',
userSelect: 'none',
}}
/>
) : (
<Typography sx={{ color: 'rgba(255,255,255,0.6)' }}>?</Typography>
)}
</Box>
{/* низ: шанс/вес/кол-во */}
<Box
sx={{
px: 1,
py: 0.9,
borderTop: '1px solid rgba(255,255,255,0.08)',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 1,
}}
>
<Typography sx={{ fontSize: '0.75rem', fontFamily: 'Benzin-Bold' }}>
{chance.toFixed(2)}%
</Typography>
</Box>
</Paper>
</Grid>
);
})}
</Grid>
</>
)}
</DialogContent>
</Dialog>
);
}

View File

@ -21,6 +21,9 @@ interface CoinsDisplayProps {
backgroundColor?: string;
textColor?: string;
onClick?: () => void;
disableRefreshOnClick?: boolean;
sx?: SxProps<Theme>;
}
@ -40,8 +43,13 @@ export default function CoinsDisplay({
backgroundColor = 'rgba(0, 0, 0, 0.2)',
textColor = 'white',
onClick,
disableRefreshOnClick = false,
sx,
}: CoinsDisplayProps) {
const [isLoading, setIsLoading] = useState<boolean>(false);
const [settingsVersion, setSettingsVersion] = useState(0);
const storageKey = useMemo(() => {
// ключ под конкретного пользователя
return username ? `coins:${username}` : 'coins:anonymous';
@ -59,6 +67,14 @@ export default function CoinsDisplay({
}
};
const handleClick = () => {
// 1) если передали внешний обработчик — выполняем его
if (onClick) onClick();
// 2) опционально оставляем обновление баланса по клику
if (!disableRefreshOnClick && username) fetchCoinsData();
};
const [coins, setCoins] = useState<number>(() => {
// 1) если пришло значение извне — оно приоритетнее
if (externalValue !== undefined) return externalValue;
@ -71,7 +87,25 @@ export default function CoinsDisplay({
return 0;
});
const [isLoading, setIsLoading] = useState<boolean>(false);
useEffect(() => {
const handler = () => setSettingsVersion((v) => v + 1);
window.addEventListener('settings-updated', handler as EventListener);
return () =>
window.removeEventListener('settings-updated', handler as EventListener);
}, []);
const isTooltipDisabledBySettings = useMemo(() => {
try {
const raw = localStorage.getItem('launcher_settings');
if (!raw) return false;
const s = JSON.parse(raw);
return Boolean(s?.disableToolTip);
} catch {
return false;
}
}, [settingsVersion]);
const tooltipEnabled = showTooltip && !isTooltipDisabledBySettings;
const getSizes = () => {
switch (size) {
@ -172,7 +206,7 @@ export default function CoinsDisplay({
borderRadius: sizes.borderRadius,
padding: sizes.containerPadding,
border: '1px solid rgba(255, 255, 255, 0.1)',
cursor: showTooltip ? 'help' : 'default',
cursor: onClick ? 'pointer' : tooltipEnabled ? 'help' : 'default',
// можно оставить лёгкий намёк на загрузку, но без "пульса" текста
opacity: isLoading ? 0.85 : 1,
@ -180,7 +214,7 @@ export default function CoinsDisplay({
...sx,
}}
onClick={username ? handleRefresh : undefined}
onClick={handleClick}
title={username ? 'Нажмите для обновления' : undefined}
>
{showIcon && (
@ -222,7 +256,7 @@ export default function CoinsDisplay({
</Box>
);
if (showTooltip) {
if (tooltipEnabled) {
return (
<CustomTooltip
title={tooltipText}

View File

@ -0,0 +1,152 @@
import React from 'react';
import { Box, Typography } from '@mui/material';
type Props = {
title: string;
description?: string;
checked: boolean;
onChange: (checked: boolean) => void;
disabled?: boolean;
};
const GRADIENT =
'linear-gradient(71deg, #F27121 0%, #E940CD 70%, #8A2387 100%)';
export default function SettingCheckboxRow({
title,
description,
checked,
onChange,
disabled,
}: Props) {
const toggle = () => {
if (disabled) return;
onChange(!checked);
};
return (
<Box
onClick={toggle}
role="checkbox"
aria-checked={checked}
tabIndex={disabled ? -1 : 0}
onKeyDown={(e) => {
if (disabled) return;
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
onChange(!checked);
}
}}
sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: '1vw',
p: '0.9vw',
borderRadius: '1.1vw',
cursor: disabled ? 'not-allowed' : 'pointer',
userSelect: 'none',
opacity: disabled ? 0.5 : 1,
background: checked
? 'linear-gradient(120deg, rgba(242,113,33,0.12), rgba(233,64,205,0.10))'
: 'rgba(255,255,255,0.04)',
border: checked
? '1px solid rgba(233,64,205,0.45)'
: '1px solid rgba(255,255,255,0.10)',
transition: 'all 0.18s ease',
'&:hover': disabled
? undefined
: {
background: checked
? 'linear-gradient(120deg, rgba(242,113,33,0.15), rgba(233,64,205,0.12))'
: 'rgba(255,255,255,0.06)',
border: checked
? '1px solid rgba(233,64,205,0.55)'
: '1px solid rgba(255,255,255,0.14)',
},
}}
>
{/* text */}
<Box sx={{ minWidth: 0 }}>
<Typography
sx={{
fontFamily: 'Benzin-Bold',
color: 'rgba(255,255,255,0.92)',
fontSize: '1.3vw',
lineHeight: 1.15,
}}
>
{title}
</Typography>
{description && (
<Typography
sx={{
mt: '0.25vw',
color: 'rgba(255,255,255,0.60)',
fontWeight: 700,
fontSize: '1vw',
lineHeight: 1.2,
}}
>
{description}
</Typography>
)}
</Box>
{/* glass checkbox */}
<Box
sx={{
flexShrink: 0,
width: '2.6vw',
height: '2.6vw',
borderRadius: '0.75vw',
background: 'rgba(0,0,0,0.22)',
border: checked
? '1px solid rgba(233,64,205,0.55)'
: '1px solid rgba(255,255,255,0.14)',
boxShadow: checked
? '0 0.9vw 2.2vw rgba(233,64,205,0.18)'
: '0 0.9vw 2.2vw rgba(0,0,0,0.25)',
display: 'grid',
placeItems: 'center',
}}
>
{/* check */}
<Box
sx={{
borderRadius: '0.45vw',
background: checked ? GRADIENT : 'rgba(255,255,255,0.08)',
border: '1px solid rgba(255,255,255,0.10)',
display: 'grid',
placeItems: 'center',
transform: checked ? 'scale(1)' : 'scale(0.92)',
transition: 'transform 0.16s ease',
}}
>
<svg
width="14"
height="14"
viewBox="0 0 24 24"
style={{
opacity: checked ? 1 : 0,
transition: 'opacity 0.14s ease',
}}
>
<path
d="M20 6L9 17l-5-5"
fill="none"
stroke="white"
strokeWidth="2.6"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</Box>
</Box>
</Box>
);
}

View File

@ -39,13 +39,12 @@ export const FullScreenLoader = ({
{fullScreen && (
<Fade in timeout={220} appear>
<Box
className="glass-ui"
sx={{
position: 'absolute',
inset: 0,
background:
'radial-gradient(circle at 15% 20%, rgba(242,113,33,0.15), transparent 60%), radial-gradient(circle at 85% 10%, rgba(233,64,205,0.12), transparent 55%), rgba(5,5,10,0.75)',
backdropFilter: 'blur(14px)',
WebkitBackdropFilter: 'blur(14px)',
}}
/>
</Fade>
@ -61,7 +60,9 @@ export const FullScreenLoader = ({
alignItems: 'center',
gap: 3,
// небольшой "подъём" при появлении
animation: 'popIn 260ms ease-out both',
animation: document.body.classList.contains('reduce-motion')
? 'none'
: 'popIn 260ms ease-out both',
'@keyframes popIn': {
from: { opacity: 0, transform: 'translateY(8px) scale(0.98)' },
to: { opacity: 1, transform: 'translateY(0) scale(1)' },
@ -76,7 +77,9 @@ export const FullScreenLoader = ({
position: 'relative',
overflow: 'hidden',
background: 'conic-gradient(#F27121, #E940CD, #8A2387, #F27121)',
animation: 'spin 1s linear infinite',
animation: document.body.classList.contains('reduce-motion')
? 'none'
: 'spin 1s linear infinite',
WebkitMask: 'radial-gradient(circle, transparent 55%, black 56%)',
mask: 'radial-gradient(circle, transparent 55%, black 56%)',
'@keyframes spin': {

View File

@ -4,7 +4,7 @@ interface HeadAvatarProps {
skinUrl?: string;
size?: number;
style?: React.CSSProperties;
version?: number; // ✅ добавили
version?: number;
}
const DEFAULT_SKIN =
@ -14,15 +14,17 @@ export const HeadAvatar: React.FC<HeadAvatarProps> = ({
skinUrl,
size = 24,
style,
version = 0, // ✅ дефолт
version = 0,
...canvasProps
}) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const requestIdRef = useRef(0);
useEffect(() => {
const baseUrl = skinUrl?.trim() ? skinUrl : DEFAULT_SKIN;
requestIdRef.current += 1;
const requestId = requestIdRef.current;
// ✅ cache-bust: чтобы браузер НЕ отдавал старую картинку
const baseUrl = skinUrl?.trim() ? skinUrl : DEFAULT_SKIN;
const finalSkinUrl = `${baseUrl}${baseUrl.includes('?') ? '&' : '?'}v=${version}`;
const canvas = canvasRef.current;
@ -33,6 +35,9 @@ export const HeadAvatar: React.FC<HeadAvatarProps> = ({
img.src = finalSkinUrl;
img.onload = () => {
// ✅ игнорим старые onload
if (requestIdRef.current !== requestId) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
@ -47,9 +52,16 @@ export const HeadAvatar: React.FC<HeadAvatarProps> = ({
};
img.onerror = (e) => {
if (requestIdRef.current !== requestId) return;
console.error('Не удалось загрузить скин для HeadAvatar:', e);
};
}, [skinUrl, size, version]); // ✅ version добавили
return () => {
// ✅ гарантированно “убиваем” обработчики старого запроса
img.onload = null;
img.onerror = null;
};
}, [skinUrl, size, version]);
return (
<canvas

View File

@ -1,10 +1,17 @@
import { useState } from "react";
import { Box, Button, TextField, Typography, InputAdornment, IconButton } from '@mui/material';
import { useState } from 'react';
import {
Box,
Button,
TextField,
Typography,
InputAdornment,
IconButton,
} from '@mui/material';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
import VisibilityIcon from '@mui/icons-material/Visibility';
import GradientTextField from '../GradientTextField';
import GradientVisibilityToggleIcon from '../../assets/Icons/GradientVisibilityToggleIcon'
import { useNavigate } from 'react-router-dom'
import GradientVisibilityToggleIcon from '../../assets/Icons/GradientVisibilityToggleIcon';
import { useNavigate } from 'react-router-dom';
interface AuthFormProps {
config: {
@ -35,22 +42,22 @@ const AuthForm = ({ config, handleInputChange, onLogin }: AuthFormProps) => {
onChange={handleInputChange}
sx={{
mt: '2.5vw',
mb: '0vw'
mb: '0vw',
}}
/>
<GradientTextField
label="Пароль"
required
type={showPassword ? "text" : "password"}
type={showPassword ? 'text' : 'password'}
name="password"
value={config.password}
onChange={handleInputChange}
sx={{
'& .MuiInputBase-input': {
color: 'white',
padding: '1rem 0.7rem 1.1rem 1.5rem',
fontFamily: 'Benzin-Bold',
},
color: 'white',
padding: '1rem 0.7rem 1.1rem 1.5rem',
fontFamily: 'Benzin-Bold',
},
}}
InputProps={{
endAdornment: (
@ -62,43 +69,47 @@ const AuthForm = ({ config, handleInputChange, onLogin }: AuthFormProps) => {
onClick={() => setShowPassword((prev) => !prev)}
edge="end"
sx={{
color: "white",
color: 'white',
margin: '0',
padding: '0',
'& MuiTouchRipple-root css-r3djoj-MuiTouchRipple-root': {
display: 'none',
},
}}>
}}
>
<GradientVisibilityToggleIcon
crossed={showPassword} // когда type="text" -> перечеркнуть
sx={{ fontSize: "2.5vw", mr: '0.5vw' }}
crossed={showPassword} // когда type="text" -> перечеркнуть
sx={{ fontSize: '2.5vw', mr: '0.5vw' }}
/>
</IconButton>
</InputAdornment>
),
}}
/>
<Button onClick={onLogin} variant="contained"
sx={{
transition: 'transform 0.3s ease',
width: '60%',
mt: 2,
background: 'linear-gradient(71deg, #F27121 0%, #E940CD 70%, #8A2387 100%)',
fontFamily: 'Benzin-Bold',
borderRadius: '2.5vw',
fontSize: '2vw',
'&:hover': {
transform: 'scale(1.02)',
},
}}>
<Button
onClick={onLogin}
variant="contained"
sx={{
transition: 'transform 0.3s ease',
width: '60%',
mt: 2,
background:
'linear-gradient(71deg, #F27121 0%, #E940CD 70%, #8A2387 100%)',
fontFamily: 'Benzin-Bold',
borderRadius: '2.5vw',
fontSize: '2vw',
'&:hover': {
transform: 'scale(1.02)',
},
}}
>
Войти
</Button>
<Box
sx={{
display: 'flex',
justifyContent: 'flex-end',
}}
display: 'flex',
justifyContent: 'flex-end',
}}
>
<Typography
onClick={() => navigate('/registration')}
@ -109,15 +120,15 @@ const AuthForm = ({ config, handleInputChange, onLogin }: AuthFormProps) => {
letterSpacing: '0.08em',
cursor: 'pointer',
backgroundImage:
'linear-gradient(71deg, #F27121 0%, #E940CD 60%, #8A2387 100%)',
'linear-gradient(71deg, #F27121 0%, #E940CD 60%, #8A2387 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
textShadow: '0 0 15px rgba(0,0,0,0.9)',
'&:hover': {
opacity: 1,
},
}}
>
}}
>
Зарегистрироваться
</Typography>
</Box>

View File

@ -1,12 +1,39 @@
/* eslint-disable react/jsx-props-no-spreading */
import React, { useEffect, useState, useMemo } from 'react';
import { styled } from '@mui/material/styles';
import Tooltip, { tooltipClasses, TooltipProps } from '@mui/material/Tooltip';
// Создаем кастомный стилизованный Tooltip с правильной типизацией
const CustomTooltip = styled(({ className, ...props }: TooltipProps) => (
const STORAGE_KEY = 'launcher_settings';
function readDisableTooltip(): boolean {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return false;
const s = JSON.parse(raw);
return Boolean(s?.disableToolTip);
} catch {
return false;
}
}
const readTooltipPolicy = () => {
try {
const raw = localStorage.getItem('launcher_settings');
if (!raw) return { disableToolTip: false, allowEssentialTooltips: true };
const s = JSON.parse(raw);
return {
disableToolTip: Boolean(s?.disableToolTip),
allowEssentialTooltips: s?.allowEssentialTooltips !== false, // default true
};
} catch {
return { disableToolTip: false, allowEssentialTooltips: true };
}
};
// ВАЖНО: styled-компонент отдельно, чтобы не пересоздавался на каждый рендер
const StyledTooltip = styled(({ className, ...props }: TooltipProps) => (
<Tooltip {...props} classes={{ popper: className }} />
))(({ theme }) => ({
))(() => ({
[`& .${tooltipClasses.tooltip}`]: {
backgroundColor: 'rgba(0, 0, 0, 0.9)',
color: '#fff',
@ -72,4 +99,29 @@ const CustomTooltip = styled(({ className, ...props }: TooltipProps) => (
},
}));
export default CustomTooltip;
export type CustomTooltipProps = TooltipProps & {
/**
* Можно принудительно отключить тултип снаружи,
* плюс учитывается настройка disableToolTip из launcher_settings
*/
essential?: boolean;
disabled?: boolean;
};
export default function CustomTooltip(props: CustomTooltipProps) {
const { essential = false, children, ...rest } = props;
const { disableToolTip, allowEssentialTooltips } = useMemo(
() => readTooltipPolicy(),
// важно: чтобы при "Save" пересчитывалось — ты уже диспатчишь settings-updated
// поэтому ниже мы просто прочитаем ещё раз через key в местах использования (или можно слушать event тут)
[],
);
const disabledBySettings = disableToolTip && !(essential && allowEssentialTooltips);
// Если отключено — просто возвращаем children без обёртки Tooltip
if (disabledBySettings) return <>{children}</>;
return <StyledTooltip {...props}>{children}</StyledTooltip>;
}

View File

@ -1,12 +1,77 @@
import { Alert, Box, Snackbar, Button } from '@mui/material';
import {
Alert,
Box,
Snackbar,
Button,
Stack,
Typography,
Paper,
} from '@mui/material';
import { useEffect, useState } from 'react';
import { styled, alpha, keyframes } from '@mui/material/styles';
export const GRADIENT =
'linear-gradient(71deg, #F27121 0%, #E940CD 70%, #8A2387 100%)';
const glowPulse = keyframes`
0% { opacity: .6 }
50% { opacity: 1 }
100% { opacity: .6 }
`;
export const GlassCard = styled(Paper)(() => ({
position: 'relative',
overflow: 'hidden',
borderRadius: 18,
background: 'rgba(0,0,0,0.45)',
border: '1px solid rgba(255,255,255,0.12)',
backdropFilter: 'blur(14px)',
boxShadow: '0 16px 40px rgba(0,0,0,0.45)',
}));
export const Glow = styled('div')(() => ({
position: 'absolute',
inset: -2,
background:
'radial-gradient(400px 120px at 10% 0%, rgba(242,113,33,0.25), transparent 60%),' +
'radial-gradient(400px 120px at 90% 0%, rgba(233,64,205,0.25), transparent 60%)',
pointerEvents: 'none',
animation: `${glowPulse} 5s ease-in-out infinite`,
}));
export const GradientButton = styled(Button)(() => ({
background: GRADIENT,
borderRadius: 999,
textTransform: 'none',
fontWeight: 700,
'&:hover': {
background: GRADIENT,
filter: 'brightness(1.08)',
},
}));
export const SoftButton = styled(Button)(() => ({
borderRadius: 999,
textTransform: 'none',
color: '#fff',
border: '1px solid rgba(255,255,255,0.14)',
background: 'rgba(255,255,255,0.06)',
'&:hover': { background: 'rgba(255,255,255,0.1)' },
}));
type Severity = 'error' | 'warning' | 'info' | 'success';
const severityColor: Record<Severity, string> = {
info: '#4fc3f7',
success: '#4caf50',
warning: '#ff9800',
error: '#f44336',
};
export const Notifier = () => {
const [open, setOpen] = useState(false);
const [message, setMessage] = useState('');
const [severity, setSeverity] = useState<
'error' | 'warning' | 'info' | 'success'
>('info');
const [severity, setSeverity] = useState<Severity>('info');
const [hasUpdateAvailable, setHasUpdateAvailable] = useState(false);
useEffect(() => {
@ -24,6 +89,15 @@ export const Notifier = () => {
};
}, []);
useEffect(() => {
if (process.env.NODE_ENV === 'development') {
setMessage('Доступно новое обновление (dev preview)');
setSeverity('info');
setHasUpdateAvailable(true);
setOpen(true);
}
}, []);
const handleClose = () => {
setOpen(false);
};
@ -34,30 +108,48 @@ export const Notifier = () => {
};
return (
<Box>
<Snackbar
open={open}
autoHideDuration={hasUpdateAvailable ? null : 6000}
onClose={handleClose}
>
<Alert
severity={severity}
action={
hasUpdateAvailable && (
<>
<Button color="primary" size="small" onClick={handleUpdate}>
Обновить сейчас
</Button>
<Button color="secondary" size="small" onClick={handleClose}>
Позже
</Button>
</>
)
}
<Snackbar
open={open}
onClose={handleClose}
autoHideDuration={hasUpdateAvailable ? null : 5000}
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
>
<GlassCard sx={{ minWidth: 340 }}>
<Glow />
<Box
sx={{
p: 2,
position: 'relative',
gap: 1,
display: 'flex',
flexDirection: 'column',
}}
>
{message}
</Alert>
</Snackbar>
</Box>
<Typography
sx={{
color: 'rgba(255,255,255,0.82)',
fontSize: 13.5,
lineHeight: 1.35,
pr: hasUpdateAvailable ? 1 : 0,
}}
>
{message}
</Typography>
{hasUpdateAvailable && (
<Stack direction="row" spacing={1} justifyContent="center" gap={1}>
<SoftButton size="small" onClick={handleUpdate}>
Обновить
</SoftButton>
<SoftButton size="small" onClick={handleClose}>
Позже
</SoftButton>
</Stack>
)}
</Box>
</GlassCard>
</Snackbar>
);
};

View File

@ -134,13 +134,13 @@ export const OnlinePlayersPanel: React.FC<OnlinePlayersPanelProps> = ({
);
}
if (!onlinePlayers.length) {
return (
<Typography sx={{ mt: 2, color: 'rgba(255,255,255,0.75)', fontWeight: 700 }}>
Сейчас на серверах никого нет.
</Typography>
);
}
// if (!onlinePlayers.length) {
// return (
// <Typography sx={{ mt: 2, color: 'rgba(255,255,255,0.75)', fontWeight: 700 }}>
// Сейчас на серверах никого нет.
// </Typography>
// );
// }
const totalOnline = onlinePlayers.length;
@ -371,82 +371,119 @@ export const OnlinePlayersPanel: React.FC<OnlinePlayersPanelProps> = ({
},
}}
>
{filteredPlayers.map((p) => {
const isMe = p.username === currentUsername;
{filteredPlayers.length ? (
filteredPlayers.map((p) => {
const isMe = p.username === currentUsername;
return (
<Paper
key={p.uuid}
elevation={0}
sx={{
px: '1.1vw',
py: '0.75vw',
borderRadius: '1.1vw',
background: 'rgba(255,255,255,0.04)',
border: '1px solid rgba(255,255,255,0.08)',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
gap: '1vw',
transition: 'transform 0.18s ease, border-color 0.18s ease, box-shadow 0.18s ease',
'&:hover': {
transform: 'scale(1.01)',
borderColor: 'rgba(242,113,33,0.35)',
boxShadow: '0 0.8vw 2.4vw rgba(0,0,0,0.45)',
},
}}
>
<Box sx={{ display: 'flex', alignItems: 'center', gap: '0.8vw', minWidth: 0 }}>
<HeadAvatar skinUrl={skinMap[p.uuid]} size={26} />
<Typography
return (
<Paper
key={p.uuid}
elevation={0}
sx={{
px: '1.1vw',
py: '0.75vw',
borderRadius: '1.1vw',
background: 'rgba(255,255,255,0.04)',
border: '1px solid rgba(255,255,255,0.08)',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
gap: '1vw',
transition:
'transform 0.18s ease, border-color 0.18s ease, box-shadow 0.18s ease',
'&:hover': {
transform: 'scale(1.01)',
borderColor: 'rgba(242,113,33,0.35)',
boxShadow: '0 0.8vw 2.4vw rgba(0,0,0,0.45)',
},
}}
>
<Box
sx={{
fontFamily: 'Benzin-Bold',
color: 'rgba(255,255,255,0.92)',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
display: 'flex',
alignItems: 'center',
gap: '0.8vw',
minWidth: 0,
}}
>
{p.username}
</Typography>
<HeadAvatar skinUrl={skinMap[p.uuid]} size={26} />
<Typography
sx={{
fontFamily: 'Benzin-Bold',
color: 'rgba(255,255,255,0.92)',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{p.username}
</Typography>
{isMe && (
{isMe && (
<Chip
label="Вы"
size="small"
sx={{
height: '1.55rem',
fontSize: '0.72rem',
fontWeight: 900,
color: 'white',
borderRadius: '999px',
backgroundImage: GRADIENT,
boxShadow: '0 10px 22px rgba(0,0,0,0.45)',
}}
/>
)}
</Box>
<Box
sx={{
display: 'flex',
alignItems: 'center',
gap: '0.6vw',
flexShrink: 0,
}}
>
<Chip
label="Вы"
label={translateServer(p.serverName)}
size="small"
sx={{
height: '1.55rem',
fontFamily: 'Benzin-Bold',
fontSize: '0.72rem',
fontWeight: 900,
color: 'white',
borderRadius: '999px',
backgroundImage: GRADIENT,
boxShadow: '0 10px 22px rgba(0,0,0,0.45)',
color: 'rgba(255,255,255,0.88)',
background:
'linear-gradient(120deg, rgba(242,113,33,0.18), rgba(233,64,205,0.12), rgba(138,35,135,0.16))',
border: '1px solid rgba(255,255,255,0.10)',
backdropFilter: 'blur(12px)',
}}
/>
)}
</Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: '0.6vw', flexShrink: 0 }}>
<Chip
label={translateServer(p.serverName)}
size="small"
sx={{
fontFamily: 'Benzin-Bold',
fontSize: '0.72rem',
borderRadius: '999px',
color: 'rgba(255,255,255,0.88)',
background:
'linear-gradient(120deg, rgba(242,113,33,0.18), rgba(233,64,205,0.12), rgba(138,35,135,0.16))',
border: '1px solid rgba(255,255,255,0.10)',
backdropFilter: 'blur(12px)',
}}
/>
{/* onlineSince можно потом красиво форматировать */}
</Box>
</Paper>
);
})}
</Box>
</Paper>
);
})
) : (
<Box
sx={{
py: '1.4vw',
px: '1.1vw',
borderRadius: '1.1vw',
background: 'rgba(255,255,255,0.03)',
border: '1px dashed rgba(255,255,255,0.14)',
textAlign: 'center',
}}
>
<Typography
sx={{
fontFamily: 'Benzin-Bold',
fontSize: '0.95vw',
color: 'rgba(255,255,255,0.78)',
}}
>
Сейчас на сервере никого нет!
</Typography>
</Box>
)}
</Box>
</Paper>
);

View File

@ -33,6 +33,10 @@ export default function PageHeader() {
path === '/registration' ||
path === '/marketplace' ||
path === '/profile' ||
path === '/inventory' ||
path === '/fakepaymentpage' ||
path === '/promocode' ||
path === '/voice' ||
path.startsWith('/launch')
) {
return { title: '', subtitle: '', hidden: true };
@ -42,7 +46,7 @@ export default function PageHeader() {
return {
title: 'Настройки',
subtitle: 'Персонализация интерфейса и поведения лаунчера',
}
};
}
if (path === '/news') {
@ -62,7 +66,8 @@ export default function PageHeader() {
if (path.startsWith('/daily')) {
return {
title: 'Ежедневные награды',
subtitle: 'Ежедневный вход на сервер приносит бонусы и полезные награды!',
subtitle:
'Ежедневный вход на сервер приносит бонусы и полезные награды!',
};
}

View File

@ -1,5 +1,5 @@
// src/renderer/components/PlayerInventory.tsx
import { useEffect, useState } from 'react';
import React, { useEffect, useImperativeHandle, useState } from 'react';
import {
Box,
Typography,
@ -22,6 +22,118 @@ import {
PlayerInventoryItem,
} from '../api';
import { FullScreenLoader } from './FullScreenLoader';
import CloseIcon from '@mui/icons-material/Close';
import IconButton from '@mui/material/IconButton';
const GRADIENT =
'linear-gradient(71deg, #F27121 0%, #E940CD 70%, #8A2387 100%)';
const GLASS_PAPER_SX = {
borderRadius: '1.2vw',
overflow: 'hidden',
background:
'radial-gradient(circle at 10% 10%, rgba(242,113,33,0.14), transparent 55%), radial-gradient(circle at 90% 20%, rgba(233,64,205,0.12), transparent 55%), rgba(10,10,20,0.86)',
border: '1px solid rgba(255,255,255,0.08)',
boxShadow: '0 1.2vw 3.2vw rgba(0,0,0,0.55)',
color: 'white',
backdropFilter: 'blur(16px)',
} as const;
const DIALOG_TITLE_SX = {
fontFamily: 'Benzin-Bold',
pr: 6,
position: 'relative',
} as const;
const CLOSE_BTN_SX = {
position: 'absolute',
top: 10,
right: 10,
color: 'rgba(255,255,255,0.9)',
border: '1px solid rgba(255,255,255,0.12)',
background: 'rgba(255,255,255,0.06)',
backdropFilter: 'blur(12px)',
'&:hover': { transform: 'scale(1.05)', background: 'rgba(255,255,255,0.10)' },
transition: 'all 0.2s ease',
} as const;
const DIVIDERS_SX = {
borderColor: 'rgba(255,255,255,0.10)',
} as const;
const INPUT_SX = {
mt: 1.2,
'& .MuiInputLabel-root': {
color: 'rgba(255,255,255,0.72)',
fontFamily: 'Benzin-Bold',
letterSpacing: 0.3,
textTransform: 'uppercase',
},
'& .MuiInputLabel-root.Mui-focused': {
color: 'rgba(255,255,255,0.92)',
},
'& .MuiOutlinedInput-root': {
position: 'relative',
borderRadius: '1.1vw',
overflow: 'hidden',
background:
'radial-gradient(circle at 10% 10%, rgba(242,113,33,0.16), transparent 55%), radial-gradient(circle at 90% 20%, rgba(233,64,205,0.12), transparent 55%), rgba(10,10,20,0.92)',
border: '1px solid rgba(255,255,255,0.10)',
boxShadow: '0 1.2vw 3.0vw rgba(0,0,0,0.55)',
backdropFilter: 'blur(14px)',
'& .MuiOutlinedInput-notchedOutline': { border: 'none' },
'& input': {
fontFamily: 'Benzin-Bold',
fontSize: '1.0rem',
padding: '1.0vw 1.0vw',
color: 'rgba(255,255,255,0.95)',
},
transition: 'transform 0.18s ease, filter 0.18s ease, border-color 0.18s ease',
'&:hover': {
transform: 'scale(1.01)',
borderColor: 'rgba(255,255,255,0.14)',
},
'&.Mui-focused': {
borderColor: 'rgba(255,255,255,0.18)',
filter: 'brightness(1.03)',
},
'&:after': {
content: '""',
position: 'absolute',
left: 0,
right: 0,
bottom: 0,
height: '0.18vw',
borderRadius: '999px',
background: GRADIENT,
opacity: 0.92,
pointerEvents: 'none',
},
},
} as const;
const PRIMARY_BTN_SX = {
fontFamily: 'Benzin-Bold',
color: '#fff',
background: GRADIENT,
borderRadius: '999px',
px: '1.6vw',
py: '0.65vw',
boxShadow: '0 1.0vw 2.6vw rgba(0,0,0,0.45)',
'&:hover': { filter: 'brightness(1.05)' },
} as const;
const SECONDARY_BTN_SX = {
color: 'rgba(255,255,255,0.85)',
fontFamily: 'Benzin-Bold',
} as const;
interface PlayerInventoryProps {
username: string;
@ -29,11 +141,12 @@ interface PlayerInventoryProps {
onSellSuccess?: () => void; // Callback для обновления маркетплейса после продажи
}
export default function PlayerInventory({
username,
serverIp,
onSellSuccess,
}: PlayerInventoryProps) {
export type PlayerInventoryHandle = {
refresh: () => Promise<void>;
};
const PlayerInventory = React.forwardRef<PlayerInventoryHandle, PlayerInventoryProps>(
({ username, serverIp, onSellSuccess }, ref) => {
const [loading, setLoading] = useState<boolean>(false);
const [inventoryItems, setInventoryItems] = useState<PlayerInventoryItem[]>(
[],
@ -48,6 +161,8 @@ export default function PlayerInventory({
const [sellLoading, setSellLoading] = useState<boolean>(false);
const [sellError, setSellError] = useState<string | null>(null);
const [description, setDescription] = useState('');
// Функция для запроса инвентаря игрока
const fetchPlayerInventory = async () => {
try {
@ -96,6 +211,12 @@ export default function PlayerInventory({
}
};
useImperativeHandle(ref, () => ({
refresh: async () => {
await fetchPlayerInventory();
},
}));
// Открываем диалог для продажи предмета
const handleOpenSellDialog = (item: PlayerInventoryItem) => {
setSelectedItem(item);
@ -137,6 +258,7 @@ export default function PlayerInventory({
amount,
price,
serverIp,
description,
);
// Проверяем статус операции
@ -183,7 +305,7 @@ export default function PlayerInventory({
};
return (
<Box sx={{ mt: '1vw' }}>
<Box>
<Box
sx={{
display: 'flex',
@ -195,25 +317,6 @@ export default function PlayerInventory({
<Typography variant="h5" color="white">
Ваш инвентарь
</Typography>
<Button
variant="outlined"
onClick={fetchPlayerInventory}
disabled={loading}
sx={{
borderRadius: '20px',
p: '10px 25px',
color: 'white',
borderColor: 'rgba(255, 77, 77, 1)',
'&:hover': {
backgroundColor: 'rgba(255, 77, 77, 1)',
borderColor: 'rgba(255, 77, 77, 1)',
},
fontFamily: 'Benzin-Bold',
fontSize: '1vw',
}}
>
Обновить
</Button>
</Box>
{error && (
@ -223,7 +326,7 @@ export default function PlayerInventory({
)}
{loading ? (
<FullScreenLoader fullScreen={false} />
<FullScreenLoader fullScreen={false} message="Загрузка инвентаря..." />
) : (
<>
{inventoryItems.length === 0 ? (
@ -311,79 +414,157 @@ export default function PlayerInventory({
)}
{/* Диалог для продажи предмета */}
<Dialog open={sellDialogOpen} onClose={handleCloseSellDialog}>
<DialogTitle>Продать предмет</DialogTitle>
<DialogContent>
<Dialog
open={sellDialogOpen}
onClose={handleCloseSellDialog}
fullWidth
maxWidth="xs"
PaperProps={{ sx: GLASS_PAPER_SX }}
>
<DialogTitle sx={DIALOG_TITLE_SX}>
Продать предмет
<IconButton onClick={handleCloseSellDialog} sx={CLOSE_BTN_SX}>
<CloseIcon fontSize="small" />
</IconButton>
</DialogTitle>
<DialogContent dividers sx={DIVIDERS_SX}>
{selectedItem && (
<Box sx={{ mt: 1 }}>
<Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
<CardMedia
<Box sx={{ mt: 0.5 }}>
{/* Верхняя карточка предмета */}
<Box
sx={{
display: 'flex',
alignItems: 'center',
gap: '1vw',
p: '0.9vw',
borderRadius: '1.1vw',
border: '1px solid rgba(255,255,255,0.10)',
background: 'rgba(255,255,255,0.05)',
mb: 1.1,
}}
>
<Box
component="img"
sx={{
width: 50,
height: 50,
objectFit: 'contain',
mr: 2,
}}
image={`https://cdn.minecraft.popa-popa.ru/textures/${selectedItem.material.toLowerCase()}.png`}
src={`https://cdn.minecraft.popa-popa.ru/textures/${selectedItem.material.toLowerCase()}.png`}
alt={selectedItem.material}
draggable={false}
style={{
width: 54,
height: 54,
objectFit: 'contain',
imageRendering: 'pixelated',
userSelect: 'none',
}}
/>
<Typography variant="h6">
{getItemDisplayName(selectedItem.material)}
</Typography>
<Box sx={{ minWidth: 0 }}>
<Typography
sx={{
fontFamily: 'Benzin-Bold',
fontSize: '1.05rem',
lineHeight: 1.1,
color: 'rgba(255,255,255,0.95)',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
title={getItemDisplayName(selectedItem.material)}
>
{getItemDisplayName(selectedItem.material)}
</Typography>
<Typography sx={{ color: 'rgba(255,255,255,0.70)', fontWeight: 800, mt: 0.4 }}>
Доступно: <span style={{ color: 'rgba(255,255,255,0.92)' }}>{selectedItem.amount}</span>
</Typography>
</Box>
</Box>
<Typography variant="body2" gutterBottom>
Всего доступно: {selectedItem.amount}
</Typography>
{/* Поля */}
<TextField
label="Количество"
type="number"
fullWidth
margin="dense"
value={amount}
onChange={(e) =>
setAmount(
Math.min(
parseInt(e.target.value) || 0,
selectedItem.amount,
),
)
}
onChange={(e) => {
const v = Number(e.target.value);
const safe = Number.isFinite(v) ? v : 0;
setAmount(Math.min(Math.max(1, safe), selectedItem.amount));
}}
inputProps={{ min: 1, max: selectedItem.amount }}
sx={INPUT_SX}
/>
<TextField
label="Цена (за всё)"
type="number"
fullWidth
margin="dense"
value={price}
onChange={(e) => setPrice(parseInt(e.target.value) || 0)}
onChange={(e) => {
const v = Number(e.target.value);
setPrice(Number.isFinite(v) ? v : 0);
}}
inputProps={{ min: 1 }}
sx={INPUT_SX}
/>
<TextField
label="Описание (необязательно)"
fullWidth
value={description}
onChange={(e) => setDescription(e.target.value)}
inputProps={{ min: 1 }}
sx={INPUT_SX}
/>
{sellError && (
<Alert severity="error" sx={{ mt: 2 }}>
<Box
sx={{
mt: 1.2,
p: '0.9vw',
borderRadius: '1.0vw',
border: '1px solid rgba(255,70,70,0.22)',
background: 'rgba(255,70,70,0.12)',
color: 'rgba(255,255,255,0.92)',
fontWeight: 800,
}}
>
{sellError}
</Alert>
</Box>
)}
{/* Подсказка */}
<Typography sx={{ mt: 1.1, color: 'rgba(255,255,255,0.60)', fontWeight: 700 }}>
Цена указывается за весь лот!
</Typography>
</Box>
)}
</DialogContent>
<DialogActions>
<Button onClick={handleCloseSellDialog}>Отмена</Button>
<DialogActions sx={{ p: '1.2vw' }}>
<Button onClick={handleCloseSellDialog} sx={SECONDARY_BTN_SX}>
Отмена
</Button>
<Button
onClick={handleSellItem}
variant="contained"
color="primary"
disableRipple
disabled={sellLoading}
sx={{
...PRIMARY_BTN_SX,
...(sellLoading
? {
background: 'rgba(255,255,255,0.10)',
boxShadow: 'none',
color: 'rgba(255,255,255,0.55)',
}
: null),
}}
>
{sellLoading ? <FullScreenLoader fullScreen={false} /> : 'Продать'}
{sellLoading ? 'Выставляем…' : 'Продать'}
</Button>
</DialogActions>
</Dialog>
</Box>
);
}
})
export default PlayerInventory;

View File

@ -13,6 +13,8 @@ import CoinsDisplay from './CoinsDisplay';
import { CapePreview } from './CapePreview';
import VisibilityIcon from '@mui/icons-material/Visibility';
import CapePreviewModal from './PlayerPreviewModal';
import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined';
import CaseItemsDialog from './CaseItemsDialog';
export type ShopItemType = 'case' | 'cape';
@ -32,6 +34,7 @@ export interface ShopItemProps {
export default function ShopItem({
type,
id,
name,
description,
imageUrl,
@ -46,6 +49,7 @@ export default function ShopItem({
type === 'case' ? (isOpening ? 'Открываем...' : 'Открыть кейс') : 'Купить';
const [previewOpen, setPreviewOpen] = useState(false);
const [caseInfoOpen, setCaseInfoOpen] = useState(false);
return (
<Card
@ -66,8 +70,8 @@ export default function ShopItem({
transition: 'transform 0.35s ease, box-shadow 0.35s ease',
'&:hover': {
transform: 'scale(1.01)',
boxShadow: '0 20px 20px rgba(242,113,33,0.1)',
borderColor: 'rgba(200, 33, 242, 0.35)',
boxShadow: '0 1.2vw 3.2vw rgba(53, 3, 66, 0.75)',
},
}}
>
@ -78,7 +82,7 @@ export default function ShopItem({
inset: 0,
pointerEvents: 'none',
background:
'radial-gradient(circle at top, rgba(242,113,33,0.25), transparent 60%)',
'radial-gradient(circle at 10% 10%, rgba(242,113,33,0.10), transparent 55%), radial-gradient(circle at 90% 20%, rgba(233,64,205,0.16), transparent 55%)',
}}
/>
@ -193,15 +197,35 @@ export default function ShopItem({
)}
{type === 'case' && typeof itemsCount === 'number' && (
<Typography
sx={{
color: 'rgba(255,255,255,0.6)',
fontSize: '0.75rem',
mt: 1,
}}
>
Предметов в кейсе: {itemsCount}
</Typography>
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mt: 1 }}>
<Typography
sx={{
color: 'rgba(255,255,255,0.6)',
fontSize: '0.75rem',
}}
>
Предметов в кейсе: {itemsCount}
</Typography>
<IconButton
size="small"
onClick={(e) => {
e.preventDefault();
e.stopPropagation(); // важно: чтобы не сработало onClick карточки/кнопки открытия
setCaseInfoOpen(true);
}}
sx={{
ml: 1,
color: 'rgba(255,255,255,0.85)',
border: '1px solid rgba(255,255,255,0.12)',
background: 'rgba(255,255,255,0.04)',
'&:hover': { transform: 'scale(1.05)' },
transition: 'all 0.25s ease',
}}
>
<InfoOutlinedIcon fontSize="inherit" />
</IconButton>
</Box>
)}
</Box>
@ -219,6 +243,7 @@ export default function ShopItem({
fontFamily: 'Benzin-Bold',
borderRadius: '2.5vw',
fontSize: '0.85rem',
color: 'white',
'&:hover': {
transform: 'scale(1.02)',
},
@ -236,6 +261,14 @@ export default function ShopItem({
skinUrl={playerSkinUrl}
/>
)}
{type === 'case' && (
<CaseItemsDialog
open={caseInfoOpen}
onClose={() => setCaseInfoOpen(false)}
caseId={id}
caseName={name}
/>
)}
</Card>
);
}

View File

@ -21,6 +21,15 @@ import EmojiEventsIcon from '@mui/icons-material/EmojiEvents';
import PersonIcon from '@mui/icons-material/Person';
import SettingsIcon from '@mui/icons-material/Settings';
import { useTheme } from '@mui/material/styles';
import InventoryIcon from '@mui/icons-material/Inventory';
import { RiCoupon3Fill } from 'react-icons/ri';
import type { NotificationPosition } from '../components/Notifications/CustomNotification';
import {
isNotificationsEnabled,
getNotifPositionFromSettings,
} from '../utils/notifications';
declare global {
interface Window {
electron: {
@ -72,10 +81,48 @@ export default function TopBar({ onRegister, username }: TopBarProps) {
null,
);
// ===== QUICK LAUNCH ===== \\
const [lastVersion, setLastVersion] = useState<null | any>(null);
useEffect(() => {
try {
const raw = localStorage.getItem('last_launched_version');
if (!raw) return;
setLastVersion(JSON.parse(raw));
} catch {
setLastVersion(null);
}
}, []);
// ===== QUICK LAUNCH ===== \\
const path = location.pathname || '';
const isAuthPage =
path.startsWith('/login') || path.startsWith('/registration');
const [notifOpen, setNotifOpen] = useState(false);
const [notifMsg, setNotifMsg] = useState<React.ReactNode>('');
const [notifSeverity, setNotifSeverity] = useState<
'success' | 'info' | 'warning' | 'error'
>('info');
const [notifPos, setNotifPos] = useState<NotificationPosition>({
vertical: 'bottom',
horizontal: 'center',
});
const showNotification = (
message: React.ReactNode,
severity: 'success' | 'info' | 'warning' | 'error' = 'info',
position: NotificationPosition = getNotifPositionFromSettings(),
) => {
if (!isNotificationsEnabled()) return;
setNotifMsg(message);
setNotifSeverity(severity);
setNotifPos(position);
setNotifOpen(true);
};
const TAB_ROUTES: Array<{
value: number;
match: (p: string) => boolean;
@ -101,6 +148,11 @@ export default function TopBar({ onRegister, username }: TopBarProps) {
match: (p) => p.startsWith('/marketplace'),
to: '/marketplace',
},
{
value: 4,
match: (p) => p.startsWith('/voice'),
to: '/voice',
},
];
const selectedTab =
@ -205,7 +257,10 @@ export default function TopBar({ onRegister, username }: TopBarProps) {
const logout = () => {
localStorage.removeItem('launcher_config');
localStorage.removeItem(`coins:${username}`);
localStorage.removeItem('last_route');
navigate('/login');
window.electron.ipcRenderer.invoke('auth-changed', { isAuthed: false });
};
const loadSkin = useCallback(async () => {
@ -251,8 +306,79 @@ export default function TopBar({ onRegister, username }: TopBarProps) {
window.removeEventListener('skin-updated', handler as EventListener);
}, [loadSkin]);
useEffect(() => {
const handler = () => {
requestAnimationFrame(updateGradientVars);
};
window.addEventListener('settings-updated', handler as EventListener);
return () =>
window.removeEventListener('settings-updated', handler as EventListener);
}, [updateGradientVars]);
const handleQuickLaunch = async () => {
const raw = localStorage.getItem('last_launched_version');
if (!raw) {
showNotification('Вы не запускали ни одну из сборок!', 'warning');
return;
}
const ctx = JSON.parse(raw);
const savedConfig = JSON.parse(
localStorage.getItem('launcher_config') || '{}',
);
if (!savedConfig.accessToken) {
showNotification('Вы не авторизованы', 'error');
return;
}
await window.electron.ipcRenderer.invoke('launch-minecraft', {
accessToken: savedConfig.accessToken,
uuid: savedConfig.uuid,
username: savedConfig.username,
memory: ctx.memory,
baseVersion: ctx.baseVersion,
fabricVersion: ctx.fabricVersion,
packName: ctx.packName,
serverIp: ctx.serverIp,
isVanillaVersion: ctx.isVanillaVersion,
versionToLaunchOverride: ctx.versionToLaunchOverride,
});
};
const getLastLaunchLabel = (v: any) => {
if (!v) return '';
const title = v.isVanillaVersion
? `Minecraft ${v.versionId}`
: `Сборка ${v.packName}`;
const details = [
v.baseVersion ? `MC ${v.baseVersion}` : null,
v.memory ? `${v.memory} MB RAM` : null,
]
.filter(Boolean)
.join(' · ');
return (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: '0.2vw' }}>
<Typography sx={{ fontSize: '0.9vw', fontWeight: 600 }}>
{title}
</Typography>
<Typography sx={{ fontSize: '0.75vw', opacity: 0.7 }}>
{details}
</Typography>
</Box>
);
};
return (
<Box
className={isAuthPage ? undefined : 'glass-ui'}
sx={[
{
display: 'flex',
@ -418,6 +544,142 @@ export default function TopBar({ onRegister, username }: TopBarProps) {
marginRight: '1vw',
}}
>
{lastVersion && (
<CustomTooltip
title={getLastLaunchLabel(lastVersion)}
arrow
placement="bottom"
essential
TransitionProps={{ timeout: 120 }}
>
<Button
onClick={handleQuickLaunch}
disableRipple
disableFocusRipple
sx={{
minWidth: 'unset',
width: '3vw',
height: '3vw',
borderRadius: '3vw',
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
overflow: 'hidden',
px: '0.8vw',
background:
'radial-gradient(circle at 10% 10%, rgba(242,113,33,0.20), transparent 55%), radial-gradient(circle at 90% 20%, rgba(233,64,205,0.16), transparent 55%), rgba(10,10,20,0.92)',
border: '1px solid rgba(255,255,255,0.10)',
boxShadow: '0 1.4vw 3.8vw rgba(0,0,0,0.55)',
color: 'white',
backdropFilter: 'blur(14px)',
transition: 'all 0.3s ease',
'& .quick-text': {
opacity: 0,
whiteSpace: 'nowrap',
marginRight: '0.6vw',
fontSize: '0.9vw',
fontFamily: 'Benzin-Bold',
transform: 'translateX(10px)',
transition: 'all 0.25s ease',
},
'&:hover': {
width: '16.5vw',
transform: 'scale(1.05)',
'& .quick-text': {
opacity: 1,
transform: 'translateX(0)',
},
},
'&:after': {
content: '""',
position: 'absolute',
left: '0%',
right: '0%',
bottom: 0,
height: '0.15vw',
borderRadius: '999px',
// background:
// 'linear-gradient(71deg, #F27121 0%, #E940CD 70%, #8A2387 100%)',
opacity: 0.9,
},
}}
>
<span className="quick-text">Быстрый запуск</span>
<span style={{ fontSize: '1vw' }}></span>
</Button>
</CustomTooltip>
)}
<Button
onClick={() => navigate('/voice')}
disableRipple
disableFocusRipple
sx={{
minWidth: 'unset',
width: '3vw',
height: '3vw',
borderRadius: '3vw',
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
overflow: 'hidden',
px: '0.8vw',
background:
'radial-gradient(circle at 10% 10%, rgba(242,113,33,0.20), transparent 55%), radial-gradient(circle at 90% 20%, rgba(233,64,205,0.16), transparent 55%), rgba(10,10,20,0.92)',
border: '1px solid rgba(255,255,255,0.10)',
boxShadow: '0 1.4vw 3.8vw rgba(0,0,0,0.55)',
color: 'white',
backdropFilter: 'blur(14px)',
transition: 'all 0.3s ease',
'& .quick-text': {
opacity: 0,
whiteSpace: 'nowrap',
marginRight: '0.6vw',
fontSize: '0.9vw',
fontFamily: 'Benzin-Bold',
transform: 'translateX(10px)',
transition: 'all 0.25s ease',
},
'&:hover': {
width: '16.5vw',
transform: 'scale(1.05)',
'& .quick-text': {
opacity: 1,
transform: 'translateX(0)',
},
},
'&:after': {
content: '""',
position: 'absolute',
left: '0%',
right: '0%',
bottom: 0,
height: '0.15vw',
borderRadius: '999px',
// background:
// 'linear-gradient(71deg, #F27121 0%, #E940CD 70%, #8A2387 100%)',
opacity: 0.9,
},
}}
>
<span className="quick-text">Голосовой чат</span>
<span style={{ fontSize: '1vw' }}>🎙</span>
</Button>
{!isLoginPage && !isRegistrationPage && username && (
<Box sx={{ display: 'flex', alignItems: 'center', gap: '1vw' }}>
<HeadAvatar
@ -439,6 +701,8 @@ export default function TopBar({ onRegister, username }: TopBarProps) {
size="medium"
autoUpdate={true}
showTooltip={true}
onClick={() => navigate('/fakepaymentpage')}
disableRefreshOnClick={true} // чтобы клик не дёргал fetchCoins
/>
)}
@ -561,6 +825,19 @@ export default function TopBar({ onRegister, username }: TopBarProps) {
<PersonIcon sx={{ fontSize: '2vw' }} /> Профиль
</MenuItem>
<MenuItem
onClick={() => {
handleAvatarMenuClose();
navigate('/inventory');
}}
sx={[
{ fontSize: '1.5vw', gap: '0.5vw', py: '0.7vw' },
theme.launcher.topbar.menuItem,
]}
>
<InventoryIcon sx={{ fontSize: '2vw' }} /> Инвентарь
</MenuItem>
{/* ===== 2 строка: ежедневные задания ===== */}
<MenuItem
onClick={() => {
@ -602,27 +879,42 @@ export default function TopBar({ onRegister, username }: TopBarProps) {
<SettingsIcon sx={{ fontSize: '2vw' }} /> Настройки
</MenuItem>
<MenuItem
onClick={() => {
handleAvatarMenuClose();
navigate('/promocode');
}}
sx={[
{ fontSize: '1.5vw', gap: '0.5vw', py: '0.7vw' },
theme.launcher.topbar.menuItem,
]}
>
<RiCoupon3Fill style={{ fontSize: '2vw' }} /> Промокоды
</MenuItem>
<Divider sx={{ my: '0.4vw', ...theme.launcher.topbar.menuDivider }} />
{!isLoginPage && !isRegistrationPage && username && (
<Button
variant="outlined"
color="primary"
onClick={() => {
handleAvatarMenuClose();
logout();
}}
sx={[
{
width: '8vw',
height: '3vw',
fontSize: '1.2vw',
m: '0 0 0 18vw',
},
theme.launcher.topbar.logoutButton,
]}
>
Выйти
</Button>
<Box sx={{ display: 'flex', justifyContent: 'center' }}>
<Button
variant="outlined"
color="primary"
onClick={() => {
handleAvatarMenuClose();
logout();
}}
sx={[
{
width: '90%',
height: '3vw',
fontSize: '1.2vw',
mx: '1vw',
},
theme.launcher.topbar.logoutButton,
]}
>
Выйти
</Button>
</Box>
)}
{/* ↓↓↓ дальше ты сам добавишь пункты ↓↓↓ */}

View File

@ -0,0 +1,112 @@
import {
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Button,
TextField,
FormControlLabel,
Switch,
Typography,
} from '@mui/material';
import { useState } from 'react';
export function CreateRoomDialog({
open,
onClose,
onCreate,
}: {
open: boolean;
onClose: () => void;
onCreate: (data: { name: string; isPublic: boolean }) => Promise<{
invite_code?: string | null;
}>;
}) {
const [name, setName] = useState('');
const [isPublic, setIsPublic] = useState(true);
const [inviteCode, setInviteCode] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const handleCreate = async () => {
setLoading(true);
const res = await onCreate({
name,
isPublic,
});
if (!isPublic && res?.invite_code) {
setInviteCode(res.invite_code);
} else {
onClose();
}
setLoading(false);
};
return (
<Dialog open={open} onClose={onClose} maxWidth="xs" fullWidth>
<DialogTitle>Создать комнату</DialogTitle>
<DialogContent>
{!inviteCode ? (
<>
<TextField
autoFocus
fullWidth
label="Название комнаты"
value={name}
onChange={(e) => setName(e.target.value)}
margin="dense"
/>
<FormControlLabel
control={
<Switch
checked={isPublic}
onChange={(e) => setIsPublic(e.target.checked)}
/>
}
label={isPublic ? 'Публичная' : 'Приватная'}
sx={{ mt: 1 }}
/>
</>
) : (
<>
<Typography sx={{ mb: 1 }}>Код для входа в комнату:</Typography>
<TextField
fullWidth
value={inviteCode}
InputProps={{ readOnly: true }}
/>
<Button
sx={{ mt: 2 }}
fullWidth
onClick={() => {
navigator.clipboard.writeText(inviteCode);
}}
>
Скопировать код
</Button>
</>
)}
</DialogContent>
<DialogActions>
<Button onClick={onClose}>Закрыть</Button>
{!inviteCode && (
<Button
variant="contained"
onClick={handleCreate}
disabled={!name || loading}
>
Создать
</Button>
)}
</DialogActions>
</Dialog>
);
}

View File

@ -0,0 +1,58 @@
import {
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Button,
TextField,
} from '@mui/material';
import { useState } from 'react';
export function JoinByCodeDialog({
open,
onClose,
onJoin,
}: {
open: boolean;
onClose: () => void;
onJoin: (code: string) => Promise<void>;
}) {
const [code, setCode] = useState('');
const [loading, setLoading] = useState(false);
const handleJoin = async () => {
setLoading(true);
await onJoin(code);
setLoading(false);
setCode('');
onClose();
};
return (
<Dialog open={open} onClose={onClose} maxWidth="xs" fullWidth>
<DialogTitle>Войти по коду</DialogTitle>
<DialogContent>
<TextField
autoFocus
fullWidth
label="Invite-код"
value={code}
onChange={(e) => setCode(e.target.value)}
margin="dense"
/>
</DialogContent>
<DialogActions>
<Button onClick={onClose}>Отмена</Button>
<Button
variant="contained"
onClick={handleJoin}
disabled={!code || loading}
>
Войти
</Button>
</DialogActions>
</Dialog>
);
}

View File

@ -0,0 +1,115 @@
import { Box, Typography, Button } from '@mui/material';
import { glassBox, GRADIENT } from '../../theme/voiceStyles';
import type { RoomInfo } from '../../types/rooms';
type Props = {
rooms: RoomInfo[];
currentRoomId: string | null;
onJoin: (roomId: string) => void;
onCreate: () => void;
onJoinByCode: () => void;
};
export function RoomsPanel({
rooms,
currentRoomId,
onJoin,
onCreate,
onJoinByCode,
}: Props) {
return (
<Box
sx={{
width: 300,
p: '1.2vw',
display: 'flex',
flexDirection: 'column',
gap: '1vw',
borderRadius: '1.5vw',
...glassBox,
}}
>
<Typography
sx={{
fontFamily: 'Benzin-Bold',
fontSize: '1.4vw',
backgroundImage: GRADIENT,
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
}}
>
Голосовые комнаты
</Typography>
<Box sx={{ flex: 1, overflowY: 'auto', pr: '0.3vw' }}>
{rooms.map((room) => {
const active = room.id === currentRoomId;
return (
<Box
key={room.id}
onClick={() => onJoin(room.id)}
sx={{
p: '0.9vw',
mb: '0.6vw',
borderRadius: '1vw',
cursor: 'pointer',
transition: 'all 0.18s ease',
background: active ? GRADIENT : 'rgba(255,255,255,0.04)',
color: active ? '#fff' : 'rgba(255,255,255,0.9)',
'&:hover': {
//transform: 'scale(1.01)',
background: active ? GRADIENT : 'rgba(255,255,255,0.07)',
},
}}
>
<Typography sx={{ fontWeight: 800 }}>{room.name}</Typography>
{room.users.length > 0 && (
<Box sx={{ mt: '0.4vw', pl: '0.8vw' }}>
{room.users.map((u) => (
<Typography
key={u}
sx={{
fontSize: '0.85vw',
opacity: 0.8,
}}
>
{u}
</Typography>
))}
</Box>
)}
</Box>
);
})}
</Box>
<Button
onClick={onCreate}
sx={{
borderRadius: '999px',
py: '0.8vw',
fontFamily: 'Benzin-Bold',
background: GRADIENT,
color: '#fff',
}}
>
+ Создать комнату
</Button>
<Button
onClick={onJoinByCode}
sx={{
borderRadius: '999px',
py: '0.8vw',
fontFamily: 'Benzin-Bold',
background: 'rgba(255,255,255,0.08)',
color: '#fff',
}}
>
Войти по коду
</Button>
</Box>
);
}

View File

@ -0,0 +1,131 @@
import { Box, Button, Typography } from '@mui/material';
import { useVoiceRoom } from '../../realtime/voice/useVoiceRoom';
import { useState, useEffect } from 'react';
import { getVoiceState, subscribeVoice } from '../../realtime/voice/voiceStore';
import { glassBox, GRADIENT } from '../../theme/voiceStyles';
import { HeadAvatar } from '../HeadAvatar';
import { API_BASE_URL } from '../../api';
type Props = {
roomId: string;
voice: {
disconnect: () => void;
toggleMute: () => void;
};
roomName: string;
};
export function VoicePanel({ roomId, voice, roomName }: Props) {
const [state, setState] = useState(getVoiceState());
const [skinMap, setSkinMap] = useState<Record<string, string>>({});
useEffect(() => {
const loadSkins = async () => {
const missing = state.participants.filter((u) => !skinMap[u]);
if (!missing.length) return;
try {
// ⚠️ ВАЖНО: полный URL до API
const res = await fetch(API_BASE_URL + '/users');
const data = await res.json();
const map: Record<string, string> = {};
for (const user of data.users) {
if (missing.includes(user.username) && user.skin_url) {
map[user.username] = user.skin_url;
}
}
if (Object.keys(map).length) {
setSkinMap((prev) => ({ ...prev, ...map }));
}
} catch (e) {
console.warn('Не удалось загрузить скины для голосового чата', e);
}
};
loadSkins();
}, [state.participants]);
useEffect(
() =>
subscribeVoice(() => {
setState({ ...getVoiceState() });
}),
[],
);
console.log('participants:', state.participants);
console.log('skinMap:', skinMap);
return (
<Box
sx={{
flex: 1,
ml: '1.5vw',
p: '2vw',
borderRadius: '1.5vw',
...glassBox,
}}
>
<Typography
sx={{
fontFamily: 'Benzin-Bold',
fontSize: '2vw',
mb: '1.2vw',
backgroundImage: GRADIENT,
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
}}
>
{roomName}
</Typography>
<Box sx={{ display: 'flex', gap: '1vw', mb: '2vw' }}>
<Button
onClick={voice.toggleMute}
sx={{
borderRadius: '999px',
px: '2vw',
background: 'rgba(255,255,255,0.08)',
color: '#fff',
fontFamily: 'Benzin-Bold',
}}
>
{state.muted ? 'Вкл. микрофон' : 'Выкл. микрофон'}
</Button>
<Button
onClick={voice.disconnect}
sx={{
borderRadius: '999px',
px: '2vw',
background: 'rgba(255,60,60,0.25)',
color: '#fff',
fontFamily: 'Benzin-Bold',
}}
>
Выйти
</Button>
</Box>
<Typography sx={{ mb: '0.6vw', opacity: 0.7 }}>Участники:</Typography>
{state.participants.map((u) => (
<Box
key={u}
sx={{
display: 'flex',
alignItems: 'center',
gap: '0.6vw',
mb: '0.3vw',
}}
>
<HeadAvatar skinUrl={skinMap[u]} size={28} />
<Typography>{u}</Typography>
</Box>
))}
</Box>
);
}

View File

@ -1,27 +1,70 @@
import { useState } from 'react';
interface AuthSession {
accessToken: string;
clientToken: string;
selectedProfile: {
id: string;
name: string;
};
}
import {
authenticate,
validateToken,
refreshToken,
type AuthSession,
} from '../api';
export default function useAuth() {
const [status, setStatus] = useState('idle');
const [status, setStatus] = useState<
'idle' | 'validating' | 'refreshing' | 'authenticating' | 'error'
>('idle');
// Проверка валидности токена
// Аутентификация (HTTP напрямую, без IPC!)
const authenticateUser = async (
username: string,
password: string,
saveConfigFunc: (config: any) => void,
): Promise<AuthSession | null> => {
try {
setStatus('authenticating');
// Прямой HTTP-запрос к вашему серверу
const session = await authenticate(username, password);
await applySession(session, saveConfigFunc);
return session;
} catch (error) {
console.error('Ошибка при аутентификации:', error);
setStatus('error');
throw error;
}
};
const applySession = async (
session: AuthSession,
saveConfigFunc: (config: any) => void,
) => {
saveConfigFunc({
username: session.selectedProfile.name,
uuid: session.selectedProfile.id,
accessToken: session.accessToken,
clientToken: session.clientToken,
memory: 4096,
});
await window.electron.ipcRenderer.invoke('auth-changed', {
isAuthed: true,
minecraftSession: session,
});
};
// Валидация токена (HTTP напрямую)
const validateSession = async (accessToken: string): Promise<boolean> => {
try {
setStatus('validating');
const response = await window.electron.ipcRenderer.invoke(
'validate-token',
accessToken,
);
// Получаем clientToken из localStorage
const savedConfig = localStorage.getItem('launcher_config');
if (!savedConfig) return false;
const config = JSON.parse(savedConfig);
// Прямой HTTP-запрос на валидацию
const isValid = await validateToken(accessToken, config.clientToken);
setStatus('idle');
return response.valid;
return isValid;
} catch (error) {
console.error('Ошибка при валидации токена:', error);
setStatus('error');
@ -29,66 +72,31 @@ export default function useAuth() {
}
};
// Обновление токена
// Обновление токена (HTTP напрямую)
const refreshSession = async (
accessToken: string,
clientToken: string,
): Promise<AuthSession | null> => {
try {
setStatus('refreshing');
const response = await window.electron.ipcRenderer.invoke(
'refresh-token',
{ accessToken, clientToken },
);
// Прямой HTTP-запрос на обновление
const session = await refreshToken(accessToken, clientToken);
setStatus('idle');
return response;
return session;
} catch (error) {
console.error('Ошибка при обновлении токена:', error);
setStatus('error');
return null;
}
};
// Аутентификация в Ely.by
const authenticateWithElyBy = async (
username: string,
password: string,
saveConfigFunc: Function,
): Promise<AuthSession | null> => {
try {
setStatus('authenticating');
const response = await window.electron.ipcRenderer.invoke(
'authenticate',
{ username, password },
);
if (response && response.accessToken) {
// Правильно сохраняем данные в конфигурации
saveConfigFunc({
username: response.selectedProfile.name, // Имя игрока как строка
uuid: response.selectedProfile.id,
accessToken: response.accessToken,
clientToken: response.clientToken,
memory: 4096, // Сохраняем значение по умолчанию или из предыдущей конфигурации
});
setStatus('authenticated');
return response;
}
setStatus('error');
return null;
} catch (error) {
console.error('Ошибка при аутентификации:', error);
setStatus('error');
return null;
throw error;
}
};
return {
status,
authenticateUser,
validateSession,
refreshSession,
authenticateWithElyBy,
applySession,
};
}

View File

@ -0,0 +1,11 @@
import type { ApiRoom } from '../api/voiceRooms';
import type { RoomInfo } from '../types/rooms';
export function mapApiRoomToUI(room: ApiRoom): RoomInfo {
return {
id: room.id,
name: room.name,
public: room.public,
users: room.usernames ?? [], // ⬅️ ВАЖНО: список пользователей приходит ТОЛЬКО по WS
};
}

View File

@ -435,7 +435,7 @@ export default function DailyReward({ onClaimed }: Props) {
</Box>
<Stack direction="row" alignItems="center" spacing={1}>
<CustomTooltip title="К текущему месяцу">
<CustomTooltip essential title="К текущему месяцу">
<IconButton
onClick={goToday}
sx={{
@ -661,7 +661,7 @@ export default function DailyReward({ onClaimed }: Props) {
</Box>
<Box sx={{ display: 'flex', gap: '1.2vw', alignItems: 'center' }}>
<CustomTooltip title={subtitle} disableInteractive>
<CustomTooltip essential title={subtitle} disableInteractive>
<Box
sx={{
display: 'inline-block',
@ -701,7 +701,7 @@ export default function DailyReward({ onClaimed }: Props) {
</Box>
</CustomTooltip>
<CustomTooltip title="Сбросить выбор на сегодня">
<CustomTooltip essential title="Сбросить выбор на сегодня">
<IconButton
onClick={() => setSelected(today)}
sx={{

View File

@ -0,0 +1,519 @@
// pages/TopUpPage.tsx
import {
Box,
Button,
Paper,
Stack,
TextField,
Typography,
ToggleButton,
ToggleButtonGroup,
CircularProgress,
LinearProgress,
} from '@mui/material';
import { styled } from '@mui/material/styles';
import { useEffect, useMemo, useRef, useState } from 'react';
import fakePaymentImg from '../../../assets/images/fake-payment.png';
import { useNavigate } from 'react-router-dom';
type PayMethod = 'sbp' | 'card' | 'crypto' | 'other';
type Stage = 'form' | 'processing' | 'done';
const STEPS: string[] = [
'Создаём счёт…',
'Проверяем данные…',
'Подключаем платёжный шлюз…',
'Ожидаем подтверждение…',
'Подписываем запрос…',
'Проверяем лимиты…',
'Синхронизируем баланс…',
'Завершаем операцию…',
'Почти готово…',
];
// ===== Styles “как Registration” =====
const GRADIENT =
'linear-gradient(71deg, #F27121 0%, #E940CD 70%, #8A2387 100%)';
const GlassPaper = styled(Paper)(() => ({
position: 'relative',
overflow: 'hidden',
borderRadius: 28,
background: 'rgba(0,0,0,0.35)',
border: '1px solid rgba(255,255,255,0.10)',
backdropFilter: 'blur(14px)',
boxShadow: '0 20px 60px rgba(0,0,0,0.45)',
}));
const Glow = styled('div')(() => ({
position: 'absolute',
inset: -2,
background:
'radial-gradient(800px 300px at 20% 10%, rgba(242,113,33,0.22), transparent 60%),' +
'radial-gradient(800px 300px at 80% 0%, rgba(233,64,205,0.18), transparent 55%),' +
'radial-gradient(900px 420px at 50% 110%, rgba(138,35,135,0.20), transparent 60%)',
pointerEvents: 'none',
}));
const GradientTitle = styled(Typography)(() => ({
fontWeight: 900,
backgroundImage:
'linear-gradient(136deg, rgb(242,113,33) 0%, rgb(233,64,87) 50%, rgb(138,35,135) 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
fontFamily: 'Benzin-Bold, sans-serif',
}));
const GradientButton = styled(Button)(() => ({
background: GRADIENT,
fontFamily: 'Benzin-Bold, sans-serif',
borderRadius: 999,
textTransform: 'none',
transition: 'transform 0.25s ease, filter 0.25s ease, box-shadow 0.25s ease',
boxShadow: '0 12px 30px rgba(0,0,0,0.35)',
'&:hover': {
transform: 'scale(1.04)',
filter: 'brightness(1.06)',
boxShadow: '0 16px 42px rgba(0,0,0,0.48)',
background: GRADIENT,
},
'&:disabled': {
background: 'rgba(255,255,255,0.08)',
color: 'rgba(255,255,255,0.35)',
boxShadow: 'none',
},
}));
const StyledToggleButtonGroup = styled(ToggleButtonGroup)(() => ({
borderRadius: 999,
overflow: 'hidden',
border: '1px solid rgba(255,255,255,0.10)',
background: 'rgba(255,255,255,0.06)',
'& .MuiToggleButton-root': {
border: 'none',
color: 'rgba(255,255,255,0.75)',
fontFamily: 'Benzin-Bold, sans-serif',
letterSpacing: '0.02em',
paddingTop: 10,
paddingBottom: 10,
transition: 'transform 0.2s ease, background 0.2s ease, color 0.2s ease',
},
'& .MuiToggleButton-root:hover': {
background: 'rgba(255,255,255,0.08)',
transform: 'scale(1.02)',
},
'& .MuiToggleButton-root.Mui-selected': {
color: '#fff',
background: GRADIENT,
},
'& .MuiToggleButton-root.Mui-selected:hover': {
background: GRADIENT,
},
}));
const StyledTextField = styled(TextField)(() => ({
'& .MuiInputLabel-root': {
color: 'rgba(255,255,255,0.65)',
},
'& .MuiInputLabel-root.Mui-focused': {
color: 'rgba(255,255,255,0.9)',
},
'& .MuiOutlinedInput-root': {
borderRadius: 20,
background: 'rgba(255,255,255,0.06)',
color: '#fff',
fontFamily: 'Benzin-Bold, sans-serif',
},
'& .MuiOutlinedInput-notchedOutline': {
borderColor: 'rgba(255,255,255,0.10)',
},
'& .MuiOutlinedInput-root:hover .MuiOutlinedInput-notchedOutline': {
borderColor: 'rgba(255,255,255,0.18)',
},
'& .MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline': {
borderColor: 'rgba(233,64,205,0.55)',
boxShadow: '0 0 0 6px rgba(233,64,205,0.12)',
},
'& input': {
color: '#fff',
},
}));
export default function TopUpPage() {
const [coins, setCoins] = useState<number>(100);
const [method, setMethod] = useState<PayMethod>('sbp');
const [stage, setStage] = useState<Stage>('form');
const [stepText, setStepText] = useState<string>('Обработка платежа…');
const [progress, setProgress] = useState<number>(0);
const doneTimerRef = useRef<number | null>(null);
const stepIntervalRef = useRef<number | null>(null);
const navigate = useNavigate();
const rubles = useMemo(() => {
const safe = Number.isFinite(coins) ? coins : 0;
return Math.max(0, Math.floor(safe));
}, [coins]);
const methodLabel = useMemo(() => {
switch (method) {
case 'sbp':
return 'СБП';
case 'card':
return 'Карта';
case 'crypto':
return 'Crypto';
default:
return 'Другое';
}
}, [method]);
const clearTimers = () => {
if (doneTimerRef.current !== null) {
window.clearTimeout(doneTimerRef.current);
doneTimerRef.current = null;
}
if (stepIntervalRef.current !== null) {
window.clearInterval(stepIntervalRef.current);
stepIntervalRef.current = null;
}
};
const startProcessing = () => {
clearTimers();
setStage('processing');
setProgress(0);
const used = new Set<number>();
const pickStep = () => {
if (used.size >= STEPS.length) used.clear();
let idx = Math.floor(Math.random() * STEPS.length);
while (used.has(idx)) idx = Math.floor(Math.random() * STEPS.length);
used.add(idx);
return STEPS[idx];
};
setStepText(pickStep());
const totalMs = 1600 + Math.floor(Math.random() * 1600); // 1.63.2
const stepsCount = 3 + Math.floor(Math.random() * 4); // 36
let ticks = 0;
stepIntervalRef.current = window.setInterval(
() => {
ticks += 1;
setStepText(pickStep());
setProgress((p) => {
const bump = 8 + Math.floor(Math.random() * 18); // 8..25
return Math.min(95, p + bump);
});
if (ticks >= stepsCount && stepIntervalRef.current !== null) {
window.clearInterval(stepIntervalRef.current);
stepIntervalRef.current = null;
}
},
400 + Math.floor(Math.random() * 500),
); // 400..900
doneTimerRef.current = window.setTimeout(() => {
setProgress(100);
setStepText('Готово!');
window.setTimeout(() => setStage('done'), 250);
doneTimerRef.current = null;
}, totalMs);
};
const handlePay = () => {
if (rubles <= 0) return;
startProcessing();
};
useEffect(() => {
return () => clearTimers();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// ===== Layout wrapper =====
const PageCenter = ({ children }: { children: React.ReactNode }) => (
<Box
sx={{
height: 'calc(100vh - 8vh)',
pt: '8vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
px: 2,
}}
>
{children}
</Box>
);
// ===== DONE =====
if (stage === 'done') {
return (
<PageCenter>
<GlassPaper sx={{ width: 'min(680px, 92vw)', p: 3 }}>
<Glow />
<Stack
spacing={2.2}
alignItems="center"
sx={{ position: 'relative' }}
>
<Box
component="img"
src={fakePaymentImg}
alt="payment"
sx={{
width: 'min(440px, 82vw)',
height: 'auto',
borderRadius: '24px',
boxShadow: '0 20px 60px rgba(0,0,0,0.55)',
}}
/>
<GradientTitle variant="h5" sx={{ textAlign: 'center' }}>
Че реально думал донат добавили?
</GradientTitle>
<Typography sx={{ opacity: 0.8, textAlign: 'center' }}>
Хуй тебе а не донат
</Typography>
<Button
variant="outlined"
onClick={() => {
navigate('/');
}}
sx={{
fontFamily: 'Benzin-Bold',
borderRadius: 999,
px: 3,
borderColor: 'rgba(255,255,255,0.18)',
color: 'rgba(255,255,255,0.85)',
textTransform: 'none',
'&:hover': {
borderColor: 'rgba(255,255,255,0.30)',
background: 'rgba(255,255,255,0.06)',
},
}}
>
Вернуться назад
</Button>
</Stack>
</GlassPaper>
</PageCenter>
);
}
// ===== PROCESSING =====
if (stage === 'processing') {
return (
<PageCenter>
<GlassPaper sx={{ width: 'min(680px, 92vw)', p: 3 }}>
<Glow />
<Stack
spacing={2.2}
alignItems="center"
sx={{ position: 'relative' }}
>
<Box
sx={{
width: 72,
height: 72,
borderRadius: '50%',
display: 'grid',
placeItems: 'center',
background: 'rgba(255,255,255,0.06)',
border: '1px solid rgba(255,255,255,0.10)',
}}
>
<CircularProgress />
</Box>
<GradientTitle variant="h6" sx={{ textAlign: 'center' }}>
{stepText}
</GradientTitle>
<Box sx={{ width: '100%' }}>
<LinearProgress
variant="determinate"
value={progress}
sx={{
height: 10,
borderRadius: 999,
backgroundColor: 'rgba(255,255,255,0.08)',
'& .MuiLinearProgress-bar': {
borderRadius: 999,
backgroundImage: GRADIENT,
},
}}
/>
<Typography sx={{ fontSize: 12, opacity: 0.75, mt: 1 }}>
{Math.round(progress)}%
</Typography>
</Box>
<Box
sx={{
width: '100%',
display: 'flex',
gap: 1,
flexWrap: 'wrap',
justifyContent: 'center',
}}
>
<Box
sx={{
px: 1.5,
py: 0.8,
borderRadius: 999,
background: 'rgba(255,255,255,0.06)',
border: '1px solid rgba(255,255,255,0.10)',
}}
>
<Typography sx={{ opacity: 0.85, fontSize: 13 }}>
{rubles.toLocaleString('ru-RU')}
</Typography>
</Box>
<Box
sx={{
px: 1.5,
py: 0.8,
borderRadius: 999,
background: 'rgba(255,255,255,0.06)',
border: '1px solid rgba(255,255,255,0.10)',
}}
>
<Typography sx={{ opacity: 0.85, fontSize: 13 }}>
{rubles.toLocaleString('ru-RU')} монет
</Typography>
</Box>
<Box
sx={{
px: 1.5,
py: 0.8,
borderRadius: 999,
background: 'rgba(255,255,255,0.06)',
border: '1px solid rgba(255,255,255,0.10)',
}}
>
<Typography sx={{ opacity: 0.85, fontSize: 13 }}>
{methodLabel}
</Typography>
</Box>
</Box>
<Typography
sx={{ fontSize: 12, opacity: 0.55, textAlign: 'center' }}
>
Пожалуйста, не закрывайте окно
</Typography>
</Stack>
</GlassPaper>
</PageCenter>
);
}
// ===== FORM =====
return (
<PageCenter>
<GlassPaper sx={{ width: 'min(680px, 92vw)', p: 3 }}>
<Glow />
<Stack spacing={2.2} sx={{ position: 'relative' }}>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
<GradientTitle variant="h5">Пополнение баланса</GradientTitle>
<Typography sx={{ opacity: 0.75 }}>1 = 1 монета</Typography>
</Box>
<Box
sx={{
display: 'grid',
gridTemplateColumns: { xs: '1fr', md: '1.3fr 1fr' },
gap: 2,
alignItems: 'start',
}}
>
<StyledTextField
label="Сколько монет нужно?"
value={coins}
onChange={(e) => setCoins(Number(e.target.value))}
inputProps={{ min: 0, step: 1 }}
fullWidth
sx={{'& .MuiFormLabel-root': {fontFamily: 'Benzin-Bold'}}}
/>
<Box
sx={{
borderRadius: 20,
background: 'rgba(255,255,255,0.06)',
border: '1px solid rgba(255,255,255,0.10)',
p: 2,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}
>
<Typography sx={{ opacity: 0.75, fontSize: 12 }}>
Итого к оплате
</Typography>
<Typography
sx={{
mt: 0.5,
fontSize: 26,
fontWeight: 900,
fontFamily: 'Benzin-Bold, sans-serif',
}}
>
{rubles.toLocaleString('ru-RU')}
</Typography>
<Typography sx={{ opacity: 0.65, fontSize: 12, mt: 0.5 }}>
Начислим: {rubles.toLocaleString('ru-RU')} монет
</Typography>
</Box>
</Box>
<Box>
<Typography sx={{ mb: 1, fontWeight: 700, opacity: 0.9 }}>
Способ оплаты
</Typography>
<StyledToggleButtonGroup
value={method}
exclusive
onChange={(_, v) => v && setMethod(v)}
fullWidth
>
<ToggleButton value="sbp">СБП</ToggleButton>
<ToggleButton value="card">Карта</ToggleButton>
<ToggleButton value="crypto">Crypto</ToggleButton>
<ToggleButton value="other">Другое</ToggleButton>
</StyledToggleButtonGroup>
<Typography sx={{ mt: 1, fontSize: 12, opacity: 0.55 }}>
Выбрано: {methodLabel}
</Typography>
</Box>
<GradientButton
variant="contained"
size="large"
onClick={handlePay}
disabled={rubles <= 0}
sx={{
height: 52,
fontSize: 16,
}}
>
Оплатить
</GradientButton>
</Stack>
</GlassPaper>
</PageCenter>
);
}

View File

@ -0,0 +1,813 @@
import { useEffect, useState } from 'react';
import { Box, Typography, Grid, Button, Paper, FormControl, Select, MenuItem, InputLabel } from '@mui/material';
import { FullScreenLoader } from '../components/FullScreenLoader';
import { translateServer } from '../utils/serverTranslator';
import {
fetchInventoryItems,
withdrawInventoryItem,
type InventoryRawItem,
type InventoryItemsResponse,
} from '../api';
import CustomTooltip from '../components/Notifications/CustomTooltip';
import { getPlayerServer } from '../utils/playerOnlineCheck';
const KNOWN_SERVER_IPS = [
'minecraft.hub.popa-popa.ru',
'minecraft.survival.popa-popa.ru',
'minecraft.minigames.popa-popa.ru',
];
const STORAGE_KEY = 'inventory_layout';
function stripMinecraftColors(text?: string | null): string {
if (!text) return '';
return text.replace(/§[0-9A-FK-ORa-fk-or]/g, '');
}
const CARD_BG =
'radial-gradient(circle at 10% 10%, rgba(242,113,33,0.14), transparent 55%), radial-gradient(circle at 90% 20%, rgba(233,64,205,0.12), transparent 55%), rgba(10,10,20,0.86)';
const CardFacePaperSx = {
borderRadius: '1.2vw',
background: CARD_BG,
border: '1px solid rgba(255,255,255,0.08)',
boxShadow: '0 1.2vw 3.2vw rgba(0,0,0,0.55)',
color: 'white',
} as const;
function readInventoryLayout(): any {
try {
const raw = localStorage.getItem(STORAGE_KEY);
return raw ? JSON.parse(raw) : {};
} catch {
return {};
}
}
function writeInventoryLayout(next: any) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
}
function getLayout(username: string, serverIp: string): Record<string, number> {
const inv = readInventoryLayout();
return inv?.[username]?.[serverIp] ?? {};
}
function setLayout(username: string, serverIp: string, layout: Record<string, number>) {
const inv = readInventoryLayout();
inv[username] ??= {};
inv[username][serverIp] = layout;
writeInventoryLayout(inv);
}
function buildSlots(
items: InventoryRawItem[],
layout: Record<string, number>,
size = 28,
): (InventoryRawItem | null)[] {
const slots: (InventoryRawItem | null)[] = Array.from({ length: size }, () => null);
const byId = new Map(items.map((it) => [it.id, it]));
const used = new Set<string>();
// 1) ставим туда, куда сохранено
for (const [id, idx] of Object.entries(layout)) {
const i = Number(idx);
const it = byId.get(id);
if (!it) continue;
if (Number.isFinite(i) && i >= 0 && i < size && !slots[i]) {
slots[i] = it;
used.add(id);
}
}
// 2) остальные — в первые пустые
for (const it of items) {
if (used.has(it.id)) continue;
const empty = slots.findIndex((x) => x === null);
if (empty === -1) break;
slots[empty] = it;
used.add(it.id);
}
return slots;
}
export default function Inventory() {
const [username, setUsername] = useState('');
const [loading, setLoading] = useState(true);
const [availableServers, setAvailableServers] = useState<string[]>([]);
const [selectedServerIp, setSelectedServerIp] = useState<string>('');
const [items, setItems] = useState<InventoryRawItem[]>([]);
const [page, setPage] = useState(1);
const limit = 28;
const [total, setTotal] = useState(0);
const [pages, setPages] = useState(1);
const [withdrawingIds, setWithdrawingIds] = useState<string[]>([]);
const [hoveredId, setHoveredId] = useState<string | null>(null);
const [isOnline, setIsOnline] = useState(false);
const [playerServer, setPlayerServer] = useState<string | null>(null);
const [checkingOnline, setCheckingOnline] = useState(false);
const [draggedItemId, setDraggedItemId] = useState<string | null>(null);
const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);
const [dragPos, setDragPos] = useState<{ x: number; y: number } | null>(null);
type SlotItem = InventoryRawItem | null;
const [slots, setSlots] = useState<SlotItem[]>(() => Array.from({ length: 28 }, () => null));
const [draggedFromIndex, setDraggedFromIndex] = useState<number | null>(null);
useEffect(() => {
const handleMove = (e: MouseEvent) => {
if (!draggedItemId) return;
setDragPos({ x: e.clientX, y: e.clientY });
};
const handleUp = () => {
if (
draggedItemId &&
draggedFromIndex !== null &&
dragOverIndex !== null &&
draggedFromIndex !== dragOverIndex
) {
setSlots((prev) => {
const next = [...prev];
const moving = next[draggedFromIndex];
if (!moving) return prev;
// ✅ swap или move в пустоту
const target = next[dragOverIndex];
next[dragOverIndex] = moving;
next[draggedFromIndex] = target ?? null;
// ✅ сохраняем layout (позиции предметов)
const layout: Record<string, number> = {};
next.forEach((it, idx) => {
if (it) layout[it.id] = idx;
});
if (username && selectedServerIp) {
setLayout(username, selectedServerIp, layout);
}
return next;
});
}
setDraggedItemId(null);
setDraggedFromIndex(null);
setDragOverIndex(null);
setDragPos(null);
};
window.addEventListener('mousemove', handleMove);
window.addEventListener('mouseup', handleUp);
return () => {
window.removeEventListener('mousemove', handleMove);
window.removeEventListener('mouseup', handleUp);
};
}, [draggedItemId, dragOverIndex]);
useEffect(() => {
const savedConfig = localStorage.getItem('launcher_config');
if (!savedConfig) {
setLoading(false);
return;
}
const config = JSON.parse(savedConfig);
if (config?.username) setUsername(config.username);
setLoading(false);
}, []);
const detectServersWithItems = async (u: string) => {
const checks = await Promise.allSettled(
KNOWN_SERVER_IPS.map(async (ip) => {
const res = await fetchInventoryItems(u, ip, 1, 1);
return { ip, has: (res.items || []).length > 0 || (res.total ?? 0) > 0 };
}),
);
return checks
.filter(
(r): r is PromiseFulfilledResult<{ ip: string; has: boolean }> => r.status === 'fulfilled',
)
.filter((r) => r.value.has)
.map((r) => r.value.ip);
};
const loadInventory = async (u: string, ip: string, p: number) => {
const res: InventoryItemsResponse = await fetchInventoryItems(u, ip, p, limit);
const list = res.items || [];
setItems(res.items || []);
setTotal(res.total ?? 0);
setPages(Math.max(1, Math.ceil((res.total ?? 0) / (res.limit ?? limit))));
const layout = getLayout(u, ip);
setSlots(buildSlots(list, layout, 28));
};
useEffect(() => {
if (!username) return;
let cancelled = false;
(async () => {
try {
setLoading(true);
const servers = await detectServersWithItems(username);
if (cancelled) return;
setAvailableServers(servers);
const defaultIp = servers[0] || '';
setSelectedServerIp(defaultIp);
setPage(1);
if (defaultIp) {
await loadInventory(username, defaultIp, 1);
} else {
setItems([]);
setTotal(0);
setPages(1);
}
} catch (e) {
console.error(e);
setAvailableServers([]);
setSelectedServerIp('');
setItems([]);
setTotal(0);
setPages(1);
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => {
cancelled = true;
};
}, [username]);
useEffect(() => {
if (!username || !selectedServerIp) return;
let cancelled = false;
(async () => {
try {
setLoading(true);
setPage(1);
await loadInventory(username, selectedServerIp, 1);
} catch (e) {
console.error(e);
setItems([]);
setTotal(0);
setPages(1);
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => {
cancelled = true;
};
}, [selectedServerIp]);
const withWithdrawing = async (id: string, fn: () => Promise<void>) => {
setWithdrawingIds((prev) => [...prev, id]);
try {
await fn();
} finally {
setWithdrawingIds((prev) => prev.filter((x) => x !== id));
}
};
const handleWithdraw = async (item: InventoryRawItem) => {
if (!username || !selectedServerIp) return;
// сервер в UI может не совпадать — оставим защиту
if (selectedServerIp !== item.server_ip) {
alert('Ошибка! Вы не на том сервере для выдачи этого предмета.');
return;
}
await withWithdrawing(item.id, async () => {
try {
await withdrawInventoryItem({
username,
item_id: item.id,
server_ip: selectedServerIp,
});
setItems((prevItems) => prevItems.filter((prevItem) => prevItem.id !== item.id));
setSlots((prev) => {
const next = prev.map((x) => (x?.id === item.id ? null : x));
const layout: Record<string, number> = {};
next.forEach((it, idx) => {
if (it) layout[it.id] = idx;
});
setLayout(username, selectedServerIp, layout);
return next;
});
} catch (e) {
console.error('Ошибка при выводе предмета:', e);
}
});
};
const checkPlayerStatus = async () => {
if (!username) return;
setCheckingOnline(true);
try {
const res = await getPlayerServer(username);
setIsOnline(!!res?.online);
setPlayerServer(res?.server?.ip ?? null);
} catch (e) {
console.error('Ошибка проверки онлайна:', e);
setIsOnline(false);
setPlayerServer(null);
} finally {
setCheckingOnline(false);
}
};
useEffect(() => {
if (!username) return;
checkPlayerStatus();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [username]);
const headerServerName = selectedServerIp ? translateServer(`Server ${selectedServerIp}`) : '';
if (!username) {
return (
<Box sx={{ p: '2vw' }}>
<Typography sx={{ color: 'rgba(255,255,255,0.75)' }}>
Не найдено имя игрока. Авторизуйтесь в лаунчере.
</Typography>
</Box>
);
}
const canPrev = page > 1;
const canNext = page < pages;
const handlePrev = async () => {
if (!canPrev || !username || !selectedServerIp) return;
const nextPage = page - 1;
setPage(nextPage);
setLoading(true);
try {
await loadInventory(username, selectedServerIp, nextPage);
} finally {
setLoading(false);
}
};
const handleNext = async () => {
if (!canNext || !username || !selectedServerIp) return;
const nextPage = page + 1;
setPage(nextPage);
setLoading(true);
try {
await loadInventory(username, selectedServerIp, nextPage);
} finally {
setLoading(false);
}
};
return (
<Box
sx={{
display: 'flex',
flexDirection: 'column',
width: '100%',
height: '100%',
overflow: 'auto',
px: '2.5vw',
py: '2vw',
gap: 2,
mt: '12vh',
}}
>
{/* ШАПКА + ПАГИНАЦИЯ */}
<Box
sx={{
display: 'flex',
alignItems: 'center',
gap: 2,
flexWrap: 'wrap',
justifyContent: 'space-evenly',
flexDirection: 'row-reverse',
}}
>
{!!selectedServerIp && (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Button
variant="outlined"
disabled={!canPrev || loading}
onClick={handlePrev}
sx={{
borderRadius: '2.5vw',
fontFamily: 'Benzin-Bold',
color: 'white',
border: '1px solid rgba(255,255,255,0.15)',
}}
>
Назад
</Button>
<Typography sx={{ color: 'rgba(255,255,255,0.7)' }}>
Страница {page} / {pages} Всего: {total}
</Typography>
<Button
variant="outlined"
disabled={!canNext || loading}
onClick={handleNext}
sx={{
borderRadius: '2.5vw',
fontFamily: 'Benzin-Bold',
color: 'white',
border: '1px solid rgba(255,255,255,0.15)',
}}
>
Вперёд
</Button>
</Box>
)}
{availableServers.length > 0 && (
<FormControl size="small" sx={{ minWidth: 260 }}>
<InputLabel
id="inventory-server-label"
sx={{ fontFamily: 'Benzin-Bold', color: 'rgba(255,255,255,0.75)' }}
>
Сервер
</InputLabel>
<Select
labelId="inventory-server-label"
label="Сервер"
value={selectedServerIp}
onChange={(e) => setSelectedServerIp(String(e.target.value))}
MenuProps={{
PaperProps: {
sx: {
bgcolor: 'rgba(10,10,20,0.96)',
border: '1px solid rgba(255,255,255,0.10)',
borderRadius: '1vw',
backdropFilter: 'blur(14px)',
'& .MuiMenuItem-root': {
color: 'rgba(255,255,255,0.9)',
fontFamily: 'Benzin-Bold',
},
'& .MuiMenuItem-root.Mui-selected': {
backgroundColor: 'rgba(242,113,33,0.16)',
},
'& .MuiMenuItem-root:hover': {
backgroundColor: 'rgba(233,64,205,0.14)',
},
},
},
}}
sx={{
borderRadius: '999px',
bgcolor: 'rgba(255,255,255,0.04)',
color: 'rgba(255,255,255,0.92)',
fontFamily: 'Benzin-Bold',
'& .MuiSelect-select': {
py: '0.9vw',
px: '1.2vw',
},
'& .MuiOutlinedInput-notchedOutline': {
borderColor: 'rgba(255,255,255,0.14)',
},
'&:hover .MuiOutlinedInput-notchedOutline': {
borderColor: 'rgba(242,113,33,0.55)',
},
'&.Mui-focused .MuiOutlinedInput-notchedOutline': {
borderColor: 'rgba(233,64,205,0.65)',
borderWidth: '2px',
},
'& .MuiSelect-icon': {
color: 'rgba(255,255,255,0.75)',
},
}}
>
{availableServers.map((ip) => (
<MenuItem key={ip} value={ip}>
{translateServer(`Server ${ip}`)}
</MenuItem>
))}
</Select>
</FormControl>
)}
<Typography
variant="h6"
sx={{
fontFamily: 'Benzin-Bold',
backgroundImage:
'linear-gradient(136deg, rgb(242,113,33), rgb(233,64,87), rgb(138,35,135))',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
}}
>
Инвентарь {headerServerName ? `${headerServerName}` : ''}
</Typography>
</Box>
{/* GRID */}
{loading ? (
<FullScreenLoader fullScreen={false} message="Загрузка инвентаря..." />
) : (
<Grid container spacing={2}>
{Array.from({ length: 28 }).map((_, index) => {
const item = slots[index];
// ПУСТАЯ ЯЧЕЙКА
if (!item) {
return (
<Grid
item
xs={3}
key={index}
onMouseEnter={() => {
if (draggedItemId) setDragOverIndex(index);
}}
sx={{
outline:
draggedItemId && dragOverIndex === index
? '2px dashed rgba(255,255,255,0.4)'
: 'none',
}}
>
<Paper
elevation={0}
sx={{
...CardFacePaperSx,
overflow: 'hidden',
width: '12vw',
height: '12vw',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: 'rgba(255,255,255,0.5)',
}}
>
<Typography>Пусто</Typography>
</Paper>
</Grid>
);
}
const displayNameRaw =
item.item_data?.meta?.display_name ?? item.item_data?.material ?? 'Предмет';
const displayName = stripMinecraftColors(displayNameRaw);
const amount =
(item as any)?.amount ??
(item as any)?.item_data?.amount ??
(item as any)?.item_data?.meta?.amount ??
1;
const isHovered = hoveredId === item.id;
const isWithdrawing = withdrawingIds.includes(item.id);
// ✅ проверка: игрок реально онлайн на нужном сервере
const isOnRightServer = isOnline && playerServer === item.server_ip;
const canWithdraw = isOnRightServer && !loading && !checkingOnline && !isWithdrawing;
const texture = item.item_data?.material
? `https://cdn.minecraft.popa-popa.ru/textures/${item.item_data.material.toLowerCase()}.png`
: '';
return (
<Grid
item
xs={3}
key={item.id}
onMouseEnter={() => {
if (draggedItemId) setDragOverIndex(index);
}}
sx={{
outline:
draggedItemId && dragOverIndex === index
? '2px dashed rgba(255,255,255,0.4)'
: 'none',
}}
>
<Box
sx={{
width: '100%',
perspective: '1200px',
cursor: draggedItemId === item.id ? 'grabbing' : 'grab',
opacity: draggedItemId === item.id ? 0.4 : 1,
}}
onMouseEnter={() => setHoveredId(item.id)}
onMouseLeave={() => setHoveredId(null)}
onMouseDown={(e) => {
const target = e.target as HTMLElement;
if (target.closest('button')) return;
e.preventDefault();
setDraggedItemId(item.id);
setDraggedFromIndex(index);
setDragPos({ x: e.clientX, y: e.clientY });
}}
>
<Box
sx={{
position: 'relative',
width: '12vw',
height: '12vw', // фиксированная высота = Grid не дергается
transformStyle: 'preserve-3d',
transition: 'transform 0.5s cubic-bezier(0.4, 0.2, 0.2, 1)',
transform: isHovered ? 'rotateY(180deg)' : 'rotateY(0deg)',
}}
>
{/* FRONT */}
<Paper
elevation={0}
sx={{
...CardFacePaperSx,
position: 'absolute',
inset: 0,
backfaceVisibility: 'hidden',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
overflow: 'hidden',
}}
>
<Box
component="img"
src={texture}
sx={{
width: '5vw',
height: '5vw',
objectFit: 'contain',
imageRendering: 'pixelated',
userSelect: 'none',
transition: 'transform 0.25s ease',
transform: isHovered ? 'scale(1.05)' : 'scale(1)',
}}
draggable={false}
alt={displayName}
/>
</Paper>
{/* BACK */}
<Paper
elevation={0}
sx={{
...CardFacePaperSx,
position: 'absolute',
inset: 0,
backfaceVisibility: 'hidden',
transform: 'rotateY(180deg)',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
gap: '0.8vw',
px: '1.1vw',
overflow: 'hidden',
}}
>
<Typography
sx={{
fontFamily: 'Benzin-Bold',
fontSize: '0.8vw',
lineHeight: 1.2,
textAlign: 'center',
wordBreak: 'break-word',
}}
>
{displayName}
</Typography>
<Typography
sx={{
fontSize: '0.7vw',
textAlign: 'center',
color: 'rgba(255,255,255,0.7)',
}}
>
Кол-во: {amount}
</Typography>
{!isOnRightServer ? (
<CustomTooltip
essential
title={
!isOnline
? 'Вы должны быть онлайн на сервере'
: `Перейдите на сервер ${item.server_ip}`
}
placement="top"
arrow
>
<span>
<Button
disabled
fullWidth
variant="outlined"
sx={{
fontSize: '0.8vw',
borderRadius: '2vw',
fontFamily: 'Benzin-Bold',
border: '1px solid rgba(255,255,255,0.15)',
color: 'rgba(255,255,255,0.5)',
}}
>
Выдать
</Button>
</span>
</CustomTooltip>
) : (
<Button
fullWidth
variant="outlined"
disabled={!canWithdraw}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
handleWithdraw(item);
}}
sx={{
fontSize: '0.8vw',
borderRadius: '2vw',
fontFamily: 'Benzin-Bold',
border: '1px solid rgba(255,255,255,0.15)',
color: 'white',
}}
>
{isWithdrawing ? 'Выдача...' : 'Выдать'}
</Button>
)}
</Paper>
</Box>
</Box>
</Grid>
);
})}
</Grid>
)}
{draggedItemId && dragPos && (() => {
const draggedItem = items.find(i => i.id === draggedItemId);
if (!draggedItem) return null;
const texture = `https://cdn.minecraft.popa-popa.ru/textures/${draggedItem.item_data.material.toLowerCase()}.png`;
return (
<Box
sx={{
position: 'fixed',
left: dragPos.x,
top: dragPos.y,
transform: 'translate(-50%, -50%)',
//width: '12vw',
//height: '12vw',
pointerEvents: 'none',
zIndex: 9999,
opacity: 0.9,
}}
>
<Paper
elevation={0}
sx={{
...CardFacePaperSx,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: '12vw',
height: '12vw',
}}
>
<Box
component="img"
src={texture}
sx={{
width: '5vw',
height: '5vw',
imageRendering: 'pixelated',
}}
/>
</Paper>
</Box>
);
})()}
</Box>
);
}

View File

@ -1,9 +1,4 @@
import {
Box,
Typography,
Button,
LinearProgress,
} from '@mui/material';
import { Box, Typography, Button, LinearProgress } from '@mui/material';
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import ServerStatus from '../components/ServerStatus/ServerStatus';
@ -13,7 +8,10 @@ import React from 'react';
import SettingsModal from '../components/Settings/SettingsModal';
import CustomNotification from '../components/Notifications/CustomNotification';
import type { NotificationPosition } from '../components/Notifications/CustomNotification';
import { isNotificationsEnabled, getNotifPositionFromSettings } from '../utils/notifications';
import {
isNotificationsEnabled,
getNotifPositionFromSettings,
} from '../utils/notifications';
declare global {
interface Window {
@ -31,7 +29,6 @@ declare global {
interface LaunchPageProps {
onLaunchPage?: () => void;
launchOptions?: {
// Делаем опциональным
downloadUrl: string;
apiReleaseUrl: string;
versionFileName: string;
@ -40,6 +37,8 @@ interface LaunchPageProps {
baseVersion: string;
serverIp: string;
fabricVersion: string;
neoForgeVersion?: string;
loaderType?: string;
};
}
@ -50,6 +49,7 @@ const LaunchPage = ({
const navigate = useNavigate();
const { versionId } = useParams();
const [versionConfig, setVersionConfig] = useState<any>(null);
const [fullVersionConfig, setFullVersionConfig] = useState<any>(null); // Полная конфигурация из Gist
// Начальное состояние должно быть пустым или с минимальными значениями
const [config, setConfig] = useState<{
@ -115,6 +115,21 @@ const LaunchPage = ({
const minecraftStartedListener = () => {
setIsGameRunning(true);
const raw = localStorage.getItem('pending_launch_context');
if (!raw) return;
const context = JSON.parse(raw);
localStorage.setItem(
'last_launched_version',
JSON.stringify({
...context,
launchedAt: Date.now(),
}),
);
localStorage.removeItem('pending_launch_context');
};
const minecraftStoppedListener = () => {
@ -146,6 +161,29 @@ const LaunchPage = ({
};
}, [navigate]);
// Функция для загрузки полной конфигурации версии из Gist
const fetchFullVersionConfig = async (): Promise<any> => {
if (!versionId) return null;
try {
// Загружаем весь список версий из Gist
const result = await window.electron.ipcRenderer.invoke(
'get-available-versions',
{},
);
if (result.success && result.versions) {
// Находим нужную версию по ID
const version = result.versions.find((v: any) => v.id === versionId);
return version || null;
}
} catch (error) {
console.error('Ошибка при загрузке полной конфигурации:', error);
}
return null;
};
useEffect(() => {
const fetchVersionConfig = async () => {
if (!versionId) return;
@ -159,6 +197,7 @@ const LaunchPage = ({
// Если конфиг пустой — считаем, что он невалидный и идём по IPC-ветке
if (Object.keys(parsedConfig).length > 0) {
setVersionConfig(parsedConfig);
setFullVersionConfig(parsedConfig);
setConfig({
memory: parsedConfig.memory || 4096,
@ -172,36 +211,50 @@ const LaunchPage = ({
}
}
// Если нет в localStorage, запрашиваем с сервера
const result = await window.electron.ipcRenderer.invoke(
'get-version-config',
{ versionId },
);
// Загружаем полную конфигурацию из Gist
const fullConfig = await fetchFullVersionConfig();
if (fullConfig) {
setFullVersionConfig(fullConfig);
// Сохраняем только config часть для совместимости
setVersionConfig(fullConfig.config || {});
if (result.success) {
setVersionConfig(result.config);
setConfig({
memory: result.config.memory || 4096,
preserveFiles: result.config.preserveFiles || [],
memory: fullConfig.config?.memory || 4096,
preserveFiles: fullConfig.config?.preserveFiles || [],
});
} else {
// Если не удалось получить конфигурацию, используем значения по умолчанию
const defaultConfig = {
downloadUrl: '',
apiReleaseUrl: '',
versionFileName: `${versionId}_version.txt`,
packName: versionId || 'Comfort',
memory: 4096,
baseVersion: '1.21.4',
serverIp: 'popa-popa.ru',
fabricVersion: '0.16.14',
preserveFiles: ['popa-launcher-config.json'],
};
setVersionConfig(defaultConfig);
setConfig({
memory: defaultConfig.memory,
preserveFiles: defaultConfig.preserveFiles || [],
});
// Если не удалось получить конфигурацию из Gist, используем IPC
const result = await window.electron.ipcRenderer.invoke(
'get-version-config',
{ versionId },
);
if (result.success) {
setVersionConfig(result.config);
setConfig({
memory: result.config.memory || 4096,
preserveFiles: result.config.preserveFiles || [],
});
} else {
// Если не удалось получить конфигурацию, используем значения по умолчанию
const defaultConfig = {
downloadUrl: '',
apiReleaseUrl: '',
versionFileName: `${versionId}_version.txt`,
packName: versionId || 'Comfort',
memory: 4096,
baseVersion: '1.21.4',
serverIp: 'popa-popa.ru',
fabricVersion: '0.16.14',
preserveFiles: ['popa-launcher-config.json'],
};
setVersionConfig(defaultConfig);
setConfig({
memory: defaultConfig.memory,
preserveFiles: defaultConfig.preserveFiles || [],
});
}
}
} catch (error) {
console.error('Ошибка при получении настроек версии:', error);
@ -246,15 +299,49 @@ const LaunchPage = ({
setIsDownloading(true);
setBuffer(10);
// Используем настройки выбранной версии или дефолтные
const currentConfig = versionConfig || {
packName: versionId || 'Comfort',
memory: 4096,
baseVersion: '1.21.4',
serverIp: 'popa-popa.ru',
fabricVersion: '0.16.14',
preserveFiles: [],
};
if (isGameRunning) {
showNotification('Minecraft уже запущен', 'info');
return;
}
// Загружаем полную конфигурацию, если еще не загружена
if (!fullVersionConfig) {
const loadedConfig = await fetchFullVersionConfig();
if (loadedConfig) {
setFullVersionConfig(loadedConfig);
setVersionConfig(loadedConfig.config || {});
}
}
console.log('fullVersionConfig:', fullVersionConfig);
console.log('versionFromGist:', fullVersionConfig?.version);
// Используем настройки из Gist или дефолтные
const currentConfig = fullVersionConfig?.config ||
versionConfig || {
packName: versionId || 'Comfort',
memory: 4096,
baseVersion: '1.21.4',
serverIp: 'popa-popa.ru',
fabricVersion: '0.16.14',
neoForgeVersion: null,
loaderType: 'fabric',
preserveFiles: [],
};
// Получаем версию для запуска из Gist
let versionFromGist = fullVersionConfig?.version || null;
console.log('versionFromGist before override:', versionFromGist);
// Если версия из Gist пустая, используем логику по умолчанию
if (
!versionFromGist &&
currentConfig.loaderType === 'neoforge' &&
currentConfig.neoForgeVersion
) {
versionFromGist = `neoforge-${currentConfig.neoForgeVersion}`;
console.log('Overriding versionFromGist to:', versionFromGist);
}
// Проверяем, является ли это ванильной версией
const isVanillaVersion =
@ -298,7 +385,8 @@ const LaunchPage = ({
localStorage.getItem('launcher_config') || '{}',
);
const options = {
// Формируем полные опции для запуска
const options: any = {
accessToken: savedConfig.accessToken,
uuid: savedConfig.uuid,
username: savedConfig.username,
@ -307,11 +395,35 @@ const LaunchPage = ({
packName: versionId || currentConfig.packName,
serverIp: currentConfig.serverIp,
fabricVersion: currentConfig.fabricVersion,
// Для ванильной версии устанавливаем флаг
neoForgeVersion: currentConfig.neoForgeVersion,
loaderType: currentConfig.loaderType || 'fabric',
isVanillaVersion: isVanillaVersion,
versionToLaunchOverride: isVanillaVersion ? versionId : undefined,
versionToLaunchOverride:
versionFromGist || (isVanillaVersion ? versionId : undefined),
// Передаем Gist URL для загрузки конфигурации в процессе запуска
gistUrl:
'https://gist.githubusercontent.com/DIKER0K/06cd12fb3a4d08b1f0f8c763a7d05e06/raw/versions.json',
};
const launchContext = {
versionId,
packName: versionId || currentConfig.packName,
baseVersion: currentConfig.baseVersion,
fabricVersion: currentConfig.fabricVersion,
neoForgeVersion: currentConfig.neoForgeVersion,
loaderType: currentConfig.loaderType,
serverIp: currentConfig.serverIp,
isVanillaVersion,
versionToLaunchOverride:
versionFromGist || (isVanillaVersion ? versionId : undefined),
memory: config.memory,
};
localStorage.setItem(
'pending_launch_context',
JSON.stringify(launchContext),
);
const launchResult = await window.electron.ipcRenderer.invoke(
'launch-minecraft',
options,
@ -319,8 +431,10 @@ const LaunchPage = ({
if (launchResult?.success) {
showNotification('Minecraft успешно запущен!', 'success');
} else if (launchResult?.error) {
showNotification(`Ошибка запуска: ${launchResult.error}`, 'error');
}
} catch (error) {
} catch (error: any) {
console.error('Error:', error);
showNotification(`Ошибка: ${error.message}`, 'error');
} finally {
@ -328,6 +442,12 @@ const LaunchPage = ({
}
};
useEffect(() => {
window.addEventListener('beforeunload', () => {
localStorage.removeItem('pending_launch_context');
});
}, []);
const handleStopMinecraft = async () => {
try {
const result = await window.electron.ipcRenderer.invoke('stop-minecraft');
@ -363,9 +483,6 @@ const LaunchPage = ({
config: configToSave,
});
// Обновляем launchOptions
launchOptions.memory = config.memory;
showNotification('Настройки сохранены', 'success');
} catch (error) {
console.error('Ошибка при сохранении настроек:', error);

View File

@ -1,105 +1,426 @@
import { Box, Typography } from '@mui/material';
import {
Box,
Button,
Typography,
Paper,
Stack,
Divider,
ToggleButton,
ToggleButtonGroup,
IconButton,
} from '@mui/material';
import useAuth from '../hooks/useAuth';
import AuthForm from '../components/Login/AuthForm';
import MemorySlider from '../components/Login/MemorySlider';
import { useNavigate } from 'react-router-dom';
import PopaPopa from '../components/popa-popa';
import useConfig from '../hooks/useConfig';
import { useState } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { FullScreenLoader } from '../components/FullScreenLoader';
import { styled, alpha, keyframes } from '@mui/material/styles';
import TelegramIcon from '@mui/icons-material/Telegram';
import KeyIcon from '@mui/icons-material/Key';
import RefreshRoundedIcon from '@mui/icons-material/RefreshRounded';
import PersonAddAlt1RoundedIcon from '@mui/icons-material/PersonAddAlt1Rounded';
import OpenInNewRoundedIcon from '@mui/icons-material/OpenInNewRounded';
import React from 'react';
import CustomNotification from '../components/Notifications/CustomNotification';
import type { NotificationPosition } from '../components/Notifications/CustomNotification';
import {
isNotificationsEnabled,
getNotifPositionFromSettings,
} from '../utils/notifications';
// как в registration
import QRCodeStyling from 'qr-code-styling';
import popalogo from '../../../assets/icons/popa-popa.svg';
import GradientTextField from '../components/GradientTextField';
// твои API методы
import { qrInit, qrStatus } from '../api';
import { loadPending } from '../utils/pendingVerification';
interface LoginProps {
onLoginSuccess?: (username: string) => void;
}
const glowPulse = keyframes`
0% { transform: translate3d(0,0,0) scale(1); opacity: .85; filter: saturate(1.0); }
50% { transform: translate3d(0,-6px,0) scale(1.02); opacity: 1; filter: saturate(1.15); }
100% { transform: translate3d(0,0,0) scale(1); opacity: .85; filter: saturate(1.0); }
`;
const borderShimmer = keyframes`
0% { background-position: 0% 50%; opacity: .35; }
50% { background-position: 100% 50%; opacity: .55; }
100% { background-position: 0% 50%; opacity: .35; }
`;
const GRADIENT =
'linear-gradient(71deg, #F27121 0%, #E940CD 70%, #8A2387 100%)';
const GlassPaper = styled(Paper)(() => ({
position: 'relative',
overflow: 'hidden',
borderRadius: 28,
background: 'rgba(0,0,0,0.35)',
border: '1px solid rgba(255,255,255,0.10)',
backdropFilter: 'blur(14px)',
boxShadow: '0 20px 60px rgba(0,0,0,0.45)',
}));
const Glow = styled('div')(() => ({
position: 'absolute',
inset: -2,
background:
'radial-gradient(800px 300px at 20% 10%, rgba(242,113,33,0.22), transparent 60%),' +
'radial-gradient(800px 300px at 80% 0%, rgba(233,64,205,0.18), transparent 55%),' +
'radial-gradient(900px 420px at 50% 110%, rgba(138,35,135,0.20), transparent 60%)',
pointerEvents: 'none',
animation: `${glowPulse} 6s ease-in-out infinite`,
}));
const GradientTitle = styled(Typography)(() => ({
fontWeight: 900,
backgroundImage:
'linear-gradient(136deg, rgb(242,113,33) 0%, rgb(233,64,87) 50%, rgb(138,35,135) 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
fontFamily: 'Benzin-Bold, sans-serif',
}));
const GradientButton = styled(Button)(() => ({
background: GRADIENT,
fontFamily: 'Benzin-Bold, sans-serif',
borderRadius: 999,
textTransform: 'none',
transition: 'transform 0.25s ease, filter 0.25s ease, box-shadow 0.25s ease',
boxShadow: '0 12px 30px rgba(0,0,0,0.35)',
'&:hover': {
transform: 'scale(1.04)',
filter: 'brightness(1.06)',
boxShadow: '0 16px 42px rgba(0,0,0,0.48)',
background: GRADIENT,
},
'&:disabled': {
background: 'rgba(255,255,255,0.08)',
color: 'rgba(255,255,255,0.35)',
boxShadow: 'none',
},
}));
const Segmented = styled(ToggleButtonGroup)(() => ({
borderRadius: 999,
overflow: 'hidden',
border: '1px solid rgba(255,255,255,0.10)',
background: 'rgba(255,255,255,0.06)',
'& .MuiToggleButton-root': {
border: 'none',
color: 'rgba(255,255,255,0.75)',
fontFamily: 'Benzin-Bold, sans-serif',
letterSpacing: '0.02em',
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 18,
paddingRight: 18,
transition: 'transform 0.2s ease, background 0.2s ease, color 0.2s ease',
},
'& .MuiToggleButton-root:hover': {
background: 'rgba(255,255,255,0.08)',
transform: 'scale(1.02)',
},
'& .MuiToggleButton-root.Mui-selected': {
color: '#fff',
background: GRADIENT,
},
'& .MuiToggleButton-root.Mui-selected:hover': {
background: GRADIENT,
},
}));
const Login = ({ onLoginSuccess }: LoginProps) => {
const navigate = useNavigate();
const { config, setConfig, saveConfig, handleInputChange } = useConfig();
const { status, validateSession, refreshSession, authenticateWithElyBy } =
useAuth();
const { config, saveConfig, handleInputChange } = useConfig();
const auth = useAuth();
const [loading, setLoading] = useState(false);
const authorization = async () => {
console.log('Начинаем процесс авторизации...');
// ===== UI mode: по умолчанию QR, парольная форма показывается по кнопке =====
const [showPasswordLogin, setShowPasswordLogin] = useState(false);
// ===== QR =====
const [qrLoading, setQrLoading] = useState(false);
const [qrUrl, setQrUrl] = useState<string>('');
const qrRef = useRef<HTMLDivElement | null>(null);
const pollTimerRef = useRef<number | null>(null);
const [qrState, setQrState] = useState<'idle' | 'ready' | 'polling' | 'expired'>('idle');
const [pendingCount, setPendingCount] = useState(0);
// хранит один инстанс QRCodeStyling
const qrInstanceRef = useRef<QRCodeStyling | null>(null);
const deviceId = useMemo(() => {
const key = 'qr_device_id';
const existing = localStorage.getItem(key);
if (existing) return existing;
const v = (
crypto?.randomUUID?.() ?? `${Date.now()}_${Math.random()}`
).toString();
localStorage.setItem(key, v);
return v;
}, []);
// ===== Notifications =====
const [notifOpen, setNotifOpen] = useState(false);
const [notifMsg, setNotifMsg] = useState<React.ReactNode>('');
const [notifSeverity, setNotifSeverity] = useState<
'success' | 'info' | 'warning' | 'error'
>('info');
const [notifPos, setNotifPos] = useState<NotificationPosition>({
vertical: 'bottom',
horizontal: 'center',
});
useEffect(() => {
const list = loadPending();
setPendingCount(list.length);
}, []);
const handleContinuePending = () => {
const list = loadPending();
if (!list.length) return;
const last = list[0];
// чтобы Registration подхватил и сразу открыл verification
// можно также записать в launcher_config — удобно
saveConfig({ username: last.username, password: last.password ?? '' });
navigate('/registration', { replace: true });
};
const showNotification = (
message: React.ReactNode,
severity: 'success' | 'info' | 'warning' | 'error' = 'info',
position: NotificationPosition = getNotifPositionFromSettings(),
) => {
if (!isNotificationsEnabled()) return;
setNotifMsg(message);
setNotifSeverity(severity);
setNotifPos(position);
setNotifOpen(true);
};
const stopQrPolling = () => {
if (pollTimerRef.current) {
window.clearInterval(pollTimerRef.current);
pollTimerRef.current = null;
}
};
useEffect(() => {
return () => stopQrPolling();
}, []);
// создаём QR инстанс с теми же настройками, что в registration
useEffect(() => {
if (!qrInstanceRef.current) {
qrInstanceRef.current = new QRCodeStyling({
width: 300,
height: 300,
image: popalogo,
data: 'https://t.me/popa_popa_popa_bot?start=test',
shape: 'square',
margin: 10,
dotsOptions: {
gradient: {
type: 'linear',
colorStops: [
{ offset: 0, color: 'rgb(242,113,33)' },
{ offset: 1, color: 'rgb(233,64,87)' },
],
},
type: 'extra-rounded',
},
imageOptions: {
crossOrigin: 'anonymous',
margin: 20,
imageSize: 0.5,
},
backgroundOptions: {
color: 'transparent',
},
});
}
}, []);
// аппендим QR в контейнер, когда мы на QR-экране
useEffect(() => {
if (showPasswordLogin) return;
if (!qrRef.current) return;
if (!qrInstanceRef.current) return;
while (qrRef.current.firstChild) {
qrRef.current.removeChild(qrRef.current.firstChild);
}
qrInstanceRef.current.append(qrRef.current);
}, [showPasswordLogin]);
// при изменении URL обновляем data в QR
useEffect(() => {
if (!qrInstanceRef.current) return;
if (!qrUrl) return;
qrInstanceRef.current.update({ data: qrUrl });
}, [qrUrl]);
const startQrLogin = async () => {
setQrLoading(true);
setQrState('idle');
setQrUrl('');
stopQrPolling();
try {
const init = await qrInit(deviceId);
setQrUrl(init.qr_url);
setQrState('ready');
setQrState('polling');
pollTimerRef.current = window.setInterval(async () => {
try {
const res = await qrStatus(init.token, deviceId);
if (res.status === 'ok') {
stopQrPolling();
const session = {
accessToken: res.accessToken,
clientToken: res.clientToken,
selectedProfile: res.selectedProfile,
};
await auth.applySession(session as any, saveConfig);
if (onLoginSuccess) {
onLoginSuccess(res.selectedProfile?.name ?? config.username);
}
showNotification('Успешный вход через QR', 'success');
navigate('/');
return;
}
if (res.status === 'expired') {
stopQrPolling();
setQrState('expired');
showNotification('QR-код истёк. Нажми “Обновить QR”.', 'warning');
}
} catch {
// transient ошибки игнорим, следующий тик повторит
}
}, 2000);
} catch (e: any) {
showNotification(e?.message || 'Не удалось запустить QR-вход', 'error');
} finally {
setQrLoading(false);
}
};
// автозапуск QR при открытии страницы
useEffect(() => {
startQrLogin();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const goToPasswordLogin = () => {
stopQrPolling();
setShowPasswordLogin(true);
};
const backToQr = () => {
setShowPasswordLogin(false);
startQrLogin(); // перегенерим свежий QR при возврате
};
// ===== Password login =====
const mapAuthErrorToMessage = (error: any): string => {
const raw = error?.message ? String(error.message) : String(error);
if (raw.includes('Failed to fetch') || raw.includes('NetworkError')) {
return 'Сервер недоступен';
}
const jsonStart = raw.indexOf('{');
if (jsonStart !== -1) {
const jsonStr = raw.slice(jsonStart);
try {
const data = JSON.parse(jsonStr);
const detail = data?.detail;
if (detail === 'Invalid credentials')
return 'Неверный логин или пароль';
if (detail === 'User not verified') return 'Аккаунт не подтверждён';
if (typeof detail === 'string' && detail.trim()) return detail;
} catch {}
}
if (raw.includes('Invalid credentials')) return 'Неверный логин или пароль';
if (raw.includes('User not verified')) return 'Аккаунт не подтверждён';
return raw.startsWith('Ошибка') ? raw : `Ошибка: ${raw}`;
};
const handleLogin = async () => {
if (!config.username.trim()) {
console.log('Ошибка: не указан никнейм');
alert('Введите никнейм!');
showNotification('Введите никнейм!', 'warning');
return;
}
if (!config.password) {
showNotification('Введите пароль!', 'warning');
return;
}
setLoading(true);
try {
// Проверяем, есть ли сохранённый токен
if (config.accessToken && config.clientToken) {
console.log('Проверка валидности существующего токена...');
const isValid = await validateSession(config.accessToken);
const isValid = await auth.validateSession(config.accessToken);
if (!isValid) {
console.log('Токен недействителен, пытаемся обновить...');
const refreshedSession = await refreshSession(
const refreshed = await auth.refreshSession(
config.accessToken,
config.clientToken,
);
if (!refreshedSession) {
console.log(
'Не удалось обновить токен, требуется новая авторизация',
if (!refreshed) {
await auth.authenticateUser(
config.username,
config.password,
saveConfig,
);
// Очищаем недействительные токены
saveConfig({
accessToken: '',
clientToken: '',
});
// Пытаемся выполнить новую авторизацию
if (config.password) {
const newSession = await authenticateWithElyBy(
config.username,
config.password,
saveConfig,
);
if (!newSession) {
console.log('Авторизация не удалась');
return;
}
} else {
console.log('Требуется ввод пароля для новой авторизации');
return;
}
}
} else {
console.log('Токен действителен');
}
} else {
console.log('Токен отсутствует, выполняем авторизацию...');
// Проверяем наличие пароля
if (!config.password) {
console.log('Ошибка: не указан пароль');
alert('Введите пароль!');
return;
}
const session = await authenticateWithElyBy(
await auth.authenticateUser(
config.username,
config.password,
saveConfig,
);
if (!session) {
console.log('Авторизация не удалась');
return;
}
}
console.log('Авторизация успешно завершена');
if (onLoginSuccess) {
onLoginSuccess(config.username);
}
if (onLoginSuccess) onLoginSuccess(config.username);
showNotification('Успешный вход', 'success');
navigate('/');
} catch (error: any) {
console.log(`ОШИБКА при авторизации: ${error.message}`);
console.error('Ошибка авторизации:', error);
const msg = mapAuthErrorToMessage(error);
showNotification(msg, 'error');
saveConfig({
accessToken: '',
clientToken: '',
@ -109,20 +430,459 @@ const Login = ({ onLoginSuccess }: LoginProps) => {
}
};
const gradientTextSx = {
fontFamily: 'Benzin-Bold',
fontSize: '1.5vw',
textTransform: 'uppercase',
letterSpacing: '0.08em',
cursor: 'pointer',
backgroundImage:
'linear-gradient(71deg, #F27121 0%, #E940CD 60%, #8A2387 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
textShadow: '0 0 15px rgba(0,0,0,0.9)',
'&:hover': { opacity: 1 },
} as const;
const primaryButtonSx = {
transition: 'transform 0.3s ease',
width: '60%',
mt: 2,
background: 'linear-gradient(71deg, #F27121 0%, #E940CD 70%, #8A2387 100%)',
fontFamily: 'Benzin-Bold',
borderRadius: '2.5vw',
fontSize: '2vw',
'&:hover': { transform: 'scale(1.1)' },
} as const;
return (
<Box>
<Box
sx={{
width: '100%',
minHeight: 'calc(100vh - 8vh)',
display: 'grid',
placeItems: 'center',
px: '2vw',
}}
>
{loading ? (
<FullScreenLoader message="Входим..." />
) : (
<>
<PopaPopa />
<AuthForm
config={config}
handleInputChange={handleInputChange}
onLogin={authorization}
/>
</>
<GlassPaper
sx={{
// width: 'min(64vw, 980px)',
borderRadius: '2.2vw',
}}
>
<Glow />
<Box sx={{ position: 'relative', p: '2.2vw' }}>
{/* header */}
<Stack alignItems="center">
<PopaPopa />
{!showPasswordLogin ? (
<Stack direction="row" spacing={1} alignItems="center" sx={{ my: '1vw' }}>
<GradientTitle sx={{ fontSize: 'clamp(16px, 1.2vw, 18px)' }}>
Вход через Telegram
</GradientTitle>
<Box
sx={{
px: 1.2,
py: 0.45,
borderRadius: 999,
fontSize: 'clamp(10px, 0.75vw, 12px)',
fontWeight: 900,
letterSpacing: '0.03em',
color: 'rgba(255,255,255,0.9)',
border: '1px solid rgba(255,255,255,0.10)',
background:
qrState === 'polling'
? 'rgba(255,255,255,0.06)'
: qrState === 'expired'
? 'rgba(255,60,60,0.12)'
: 'rgba(255,255,255,0.06)',
}}
>
{qrState === 'polling' ? 'ожидание' : qrState === 'expired' ? 'истёк' : 'готов'}
</Box>
</Stack>
) : (
<Stack direction="row" spacing={1} alignItems="center" sx={{ my: '1vw' }}>
<GradientTitle sx={{ fontSize: 'clamp(16px, 1.2vw, 18px)' }}>
Вход по логину и паролю
</GradientTitle>
</Stack>
)}
{/* segmented */}
{pendingCount > 0 ? (
<Box sx={{ mb: '1vw' }}>
{/* <Button
fullWidth
onClick={handleContinuePending}
sx={{
borderRadius: 999,
py: 1.1,
textTransform: 'none',
fontFamily: 'Benzin-Bold, sans-serif',
color: '#fff',
border: '1px solid rgba(255,255,255,0.14)',
background: 'rgba(255,255,255,0.06)',
'&:hover': { background: 'rgba(255,255,255,0.09)' },
}}
>
У вас {pendingCount} неподтвержденный аккаунт. Подтвердить сейчас
</Button> */}
<Typography>
У вас {pendingCount} неподтвержденный аккаунт. <span onClick={handleContinuePending} style={{ cursor: 'pointer', borderBottom: '1px solid #fff'}}>Подтвердить сейчас</span>
</Typography>
</Box>
) : (
<Segmented
exclusive
value={showPasswordLogin ? 'password' : 'qr'}
onChange={(_, v) => {
if (!v) return;
if (v === 'password') goToPasswordLogin();
else backToQr();
}}
sx={{ mb: '1vw' }}
>
<ToggleButton value="qr">
<Stack direction="row" spacing={1} alignItems="center">
<TelegramIcon sx={{ fontSize: 18 }} />
<span style={{textTransform: 'none'}}>Telegram QR</span>
</Stack>
</ToggleButton>
<ToggleButton value="password">
<Stack direction="row" spacing={1} alignItems="center">
<KeyIcon sx={{ fontSize: 18 }} />
<span style={{textTransform: 'none'}}>Логин + пароль</span>
</Stack>
</ToggleButton>
</Segmented>
)}
</Stack>
<Divider sx={{ borderColor: 'rgba(255,255,255,0.08)', mb: '1.6vw' }} />
{/* content */}
{!showPasswordLogin ? (
<Box
sx={{
display: 'grid',
gridTemplateColumns: { xs: '1fr', md: '1.05fr 0.95fr' },
gap: '1.6vw',
alignItems: 'start',
}}
>
{/* QR card */}
<Box
sx={{
position: 'relative',
borderRadius: '1.6vw',
border: '1px solid rgba(255,255,255,0.10)',
background:
'linear-gradient(180deg, rgba(255,255,255,0.06), rgba(255,255,255,0.03))',
p: '1.2vw',
overflow: 'hidden',
}}
>
{/* subtle top glow like marketplace cards */}
<Box
sx={{
position: 'absolute',
inset: 0,
pointerEvents: 'none',
background:
'radial-gradient(circle at top, rgba(242,113,33,0.18), transparent 60%)',
opacity: 0.9,
}}
/>
<Box sx={{ position: 'relative' }}>
{/* IMPORTANT: relative wrapper so expired overlay is positioned correctly */}
<Box
sx={{
position: 'relative',
display: 'grid',
placeItems: 'center',
borderRadius: '1.2vw',
border: '1px solid rgba(255,255,255,0.12)',
background:
'linear-gradient(135deg, rgba(40,40,40,0.55), rgba(15,15,15,0.55))',
// minHeight: 340,
// py: 2,
boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.04)',
overflow: 'hidden',
}}
>
<Box
sx={{
position: 'absolute',
inset: -2,
borderRadius: '1.3vw',
padding: '2px',
background:
'linear-gradient(90deg, rgba(242,113,33,0.0), rgba(242,113,33,0.35), rgba(233,64,205,0.35), rgba(138,35,135,0.35), rgba(242,113,33,0.0))',
backgroundSize: '240% 240%',
animation: `${borderShimmer} 7s ease-in-out infinite`,
pointerEvents: 'none',
mask:
'linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)',
WebkitMask:
'linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)',
maskComposite: 'exclude',
WebkitMaskComposite: 'xor',
opacity: qrState === 'expired' ? 0.18 : 0.45,
}}
/>
<div ref={qrRef} style={{ minHeight: 300 }} />
{qrState === 'expired' && (
<Box
sx={{
position: 'absolute',
inset: 0,
display: 'grid',
placeItems: 'center',
background:
'linear-gradient(180deg, rgba(0,0,0,0.60), rgba(0,0,0,0.35))',
backdropFilter: 'blur(10px)',
textAlign: 'center',
borderRadius: '1.2vw',
px: 2,
}}
>
<Typography
sx={{
fontFamily: 'Benzin-Bold',
fontSize: 'clamp(14px, 1.05vw, 18px)',
color: alpha('#fff', 0.92),
}}
>
QR-код истёк
</Typography>
<Typography
sx={{
mt: 0.6,
fontSize: 'clamp(12px, 0.9vw, 14px)',
color: alpha('#fff', 0.75),
}}
>
Нажми Обновить QR, чтобы получить новый
</Typography>
</Box>
)}
</Box>
<Typography
sx={{
mt: 1,
textAlign: 'center',
fontSize: 'clamp(12px, 0.9vw, 14px)',
color: alpha('#fff', 0.75),
fontWeight: 700,
}}
>
{qrState === 'polling' && 'Ожидаем подтверждение…'}
{qrState === 'ready' && 'Сканируй QR в Telegram'}
{qrState === 'expired' && 'Нужно обновить QR'}
{qrState === 'idle' && 'Подготавливаем вход…'}
</Typography>
</Box>
</Box>
{/* actions */}
<Stack spacing={1.2} sx={{ pt: { xs: 0, md: '0.4vw' } }}>
<GradientTitle sx={{ fontSize: 'clamp(16px, 1.2vw, 18px)' }}>
Вход через Telegram
</GradientTitle>
<Typography
sx={{
color: 'rgba(255,255,255,0.70)',
fontWeight: 700,
fontSize: 'clamp(12px, 0.9vw, 14px)',
lineHeight: 1.35,
}}
>
1) Открой бота <br />
2) Сканируй QR <br />
3) Подтверди вход
</Typography>
<GradientButton
variant="contained"
onClick={() => qrUrl && window.open(qrUrl, '_blank')}
disabled={!qrUrl}
startIcon={<OpenInNewRoundedIcon />}
sx={{ py: 1.2, fontSize: 'clamp(12px, 0.95vw, 14px)' }}
>
Открыть бота
</GradientButton>
<Button
disableRipple
disableFocusRipple
onClick={startQrLogin}
startIcon={<RefreshRoundedIcon />}
sx={{
borderRadius: 999,
textTransform: 'none',
py: 1.0,
fontFamily: 'Benzin-Bold',
color: '#fff',
border: '1px solid rgba(255,255,255,0.12)',
background: 'rgba(255,255,255,0.06)',
'&:hover': { background: 'rgba(255,255,255,0.08)' },
}}
>
Обновить QR
</Button>
<Divider sx={{ borderColor: 'rgba(255,255,255,0.08)', my: 0.6 }} />
<Button
disableRipple
disableFocusRipple
onClick={() => navigate('/registration')}
startIcon={<PersonAddAlt1RoundedIcon />}
sx={{
textTransform: 'none',
borderRadius: 999,
py: 1.0,
fontFamily: 'Benzin-Bold',
color: '#fff',
background: 'rgba(255,255,255,0.06)',
'&:hover': { background: 'rgba(255,255,255,0.08)' },
}}
>
Зарегистрироваться
</Button>
{qrLoading && <FullScreenLoader fullScreen={false} message="Генерируем QR..." />}
</Stack>
</Box>
) : (
/* password */
<Box sx={{ display: 'grid', placeItems: 'center' }}>
<Box
sx={{
width: 'min(520px, 100%)',
borderRadius: '1.6vw',
border: '1px solid rgba(255,255,255,0.10)',
background:
'linear-gradient(180deg, rgba(255,255,255,0.06), rgba(255,255,255,0.03))',
p: '1.6vw',
}}
>
<GradientTitle sx={{ fontSize: 'clamp(16px, 1.2vw, 18px)', mb: 1 }}>
Вход по логину и паролю
</GradientTitle>
<Stack spacing={1.2}>
<GradientTextField
label="Никнейм"
required
name="username"
value={config.username}
onChange={handleInputChange}
sx={{
'& .MuiInputLabel-root.Mui-focused': {
display: 'none',
},
'& .MuiInputLabel-root.MuiInputLabel-shrink': {
display: 'none',
},
}}
/>
<GradientTextField
label="Пароль"
required
name="password"
type="password"
value={config.password}
onChange={handleInputChange}
sx={{
'& .MuiInputLabel-root.Mui-focused': {
display: 'none',
},
'& .MuiInputLabel-root.MuiInputLabel-shrink': {
display: 'none',
},
}}
/>
<GradientButton
variant="contained"
onClick={handleLogin}
sx={{
py: 1.2,
fontSize: 'clamp(12px, 0.95vw, 14px)',
mt: 0.6,
}}
>
Войти
</GradientButton>
<Stack direction="row" spacing={1}>
<Button
fullWidth
disableRipple
disableFocusRipple
onClick={() => navigate('/registration')}
sx={{
textTransform: 'none',
borderRadius: 999,
py: 1.0,
fontFamily: 'Benzin-Bold',
color: '#fff',
background: 'rgba(255,255,255,0.06)',
'&:hover': { background: 'rgba(255,255,255,0.08)' },
}}
>
Регистрация
</Button>
<Button
fullWidth
disableRipple
disableFocusRipple
onClick={backToQr}
sx={{
textTransform: 'none',
borderRadius: 999,
py: 1.0,
fontFamily: 'Benzin-Bold',
color: '#fff',
background: 'rgba(255,255,255,0.06)',
'&:hover': { background: 'rgba(255,255,255,0.08)' },
}}
>
Назад к QR
</Button>
</Stack>
</Stack>
</Box>
</Box>
)}
</Box>
</GlassPaper>
)}
<CustomNotification
open={notifOpen}
message={notifMsg}
severity={notifSeverity}
position={notifPos}
onClose={() => setNotifOpen(false)}
autoHideDuration={2500}
/>
</Box>
);
};

File diff suppressed because it is too large Load Diff

View File

@ -14,6 +14,14 @@ import { fetchNews, NewsItem, createNews, fetchMe, deleteNews } from '../api';
import { FullScreenLoader } from '../components/FullScreenLoader';
import { MarkdownEditor } from '../components/MarkdownEditor';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import React from 'react';
import CustomNotification, {
NotificationPosition,
} from '../components/Notifications/CustomNotification';
import {
getNotifPositionFromSettings,
isNotificationsEnabled,
} from '../utils/notifications';
export const News = () => {
const [news, setNews] = useState<NewsItem[]>([]);
@ -31,6 +39,17 @@ export const News = () => {
const [preview, setPreview] = useState('');
const [markdown, setMarkdown] = useState('');
const [notifOpen, setNotifOpen] = useState(false);
const [notifMsg, setNotifMsg] = useState<React.ReactNode>('');
const [notifSeverity, setNotifSeverity] = useState<
'success' | 'info' | 'warning' | 'error'
>('info');
const [notifPos, setNotifPos] = useState<NotificationPosition>({
vertical: 'bottom',
horizontal: 'center',
});
const [isAdmin, setIsAdmin] = useState(false);
useEffect(() => {
@ -103,6 +122,18 @@ export const News = () => {
}
};
const showNotification = (
message: React.ReactNode,
severity: 'success' | 'info' | 'warning' | 'error' = 'info',
position: NotificationPosition = getNotifPositionFromSettings(),
) => {
if (!isNotificationsEnabled()) return;
setNotifMsg(message);
setNotifSeverity(severity);
setNotifPos(position);
setNotifOpen(true);
};
const handleDeleteNews = async (id: string) => {
const confirmed = window.confirm('Точно удалить эту новость?');
if (!confirmed) return;
@ -148,16 +179,79 @@ export const News = () => {
);
}
const PromoInline = ({ code }: { code: string }) => {
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(code);
showNotification(`Промокод ${code} скопирован`, 'success');
} catch {
// fallback для старых браузеров
const textarea = document.createElement('textarea');
textarea.value = code;
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
showNotification(`Промокод ${code} скопирован`, 'success');
}
};
return (
<Box
component="span"
onClick={handleCopy}
title="Нажмите, чтобы скопировать промокод"
sx={{
fontFamily: 'Benzin-Bold',
backgroundImage:
'linear-gradient(71deg, #F27121 0%, #E940CD 60%, #8A2387 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
px: '0.2em',
whiteSpace: 'nowrap',
cursor: 'pointer', // 👈 показывает интерактивность
userSelect: 'none',
'&:hover': {
filter: 'brightness(1.15)',
},
'&:active': {
transform: 'scale(0.97)',
},
transition: 'all 0.15s ease',
}}
>
{code}
</Box>
);
};
const renderWithPromoCodes = (text: string) => {
const parts = text.split(/(\/\/[A-Z0-9-_]+)/g);
return parts.map((part, i) => {
if (part.startsWith('//')) {
const code = part.slice(2);
return <PromoInline key={i} code={code} />;
}
return part;
});
};
return (
<Box
sx={{
px: '7vw',
pb: '4vh',
maxHeight: '100vh',
overflowY: 'auto',
display: 'flex',
flexDirection: 'column',
gap: '2vh',
width: '85%',
}}
>
{/* Админский редактор */}
@ -196,7 +290,7 @@ export const News = () => {
'& .MuiInputBase-root': {
backgroundColor: 'rgba(0,0,0,0.6)',
color: 'white',
borderRadius: '1.2vw'
borderRadius: '1.2vw',
},
'& .MuiInputLabel-root': {
color: 'rgba(255,255,255,0.7)',
@ -230,21 +324,24 @@ export const News = () => {
backgroundColor: 'rgba(0,0,0,0.6)',
borderRadius: '1.2vw',
overflow: 'hidden',
border: 'none'
border: 'none',
},
'& .editor-toolbar': { // полоски(разделители) иконок
'& .editor-toolbar': {
// полоски(разделители) иконок
background: 'transparent',
color: 'white',
border: 'none',
borderBottom: '1px solid #FFFFFF'
borderBottom: '1px solid #FFFFFF',
},
'& .editor-toolbar .fa': { // все иконки
'& .editor-toolbar .fa': {
// все иконки
color: 'white',
},
'& .CodeMirror': { // поле ввода
'& .CodeMirror': {
// поле ввода
backgroundColor: 'transparent',
color: 'white',
border: 'none'
border: 'none',
},
}}
>
@ -283,7 +380,7 @@ export const News = () => {
filter: 'brightness(1.05)',
transform: 'scale(1.02)',
},
transition: 'all 0.5s ease'
transition: 'all 0.5s ease',
}}
>
{creating ? 'Публикация...' : 'Опубликовать'}
@ -353,7 +450,6 @@ export const News = () => {
border: '1px solid rgba(255, 255, 255, 0)',
boxShadow: '0 18px 45px rgba(0, 0, 0, 0.7)',
backdropFilter: 'blur(14px)',
width: '80vw',
// transition:
// 'transform 0.25s ease, box-shadow 0.25s.ease, border-color 0.25s ease',
'&:hover': {
@ -433,12 +529,10 @@ export const News = () => {
onClick={() => handleToggleExpand(item.id)}
sx={{
transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)',
background:
'rgba(242,113,33,0.15)',
background: 'rgba(242,113,33,0.15)',
borderRadius: '1.4vw',
'&:hover': {
background:
'rgba(242,113,33,0.4)',
background: 'rgba(242,113,33,0.4)',
},
transition: 'all 0.25s ease',
}}
@ -506,7 +600,7 @@ export const News = () => {
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
p: ({ node, ...props }) => (
p: ({ node, children, ...props }) => (
<Typography
{...props}
sx={{
@ -514,13 +608,19 @@ export const News = () => {
fontSize: '1.5vw',
lineHeight: 1.6,
mb: 1,
whiteSpace: 'pre-line', // ← вот это
whiteSpace: 'pre-line',
textAlign: 'center', // вместо alignItems center
'&:last-of-type': { mb: 0 },
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
wordBreak: 'break-word',
overflowWrap: 'anywhere',
}}
/>
>
{React.Children.map(children, (child) =>
typeof child === 'string'
? renderWithPromoCodes(child)
: child,
)}
</Typography>
),
strong: ({ node, ...props }) => (
<Box
@ -692,6 +792,14 @@ export const News = () => {
</Paper>
);
})}
<CustomNotification
open={notifOpen}
message={notifMsg}
severity={notifSeverity}
position={notifPos}
onClose={() => setNotifOpen(false)}
autoHideDuration={2500}
/>
</Box>
</Box>
);

View File

@ -349,8 +349,8 @@ export default function Profile() {
}}
>
<SkinViewer
width={400}
height={465}
width={340}
height={405}
skinUrl={skin}
capeUrl={cape}
walkingSpeed={walkingSpeed}

View File

@ -0,0 +1,170 @@
import { Box, Button, Typography } from '@mui/material';
import { useEffect, useState } from 'react';
import GradientTextField from '../components/GradientTextField';
import CustomNotification from '../components/Notifications/CustomNotification';
import type { NotificationPosition } from '../components/Notifications/CustomNotification';
import {
isNotificationsEnabled,
getNotifPositionFromSettings,
} from '../utils/notifications';
import { redeemPromoCode } from '../api/promocodes';
import { useNavigate } from 'react-router-dom';
export const PromoRedeem = () => {
const navigate = useNavigate();
const [username, setUsername] = useState<string>(''); // будет автозаполнение
const [code, setCode] = useState('');
const [loading, setLoading] = useState(false);
const [notifOpen, setNotifOpen] = useState(false);
const [notifMsg, setNotifMsg] = useState<React.ReactNode>('');
const [notifSeverity, setNotifSeverity] = useState<
'success' | 'info' | 'warning' | 'error'
>('info');
const [notifPos, setNotifPos] = useState<NotificationPosition>({
vertical: 'bottom',
horizontal: 'center',
});
const showNotification = (
message: React.ReactNode,
severity: 'success' | 'info' | 'warning' | 'error' = 'info',
position: NotificationPosition = getNotifPositionFromSettings(),
) => {
if (!isNotificationsEnabled()) return;
setNotifMsg(message);
setNotifSeverity(severity);
setNotifPos(position);
setNotifOpen(true);
};
// как в Profile.tsx: читаем launcher_config
useEffect(() => {
try {
const savedConfig = localStorage.getItem('launcher_config');
if (savedConfig) {
const config = JSON.parse(savedConfig);
setUsername(config.username || '');
}
} catch {
setUsername('');
}
}, []);
const handleRedeem = async () => {
if (!username) {
showNotification(
'Не удалось определить никнейм. Войдите в аккаунт заново.',
'warning',
);
// по желанию можно отправить в login/profile:
// navigate('/login', { replace: true });
return;
}
if (!code) {
showNotification('Введите промокод', 'warning');
return;
}
setLoading(true);
try {
const res = await redeemPromoCode(username, code);
showNotification(
<>
Промокод <b>{res.code}</b> успешно активирован!
</>,
'success',
);
setCode('');
} catch (e: any) {
showNotification(e?.message || 'Ошибка активации промокода', 'error');
} finally {
setLoading(false);
}
};
return (
<>
<Box
sx={{
height: 'calc(100vh - 8vh)',
pt: '8vh',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
px: 2,
}}
>
<Typography
variant="h4"
sx={{
textAlign: 'center',
fontFamily: 'Benzin-Bold',
backgroundImage:
'linear-gradient( 136deg, rgb(242,113,33) 0%, rgb(233,64,87) 50%, rgb(138,35,135) 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
mb: 2,
}}
>
Активация промокода
</Typography>
<Box
sx={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
width: '50vw',
}}
>
<GradientTextField
label=""
required
name="code"
value={code}
onChange={(e) => setCode(e.target.value.toUpperCase())}
/>
<Button
variant="contained"
color="primary"
disabled={loading}
sx={{
transition: 'transform 0.3s ease',
width: '100%',
mt: 2,
background:
'linear-gradient(71deg, #F27121 0%, #E940CD 70%, #8A2387 100%)',
fontFamily: 'Benzin-Bold',
borderRadius: '2.5vw',
fontSize: '2vw',
'&:hover': {
transform: loading ? 'none' : 'scale(1.1)',
},
}}
onClick={handleRedeem}
>
{loading ? 'Активируем...' : 'Активировать'}
</Button>
</Box>
<CustomNotification
open={notifOpen}
message={notifMsg}
severity={notifSeverity}
position={notifPos}
onClose={() => setNotifOpen(false)}
autoHideDuration={2500}
/>
</Box>
</>
);
};

File diff suppressed because it is too large Load Diff

View File

@ -17,6 +17,7 @@ import {
import CustomNotification from '../components/Notifications/CustomNotification';
import type { NotificationPosition } from '../components/Notifications/CustomNotification';
import { isNotificationsEnabled, getNotifPositionFromSettings } from '../utils/notifications';
import SettingCheckboxRow from '../components/CustomComponents/SettingCheckboxRow';
type SettingsState = {
// UI
@ -25,8 +26,11 @@ type SettingsState = {
blurEffects: boolean;
// Launcher / app
autoUpdate: boolean;
autoLaunch: boolean;
startInTray: boolean;
closeToTray: boolean;
disableToolTip: boolean;
allowEssentialTooltips: boolean;
// Game
autoRotateSkinViewer: boolean;
@ -35,6 +39,9 @@ type SettingsState = {
// Notifications
notifications: boolean;
notificationPosition: 'top-right' | 'top-center' | 'top-left' | 'bottom-right' | 'bottom-center' | 'bottom-left';
// Navigation
rememberLastRoute: boolean;
};
const STORAGE_KEY = 'launcher_settings';
@ -42,19 +49,69 @@ const STORAGE_KEY = 'launcher_settings';
const GRADIENT =
'linear-gradient(71deg, #F27121 0%, #E940CD 70%, #8A2387 100%)';
const SLIDER_SX = {
mt: 0.6,
'& .MuiSlider-rail': {
opacity: 1,
height: '0.55vw',
borderRadius: '999px',
backgroundColor: 'rgba(255,255,255,0.10)',
},
'& .MuiSlider-track': {
height: '0.55vw',
border: 'none',
borderRadius: '999px',
background:
'linear-gradient(90deg, rgba(242,113,33,1) 0%, rgba(233,64,205,1) 55%, rgba(138,35,135,1) 100%)',
boxShadow: '0 0.6vw 1.6vw rgba(233,64,205,0.18)',
},
'& .MuiSlider-thumb': {
width: '1.65vw',
height: '1.65vw',
borderRadius: '999px',
backgroundColor: 'rgba(10,10,20,0.92)',
border: '2px solid rgba(255,255,255,0.18)',
boxShadow: '0 0 1.6vw rgba(233,64,205,0.35)',
transition: 'transform 0.15s ease, box-shadow 0.15s ease, height 0.3s ease, width 0.3s ease',
'&:before': { display: 'none' },
'&:hover, &.Mui-focusVisible': {
width: '1.95vw',
height: '1.95vw',
boxShadow: '0 0 2.2vw rgba(242,113,33,0.35)',
},
'&:active': { width: '1.95vw', height: '1.95vw', },
},
'& .MuiSlider-valueLabel': {
borderRadius: '999px',
background: 'rgba(10,10,20,0.92)',
border: '1px solid rgba(255,255,255,0.10)',
backdropFilter: 'blur(12px)',
fontFamily: 'Benzin-Bold',
},
} as const;
const defaultSettings: SettingsState = {
uiScale: 100,
reduceMotion: false,
blurEffects: true,
autoUpdate: true,
startInTray: false,
autoLaunch: false,
closeToTray: true,
disableToolTip: false,
allowEssentialTooltips: true,
autoRotateSkinViewer: true,
walkingSpeed: 0.5,
notifications: true,
notificationPosition: 'top-right',
notificationPosition: 'bottom-center',
rememberLastRoute: true,
};
function safeParseSettings(raw: string | null): SettingsState | null {
@ -164,6 +221,40 @@ const mapNotifPosition = (
return { vertical, horizontal };
};
const SectionTitle = ({ children }: { children: string }) => (
<Typography
sx={{
fontFamily: 'Benzin-Bold',
fontSize: '1.25vw',
lineHeight: 1.1,
backgroundImage: GRADIENT,
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
mb: '0.9vw',
}}
>
{children}
</Typography>
);
const Glass = ({ children }: { children: React.ReactNode }) => (
<Paper
className="glass glass--soft"
elevation={0}
sx={{
borderRadius: '1.2vw',
overflow: 'hidden',
background:
'radial-gradient(circle at 10% 10%, rgba(242,113,33,0.14), transparent 55%), radial-gradient(circle at 90% 20%, rgba(233,64,205,0.12), transparent 55%), rgba(10,10,20,0.86)',
border: '1px solid rgba(255,255,255,0.08)',
boxShadow: '0 1.2vw 3.2vw rgba(0,0,0,0.55)',
color: 'white',
}}
>
<Box sx={{ p: '1.8vw' }}>{children}</Box>
</Paper>
);
const Settings = () => {
const [lastSavedSettings, setLastSavedSettings] = useState<SettingsState>(() => {
if (typeof window === 'undefined') return defaultSettings;
@ -185,6 +276,11 @@ const Settings = () => {
return safeParseSettings(localStorage.getItem(STORAGE_KEY)) ?? defaultSettings;
});
const setFlag =
<K extends keyof SettingsState>(key: K) =>
(v: SettingsState[K]) =>
setSettings((s) => ({ ...s, [key]: v }));
const dirty = useMemo(() => {
return JSON.stringify(settings) !== JSON.stringify(lastSavedSettings);
}, [settings, lastSavedSettings]);
@ -229,47 +325,10 @@ const Settings = () => {
};
useEffect(() => {
if (typeof document === 'undefined') return;
const scale = settings.uiScale / 100;
document.documentElement.style.setProperty('--ui-scale', String(scale));
// motion / blur классы — глобально на body
document.body.classList.toggle('reduce-motion', settings.reduceMotion);
document.body.classList.toggle('no-blur', !settings.blurEffects);
}, [settings.uiScale, settings.reduceMotion, settings.blurEffects]);
const SectionTitle = ({ children }: { children: string }) => (
<Typography
sx={{
fontFamily: 'Benzin-Bold',
fontSize: '1.25vw',
lineHeight: 1.1,
backgroundImage: GRADIENT,
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
mb: '0.9vw',
}}
>
{children}
</Typography>
);
const Glass = ({ children }: { children: React.ReactNode }) => (
<Paper
elevation={0}
sx={{
borderRadius: '1.2vw',
overflow: 'hidden',
background:
'radial-gradient(circle at 10% 10%, rgba(242,113,33,0.14), transparent 55%), radial-gradient(circle at 90% 20%, rgba(233,64,205,0.12), transparent 55%), rgba(10,10,20,0.86)',
border: '1px solid rgba(255,255,255,0.08)',
boxShadow: '0 1.2vw 3.2vw rgba(0,0,0,0.55)',
backdropFilter: 'blur(14px)',
color: 'white',
}}
>
<Box sx={{ p: '1.8vw' }}>{children}</Box>
</Paper>
);
}, [settings.reduceMotion, settings.blurEffects]);
const controlSx = {
'& .MuiFormControlLabel-label': {
@ -287,13 +346,18 @@ const Settings = () => {
},
} as const;
useEffect(() => {
document.body.classList.toggle('no-blur', !settings.blurEffects);
}, [settings.blurEffects]);
return (
<Box
sx={{
px: '2vw',
pb: '2vw',
width: '100%',
width: '95%',
boxSizing: 'border-box',
overflowY: 'auto',
}}
>
<CustomNotification
@ -394,39 +458,24 @@ const Settings = () => {
max={120}
step={5}
onChange={(_, v) => setSettings((s) => ({ ...s, uiScale: v as number }))}
sx={{
mt: 0.4,
'& .MuiSlider-thumb': { boxShadow: '0 10px 22px rgba(0,0,0,0.45)' },
}}
sx={SLIDER_SX}
/>
</Box>
<Divider sx={{ borderColor: 'rgba(255,255,255,0.10)' }} />
<FormControlLabel
control={
<Switch
checked={settings.reduceMotion}
onChange={(e) =>
setSettings((s) => ({ ...s, reduceMotion: e.target.checked }))
}
/>
}
label="Уменьшить анимации"
sx={controlSx}
<SettingCheckboxRow
title="Уменьшить анимации"
description="Отключить все анимации лаунчера"
checked={settings.reduceMotion}
onChange={setFlag('reduceMotion')}
/>
<FormControlLabel
control={
<Switch
checked={settings.blurEffects}
onChange={(e) =>
setSettings((s) => ({ ...s, blurEffects: e.target.checked }))
}
/>
}
label="Эффекты размытия (blur)"
sx={controlSx}
<SettingCheckboxRow
title="Эффекты размытия (blur)"
description="Компоненты будут прозрачными без размытия"
checked={settings.blurEffects}
onChange={setFlag('blurEffects')}
/>
</Box>
</Glass>
@ -435,17 +484,11 @@ const Settings = () => {
<SectionTitle>Уведомления</SectionTitle>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: '1.1vw' }}>
<FormControlLabel
control={
<Switch
checked={settings.notifications}
onChange={(e) =>
setSettings((s) => ({ ...s, notifications: e.target.checked }))
}
/>
}
label="Включить уведомления"
sx={controlSx}
<SettingCheckboxRow
title="Включить уведомления"
description="Уведомления о каких-либо действиях"
checked={settings.notifications}
onChange={setFlag('notifications')}
/>
<NotificationPositionPicker
@ -473,20 +516,13 @@ const Settings = () => {
{/* RIGHT */}
<Box sx={{ display: 'flex', flexDirection: 'column', gap: '2vw', minWidth: 0 }}>
<Glass>
<SectionTitle>Игра</SectionTitle>
<SectionTitle> </SectionTitle>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: '1.1vw' }}>
<FormControlLabel
control={
<Switch
checked={settings.autoRotateSkinViewer}
onChange={(e) =>
setSettings((s) => ({ ...s, autoRotateSkinViewer: e.target.checked }))
}
/>
}
label="Автоповорот персонажа в профиле"
sx={controlSx}
<SettingCheckboxRow
title="Автоповорот персонажа в профиле"
description="Прокрут игрового персонажа в профиле"
checked={settings.autoRotateSkinViewer}
onChange={setFlag('autoRotateSkinViewer')}
/>
<Box>
@ -499,13 +535,9 @@ const Settings = () => {
max={1}
step={0.05}
onChange={(_, v) => setSettings((s) => ({ ...s, walkingSpeed: v as number }))}
sx={{ mt: 0.4 }}
sx={SLIDER_SX}
/>
</Box>
<Typography sx={{ color: 'rgba(255,255,255,0.60)', fontWeight: 700, fontSize: '0.9vw' }}>
Эти значения можно прокинуть в Profile: autoRotate и walkingSpeed.
</Typography>
</Box>
</Glass>
@ -513,54 +545,47 @@ const Settings = () => {
<SectionTitle>Лаунчер</SectionTitle>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: '1.1vw' }}>
<FormControlLabel
control={
<Switch
checked={settings.autoUpdate}
onChange={(e) => setSettings((s) => ({ ...s, autoUpdate: e.target.checked }))}
/>
}
label="Автообновление данных (где поддерживается)"
sx={controlSx}
<SettingCheckboxRow
title="Запускать вместе с системой"
description="Лаунчер будет запускаться при старте Windows"
checked={settings.autoLaunch}
onChange={setFlag('autoLaunch')}
/>
<FormControlLabel
control={
<Switch
checked={settings.startInTray}
onChange={(e) => setSettings((s) => ({ ...s, startInTray: e.target.checked }))}
/>
}
label="Запускать свернутым (в трей)"
sx={controlSx}
<SettingCheckboxRow
title="Запускать свернутым (в трей)"
description="Окно не показывается при старте"
checked={settings.startInTray}
onChange={setFlag('startInTray')}
/>
<Divider sx={{ borderColor: 'rgba(255,255,255,0.10)' }} />
<SettingCheckboxRow
title="При закрытии сворачивать в трей"
description="Крестик не закрывает приложение полностью"
checked={settings.closeToTray}
onChange={setFlag('closeToTray')}
/>
<Button
onClick={() => {
// просто пример действия
try {
localStorage.removeItem('launcher_cache');
} catch {}
}}
disableRipple
sx={{
borderRadius: '999px',
py: '0.8vw',
fontFamily: 'Benzin-Bold',
color: '#fff',
background: 'rgba(255,255,255,0.10)',
border: '1px solid rgba(255,255,255,0.10)',
'&:hover': { background: 'rgba(255,255,255,0.14)' },
}}
>
Очистить кэш (пример)
</Button>
<SettingCheckboxRow
title="Запоминать последнюю страницу"
description="После перезапуска откроется тот же раздел"
checked={settings.rememberLastRoute}
onChange={setFlag('rememberLastRoute')}
/>
<Typography sx={{ color: 'rgba(255,255,255,0.60)', fontWeight: 700, fontSize: '0.9vw' }}>
Кнопка-заглушка: можно подключить к вашим реальным ключам localStorage.
</Typography>
<SettingCheckboxRow
title="Отключить подсказки"
description="Отключить подсказки при наведении на элементы"
checked={settings.disableToolTip}
onChange={setFlag('disableToolTip')}
/>
<SettingCheckboxRow
title="Показывать важные подсказки"
description="Некоторые подсказки нельзя отключить (важные)"
checked={settings.allowEssentialTooltips}
onChange={setFlag('allowEssentialTooltips')}
/>
</Box>
</Glass>
</Box>

File diff suppressed because it is too large Load Diff

View File

@ -289,6 +289,7 @@ export const VersionsExplorer = () => {
flexDirection: 'column',
gap: '2vh',
height: '100%',
width: '85%',
}}
>
{loading ? (

View File

@ -0,0 +1,163 @@
import { useEffect, useRef, useState } from 'react';
import { RoomsPanel } from '../components/Voice/RoomsPanel';
import { VoicePanel } from '../components/Voice/VoicePanel';
import {
fetchRooms,
createPublicRoom,
joinPrivateRoom,
} from '../api/voiceRooms';
import { mapApiRoomToUI } from '../mappers/roomMapper';
import type { RoomInfo } from '../types/rooms';
import { CreateRoomDialog } from '../components/Voice/CreateRoomDialog';
import { JoinByCodeDialog } from '../components/Voice/JoinByCodeDialog';
import { useVoiceRoom } from '../realtime/voice/useVoiceRoom';
export default function VoicePage() {
const [username, setUsername] = useState('');
const [rooms, setRooms] = useState<RoomInfo[]>([]);
const [currentRoomId, setCurrentRoomId] = useState<string | null>(null);
const [currentRoom, setCurrentRoom] = useState<RoomInfo | null>(null);
const [createOpen, setCreateOpen] = useState(false);
const [joinOpen, setJoinOpen] = useState(false);
const voice = useVoiceRoom(username);
const wsRef = useRef<WebSocket | null>(null);
// --- username ---
useEffect(() => {
const savedConfig = localStorage.getItem('launcher_config');
if (savedConfig) {
const config = JSON.parse(savedConfig);
if (config.username) {
setUsername(config.username);
}
}
}, []);
// --- HTTP: initial rooms list ---
useEffect(() => {
if (!username) return;
fetchRooms()
.then((apiRooms) => {
setRooms(apiRooms.map(mapApiRoomToUI));
})
.catch(console.error);
}, [username]);
// --- open dialog ---
const handleCreateClick = () => {
setCreateOpen(true);
};
// --- WS: users inside rooms ---
useEffect(() => {
if (!username) return;
const ws = new WebSocket(
`wss://minecraft.api.popa-popa.ru/ws/rooms?username=${username}`,
);
ws.onmessage = (ev) => {
const msg = JSON.parse(ev.data);
if (msg.type !== 'rooms') return;
setRooms((prev) => {
const map = new Map(prev.map((r) => [r.id, r]));
for (const updated of msg.rooms) {
const existing = map.get(updated.id);
if (!existing) continue;
map.set(updated.id, {
...existing,
users: updated.users ?? [],
});
}
return Array.from(map.values());
});
};
return () => ws.close();
}, [username]);
// --- handlers ---
const joinRoom = (roomId: string) => {
const room = rooms.find((r) => r.id === roomId);
if (!room) return;
setCurrentRoomId(roomId);
setCurrentRoom(room);
voice.connect(roomId); // 🔥 АВТОПОДКЛЮЧЕНИЕ
};
const handleCreateRoom = async ({
name,
isPublic,
}: {
name: string;
isPublic: boolean;
}) => {
const apiRoom = await createPublicRoom(name, username, isPublic);
const room: RoomInfo = mapApiRoomToUI(apiRoom);
setRooms((prev) => [room, ...prev]);
setCurrentRoomId(apiRoom.id);
return {
invite_code: apiRoom.invite_code ?? null,
};
};
const handleJoinByCode = async (code: string) => {
const room = await joinPrivateRoom(code);
setCurrentRoomId(room.id);
setCurrentRoom({
id: room.id,
name: room.name,
public: false,
users: [],
maxUsers: room.max_users,
});
};
if (!username) return null;
return (
<div
style={{ display: 'flex', width: '98%', height: '90%', marginTop: '9vh' }}
>
<RoomsPanel
rooms={rooms}
currentRoomId={currentRoomId}
onJoin={joinRoom}
onCreate={() => setCreateOpen(true)}
onJoinByCode={() => setJoinOpen(true)}
/>
<CreateRoomDialog
open={createOpen}
onClose={() => setCreateOpen(false)}
onCreate={handleCreateRoom}
/>
<JoinByCodeDialog
open={joinOpen}
onClose={() => setJoinOpen(false)}
onJoin={handleJoinByCode}
/>
{currentRoomId && (
<VoicePanel
roomId={currentRoomId}
voice={voice}
roomName={currentRoom.name}
/>
)}
</div>
);
}

View File

@ -0,0 +1,3 @@
export const rtcConfig: RTCConfiguration = {
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
};

View File

@ -0,0 +1,13 @@
export type WSMessage =
| { type: 'users'; users: string[] }
| { type: 'join'; user: string }
| { type: 'leave'; user: string }
| {
type: 'signal';
from: string;
data: {
type: 'offer' | 'answer' | 'ice';
sdp?: RTCSessionDescriptionInit;
candidate?: RTCIceCandidateInit;
};
};

View File

@ -0,0 +1,298 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { rtcConfig } from './rtcConfig';
import type { WSMessage } from './types';
import { setVoiceState, getVoiceState } from './voiceStore';
type PeerMap = Map<string, RTCPeerConnection>;
export function useVoiceRoom(username: string) {
const wsRef = useRef<WebSocket | null>(null);
const peersRef = useRef<PeerMap>(new Map());
const streamRef = useRef<MediaStream | null>(null);
const currentRoomIdRef = useRef<string | null>(null);
const reconnectTimeout = useRef<number | null>(null);
// const [connected, setConnected] = useState(false);
// const [participants, setParticipants] = useState<string[]>([]);
// const [muted, setMuted] = useState(false);
const pendingIceRef = useRef<Map<string, RTCIceCandidateInit[]>>(new Map());
// --- connect ---
const connect = useCallback(
async (roomId: string) => {
if (wsRef.current) return;
currentRoomIdRef.current = roomId;
// 1. микрофон
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true,
},
});
streamRef.current = stream;
// 2. websocket
const ws = new WebSocket(
`wss://minecraft.api.popa-popa.ru/ws/voice?room_id=${roomId}&username=${username}`,
);
wsRef.current = ws;
ws.onopen = () => {
setVoiceState({
connected: true,
shouldBeConnected: true,
participants: [username],
});
};
ws.onclose = () => {
cleanup();
setVoiceState({ connected: false });
if (getVoiceState().shouldBeConnected) {
reconnectTimeout.current = window.setTimeout(() => {
const lastRoomId = currentRoomIdRef.current;
if (lastRoomId) {
connect(lastRoomId);
}
}, 1500);
}
};
// ws.onclose = () => {
// cleanup();
// setConnected(false);
// };
ws.onmessage = async (ev) => {
const msg: WSMessage = JSON.parse(ev.data);
if (msg.type === 'join' && msg.user !== username) {
await createPeer(msg.user, false);
const { participants } = getVoiceState();
if (!participants.includes(msg.user)) {
setVoiceState({
participants: [...participants, msg.user],
});
}
}
if (msg.type === 'leave') {
removePeer(msg.user);
setVoiceState({
participants: getVoiceState().participants.filter(
(u) => u !== msg.user,
),
});
}
if (msg.type === 'signal') {
await handleSignal(msg.from, msg.data);
}
if (msg.type === 'users') {
const current = getVoiceState().participants;
const next = msg.users;
// 1. удаляем ушедших
for (const user of current) {
if (!next.includes(user)) {
removePeer(user);
}
}
// 2. создаём peer для новых
for (const user of next) {
if (user !== username && !peersRef.current.has(user)) {
await createPeer(user, true);
}
}
// 3. обновляем store
setVoiceState({
participants: next,
});
}
};
},
[username],
);
// --- create peer ---
const createPeer = async (user: string, polite: boolean) => {
if (peersRef.current.has(user)) return;
const pc = new RTCPeerConnection(rtcConfig);
peersRef.current.set(user, pc);
streamRef.current
?.getTracks()
.forEach((t) => pc.addTrack(t, streamRef.current!));
pc.onicecandidate = (e) => {
if (e.candidate) {
wsRef.current?.send(
JSON.stringify({
type: 'signal',
to: user,
data: { type: 'ice', candidate: e.candidate },
}),
);
}
};
pc.ontrack = (e) => {
const audio = document.createElement('audio');
audio.srcObject = e.streams[0];
audio.autoplay = true;
audio.setAttribute('data-user', user);
document.body.appendChild(audio);
};
if (!polite) {
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
wsRef.current?.send(
JSON.stringify({
type: 'signal',
to: user,
data: { type: 'offer', sdp: offer },
}),
);
}
};
const removePeer = (user: string) => {
const pc = peersRef.current.get(user);
if (!pc) return;
pc.close();
peersRef.current.delete(user);
pendingIceRef.current.delete(user);
// удаляем audio элемент
const audio = document.querySelector(
`audio[data-user="${user}"]`,
) as HTMLAudioElement | null;
audio?.remove();
};
// --- signaling ---
const handleSignal = async (from: string, data: any) => {
let pc = peersRef.current.get(from);
if (!pc) {
await createPeer(from, true);
pc = peersRef.current.get(from)!;
}
if (data.type === 'offer') {
if (pc.signalingState !== 'stable') {
console.warn('Skip offer, state:', pc.signalingState);
return;
}
await pc.setRemoteDescription(data.sdp);
// 🔥 применяем накопленные ICE
const queued = pendingIceRef.current.get(from);
if (queued) {
for (const c of queued) {
await pc.addIceCandidate(c);
}
pendingIceRef.current.delete(from);
}
const answer = await pc.createAnswer();
await pc.setLocalDescription(answer);
wsRef.current?.send(
JSON.stringify({
type: 'signal',
to: from,
data: { type: 'answer', sdp: answer },
}),
);
}
if (data.type === 'answer') {
if (pc.signalingState === 'have-local-offer') {
await pc.setRemoteDescription(data.sdp);
const queued = pendingIceRef.current.get(from);
if (queued) {
for (const c of queued) {
await pc.addIceCandidate(c);
}
pendingIceRef.current.delete(from);
}
}
}
if (data.type === 'ice') {
if (pc.remoteDescription) {
await pc.addIceCandidate(data.candidate);
} else {
// ⏳ remoteDescription ещё нет — сохраняем
const queue = pendingIceRef.current.get(from) ?? [];
queue.push(data.candidate);
pendingIceRef.current.set(from, queue);
}
}
};
// --- mute ---
const toggleMute = () => {
if (!streamRef.current) return;
const enabled = !getVoiceState().muted;
streamRef.current.getAudioTracks().forEach((t) => (t.enabled = !enabled));
setVoiceState({ muted: enabled });
};
// --- cleanup ---
const cleanup = () => {
peersRef.current.forEach((pc) => pc.close());
peersRef.current.clear();
streamRef.current?.getTracks().forEach((t) => t.stop());
streamRef.current = null;
wsRef.current?.close();
wsRef.current = null;
if (reconnectTimeout.current) {
clearTimeout(reconnectTimeout.current);
reconnectTimeout.current = null;
}
document.querySelectorAll('audio[data-user]').forEach((a) => a.remove());
};
const disconnect = () => {
setVoiceState({
connected: false,
shouldBeConnected: false,
participants: [],
muted: false,
});
cleanup();
};
return {
connect,
disconnect,
toggleMute,
};
}

View File

@ -0,0 +1,32 @@
type VoiceState = {
connected: boolean;
shouldBeConnected: boolean;
participants: string[];
muted: boolean;
};
const state: VoiceState = {
connected: false,
shouldBeConnected: false,
participants: [],
muted: false,
};
const listeners = new Set<() => void>();
export function getVoiceState() {
return state;
}
export function setVoiceState(patch: Partial<VoiceState>) {
Object.assign(state, patch);
listeners.forEach((l) => l());
}
export function subscribeVoice(cb: () => void): () => void {
listeners.add(cb);
return () => {
listeners.delete(cb);
};
}

View File

@ -0,0 +1,14 @@
export function getWsBaseUrl(): string {
// 1) если ты пробрасываешь конфиг в window
const w = window as any;
if (w.__ENV__?.WS_BASE) return String(w.__ENV__.WS_BASE);
// 2) если открыто с https/http — строим ws/wss автоматически
if (typeof window !== 'undefined' && window.location?.origin) {
const origin = window.location.origin; // http(s)://host
return origin.replace(/^http/, 'ws');
}
// 3) дефолт
return 'wss://minecraft.api.popa-popa.ru';
}

View File

@ -0,0 +1,12 @@
export const GRADIENT =
'linear-gradient(71deg, #F27121 0%, #E940CD 70%, #8A2387 100%)';
export const glassBox = {
background:
'radial-gradient(circle at 10% 10%, rgba(242,113,33,0.12), transparent 55%),' +
'radial-gradient(circle at 90% 20%, rgba(233,64,205,0.10), transparent 55%),' +
'rgba(10,10,20,0.86)',
border: '1px solid rgba(255,255,255,0.10)',
backdropFilter: 'blur(14px)',
boxShadow: '0 1.2vw 3.2vw rgba(0,0,0,0.55)',
};

View File

@ -0,0 +1,17 @@
export type RoomInfo = {
id: string;
name: string;
public: boolean;
users: string[]; // usernames
maxUsers: number;
};
export type RoomDetails = {
id: string;
name: string;
owner: string;
max_users: number;
users: number;
usernames: string[];
public: boolean;
};

View File

@ -0,0 +1,27 @@
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
export function TrayBridge() {
const navigate = useNavigate();
useEffect(() => {
const onNavigate = (to: unknown) => {
navigate(String(to));
};
const onLogout = () => {
localStorage.removeItem('launcher_config');
navigate('/login');
};
window.electron.ipcRenderer.on('tray-navigate', onNavigate);
window.electron.ipcRenderer.on('tray-logout', onLogout);
return () => {
window.electron.ipcRenderer.removeAllListeners('tray-navigate');
window.electron.ipcRenderer.removeAllListeners('tray-logout');
};
}, [navigate]);
return null;
}

View File

@ -0,0 +1,106 @@
// utils/itemTranslator.ts
/* ----------------------------- */
/* ENCHANT TRANSLATIONS */
/* ----------------------------- */
export const ENCHANT_TRANSLATIONS: Record<string, string> = {
sharpness: 'Острота',
smite: 'Небесная кара',
bane_of_arthropods: 'Бич членистоногих',
efficiency: 'Эффективность',
unbreaking: 'Прочность',
fortune: 'Удача',
silk_touch: 'Шёлковое касание',
power: 'Сила',
punch: 'Отдача',
flame: 'Огонь',
infinity: 'Бесконечность',
protection: 'Защита',
fire_protection: 'Огнестойкость',
blast_protection: 'Взрывоустойчивость',
projectile_protection: 'Защита от снарядов',
feather_falling: 'Невесомость',
respiration: 'Подводное дыхание',
aqua_affinity: 'Подводник',
thorns: 'Шипы',
depth_strider: 'Подводная ходьба',
frost_walker: 'Ледоход',
mending: 'Починка',
binding_curse: 'Проклятие несъёмности',
vanishing_curse: 'Проклятие утраты',
looting: 'Добыча',
sweeping: 'Разящий клинок',
fire_aspect: 'Заговор огня',
knockback: 'Отдача',
luck_of_the_sea: 'Морская удача',
lure: 'Приманка',
};
/* ----------------------------- */
/* GENERIC META TRANSLATIONS */
/* ----------------------------- */
export const META_TRANSLATIONS: Record<string, string> = {
durability: 'Прочность',
max_durability: 'Максимальная прочность',
custom_model_data: 'Кастомная модель',
unbreakable: 'Неразрушимый',
repair_cost: 'Стоимость починки',
hide_flags: 'Скрытые флаги',
rarity: 'Редкость',
damage: 'Урон',
attack_speed: 'Скорость атаки',
armor: 'Броня',
armor_toughness: 'Твёрдость брони',
knockback_resistance: 'Сопротивление отталкиванию',
glowing: 'Подсветка',
};
/* ----------------------------- */
/* FORMATTERS */
/* ----------------------------- */
export function translateEnchant(key: string): string {
return ENCHANT_TRANSLATIONS[key.toLowerCase()] ?? beautifyKey(key);
}
export function translateMetaKey(key: string): string {
return META_TRANSLATIONS[key.toLowerCase()] ?? beautifyKey(key);
}
export function beautifyKey(key: string): string {
return key
.replace(/_/g, ' ')
.replace(/\b\w/g, (l) => l.toUpperCase());
}
/* ----------------------------- */
/* VALUE FORMATTERS */
/* ----------------------------- */
export function formatMetaValue(value: any): string {
if (typeof value === 'boolean') return value ? 'Да' : 'Нет';
if (typeof value === 'number') return String(value);
if (typeof value === 'string') return value;
if (Array.isArray(value)) return value.join(', ');
if (typeof value === 'object') return 'Сложное значение';
return String(value);
}
/* ----------------------------- */
/* ENCHANT LIST HELPER */
/* ----------------------------- */
export function formatEnchants(
enchants?: Record<string, number>,
): { label: string; level: number }[] {
if (!enchants || typeof enchants !== 'object') return [];
return Object.entries(enchants).map(([key, level]) => ({
label: translateEnchant(key),
level,
}));
}

View File

@ -0,0 +1,43 @@
export type PendingVerification = {
username: string;
password?: string;
createdAt: number;
};
const PENDING_KEY = 'pending_verifications_v1';
export const loadPending = (): PendingVerification[] => {
try {
const raw = localStorage.getItem(PENDING_KEY);
return raw ? (JSON.parse(raw) as PendingVerification[]) : [];
} catch {
return [];
}
};
const savePending = (items: PendingVerification[]) => {
localStorage.setItem(PENDING_KEY, JSON.stringify(items));
};
export const upsertPending = (item: PendingVerification) => {
const list = loadPending();
const next = [
item,
...list.filter(
(x) => x.username.toLowerCase() !== item.username.toLowerCase(),
),
].slice(0, 5);
savePending(next);
};
export const removePending = (username: string) => {
const list = loadPending();
savePending(
list.filter((x) => x.username.toLowerCase() !== username.toLowerCase()),
);
};
export const clearPending = () => {
localStorage.removeItem(PENDING_KEY);
};

View File

@ -1,34 +0,0 @@
import type { NotificationPosition } from '../components/Notifications/CustomNotification';
export type LauncherSettings = {
notificationPosition?: 'top-right' | 'top-center' | 'top-left' | 'bottom-right' | 'bottom-center' | 'bottom-left';
};
export function getLauncherSettings(): LauncherSettings {
try {
return JSON.parse(localStorage.getItem('launcher_settings') || '{}');
} catch {
return {};
}
}
export function getNotificationPosition(): NotificationPosition {
const { notificationPosition } = getLauncherSettings();
switch (notificationPosition) {
case 'top-right':
return { vertical: 'top', horizontal: 'right' };
case 'top-center':
return { vertical: 'top', horizontal: 'center' };
case 'top-left':
return { vertical: 'top', horizontal: 'left' };
case 'bottom-right':
return { vertical: 'bottom', horizontal: 'right' };
case 'bottom-center':
return { vertical: 'bottom', horizontal: 'center' };
case 'bottom-left':
return { vertical: 'bottom', horizontal: 'left' };
default:
return { vertical: 'bottom', horizontal: 'center' };
}
}