Skip to content

Commit

Permalink
Merge branch 'next'
Browse files Browse the repository at this point in the history
  • Loading branch information
zardoy committed Feb 15, 2024
2 parents f4d5a46 + a37cc77 commit f61ed17
Show file tree
Hide file tree
Showing 12 changed files with 109 additions and 105 deletions.
41 changes: 40 additions & 1 deletion src/browserfs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import * as browserfs from 'browserfs'
import { options, resetOptions } from './optionsStorage'

import { fsState, loadSave } from './loadSave'
import { installTexturePackFromHandle, updateTexturePackInstalledState } from './texturePack'
import { installTexturePack, installTexturePackFromHandle, updateTexturePackInstalledState } from './texturePack'
import { miscUiState } from './globalState'
import { setLoadingScreenStatus } from './utils'

Expand Down Expand Up @@ -422,3 +422,42 @@ export const resetLocalStorageWithoutWorld = () => {
}

window.resetLocalStorageWorld = resetLocalStorageWorld
export const openFilePicker = (specificCase?: 'resourcepack') => {
// create and show input picker
let picker: HTMLInputElement = document.body.querySelector('input#file-zip-picker')!
if (!picker) {
picker = document.createElement('input')
picker.type = 'file'
picker.accept = '.zip'

picker.addEventListener('change', () => {
const file = picker.files?.[0]
picker.value = ''
if (!file) return
if (!file.name.endsWith('.zip')) {
const doContinue = confirm(`Are you sure ${file.name.slice(-20)} is .zip file? Only .zip files are supported. Continue?`)
if (!doContinue) return
}
if (specificCase === 'resourcepack') {
void installTexturePack(file)
} else {
void openWorldZip(file)
}
})
picker.hidden = true
document.body.appendChild(picker)
}

picker.click()
}

export const resetStateAfterDisconnect = () => {
miscUiState.gameLoaded = false
miscUiState.loadedDataVersion = null
miscUiState.singleplayer = false
miscUiState.flyingSquid = false
miscUiState.wanOpened = false
miscUiState.currentDisplayQr = null

fsState.saveLoaded = false
}
3 changes: 3 additions & 0 deletions src/devtools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@ window.cursorBlockRel = (x = 0, y = 0, z = 0) => {
window.cursorEntity = () => {
return getEntityCursor()
}

// wanderer
window.inspectPlayer = () => require('fs').promises.readFile('/world/playerdata/9e487d23-2ffc-365a-b1f8-f38203f59233.dat').then(window.nbt.parse).then(console.log)
9 changes: 9 additions & 0 deletions src/flyingSquidUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,12 @@ export const saveServer = async (autoSave = true) => {
const worlds = [(localServer as any).overworld] as Array<import('prismarine-world').world.World>
await Promise.all([savePlayers(autoSave), ...worlds.map(async world => world.saveNow())])
}
export const disconnect = async () => {
if (localServer) {
await saveServer()
//@ts-expect-error todo expose!
void localServer.quit() // todo investigate we should await
}
window.history.replaceState({}, '', `${window.location.pathname}`) // remove qs
bot.end('You left the server')
}
35 changes: 35 additions & 0 deletions src/globalDomListeners.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { saveServer } from './flyingSquidUtils'
import { isGameActive, activeModalStack } from './globalState'
import { options } from './optionsStorage'

window.addEventListener('unload', (e) => {
if (!window.justReloaded) {
sessionStorage.justReloaded = false
}
void saveServer()
})

document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') void saveServer()
})
document.addEventListener('blur', () => {
void saveServer()
})

window.addEventListener('beforeunload', (event) => {
if (!window.justReloaded) {
sessionStorage.justReloaded = false
}

// todo-low maybe exclude chat?
if (!isGameActive(true) && activeModalStack.at(-1)?.elem?.id !== 'chat') return
if (sessionStorage.lastReload && !options.preventDevReloadWhilePlaying) return
if (!options.closeConfirmation) return

// For major browsers doning only this is enough
event.preventDefault()

// Display a confirmation prompt
event.returnValue = '' // Required for some browsers
return 'The game is running. Are you sure you want to close this page?'
})
49 changes: 0 additions & 49 deletions src/globalState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@

import { proxy, ref, subscribe } from 'valtio'
import { pointerLock } from './utils'
import { options } from './optionsStorage'
import type { OptionsGroupType } from './optionsGuiScheme'
import { saveServer } from './flyingSquidUtils'
import { fsState } from './loadSave'

// todo: refactor structure with support of hideNext=false

Expand Down Expand Up @@ -145,17 +142,6 @@ export const miscUiState = proxy({
displaySearchInput: false,
})

export const resetStateAfterDisconnect = () => {
miscUiState.gameLoaded = false
miscUiState.loadedDataVersion = null
miscUiState.singleplayer = false
miscUiState.flyingSquid = false
miscUiState.wanOpened = false
miscUiState.currentDisplayQr = null

fsState.saveLoaded = false
}

export const isGameActive = (foregroundCheck: boolean) => {
if (foregroundCheck && activeModalStack.length) return false
return miscUiState.gameLoaded
Expand Down Expand Up @@ -186,38 +172,3 @@ export const showNotification = (newNotification: Partial<typeof notification>)
}

// todo restore auto-save on interval for player data! (or implement it in flying squid since there is already auto-save for world)

window.addEventListener('unload', (e) => {
if (!window.justReloaded) {
sessionStorage.justReloaded = false
}
void saveServer()
})

document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') void saveServer()
})
document.addEventListener('blur', () => {
void saveServer()
})

window.inspectPlayer = () => require('fs').promises.readFile('/world/playerdata/9e487d23-2ffc-365a-b1f8-f38203f59233.dat').then(window.nbt.parse).then(console.log)

// todo move from global state
window.addEventListener('beforeunload', (event) => {
if (!window.justReloaded) {
sessionStorage.justReloaded = false
}

// todo-low maybe exclude chat?
if (!isGameActive(true) && activeModalStack.at(-1)?.elem?.id !== 'chat') return
if (sessionStorage.lastReload && !options.preventDevReloadWhilePlaying) return
if (!options.closeConfirmation) return

// For major browsers doning only this is enough
event.preventDefault()

// Display a confirmation prompt
event.returnValue = '' // Required for some browsers
return 'The game is running. Are you sure you want to close this page?'
})
6 changes: 4 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import './globals'
import 'iconify-icon'
import './devtools'
import './entities'
import './globalDomListeners'
import initCollisionShapes from './getCollisionShapes'
import { onGameLoad } from './playerWindows'
import { supportedVersions } from 'minecraft-protocol'
Expand All @@ -29,7 +30,7 @@ import { options, watchValue } from './optionsStorage'
import './reactUi.jsx'
import { contro, onBotCreate } from './controls'
import './dragndrop'
import { possiblyCleanHandle } from './browserfs'
import { possiblyCleanHandle, resetStateAfterDisconnect } from './browserfs'
import './eruda'
import { watchOptionsAfterViewerInit } from './watchOptions'
import downloadAndOpenFile from './downloadAndOpenFile'
Expand All @@ -54,10 +55,11 @@ import {
showModal, activeModalStacks,
insertActiveModalStack,
isGameActive,
miscUiState, resetStateAfterDisconnect,
miscUiState,
notification
} from './globalState'


import {
pointerLock,
toMajorVersion,
Expand Down
8 changes: 4 additions & 4 deletions src/loadSave.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import * as nbt from 'prismarine-nbt'
import { proxy } from 'valtio'
import { gzip } from 'node-gzip'
import { options } from './optionsStorage'
import { nameToMcOfflineUUID } from './flyingSquidUtils'
import { nameToMcOfflineUUID, disconnect } from './flyingSquidUtils'
import { forceCachedDataPaths } from './browserfs'
import { disconnect, isMajorVersionGreater } from './utils'
import { activeModalStack, activeModalStacks, hideModal, insertActiveModalStack, miscUiState } from './globalState'
import { appStatusState } from './react/AppStatusProvider'
import { isMajorVersionGreater } from './utils'

import { activeModalStacks, insertActiveModalStack, miscUiState } from './globalState'

// todo include name of opened handle (zip)!
// additional fs metadata
Expand Down
5 changes: 3 additions & 2 deletions src/optionsGuiScheme.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import { AppOptions, options } from './optionsStorage'
import Button from './react/Button'
import { OptionMeta, OptionSlider } from './react/OptionsItems'
import Slider from './react/Slider'
import { getScreenRefreshRate, openFilePicker, setLoadingScreenStatus } from './utils'
import { getScreenRefreshRate, setLoadingScreenStatus } from './utils'
import { openFilePicker, resetLocalStorageWithoutWorld } from './browserfs'
import { getResourcePackName, resourcePackState, uninstallTexturePack } from './texturePack'
import { resetLocalStorageWithoutWorld } from './browserfs'


export const guiOptionsScheme: {
[t in OptionsGroupType]: Array<{ [K in keyof AppOptions]?: Partial<OptionMeta<AppOptions[K]>> } & { custom?}>
Expand Down
4 changes: 2 additions & 2 deletions src/react/DeathScreenProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { useEffect } from 'react'
import { proxy, useSnapshot } from 'valtio'
import { disconnect } from '../utils'
import { disconnect } from '../flyingSquidUtils'
import { MessageFormatPart, formatMessage } from '../botUtils'
import { showModal, hideModal, activeModalStack } from '../globalState'
import { showModal, hideModal } from '../globalState'
import { options } from '../optionsStorage'
import DeathScreen from './DeathScreen'
import { useIsModalActive } from './utils'
Expand Down
5 changes: 3 additions & 2 deletions src/react/MainMenuRenderApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import { useSnapshot } from 'valtio'
import { useEffect } from 'react'
import { activeModalStack, miscUiState, openOptionsMenu, showModal } from '../globalState'
import { openURL } from '../menus/components/common'
import { openFilePicker, openGithub, setLoadingScreenStatus } from '../utils'
import { copyFilesAsync, mkdirRecursive, openWorldDirectory, removeFileRecursiveAsync } from '../browserfs'
import { openGithub, setLoadingScreenStatus } from '../utils'
import { openFilePicker, copyFilesAsync, mkdirRecursive, openWorldDirectory, removeFileRecursiveAsync } from '../browserfs'

import MainMenu from './MainMenu'

// todo clean
Expand Down
6 changes: 6 additions & 0 deletions src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,12 @@ body {
color: #999;
}

@media screen and (min-width: 430px) {
.span-2 {
grid-column: span 2;
}
}

@keyframes dive-animation {
0% {
transform: translateZ(-150px);
Expand Down
43 changes: 0 additions & 43 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { hideModal, isGameActive, miscUiState, notification, showModal } from './globalState'
import { options } from './optionsStorage'
import { openWorldZip } from './browserfs'
import { installTexturePack } from './texturePack'
import { appStatusState } from './react/AppStatusProvider'
import { saveServer } from './flyingSquidUtils'

export const goFullscreen = async (doToggle = false) => {
if (!document.fullscreenElement) {
Expand Down Expand Up @@ -147,17 +144,6 @@ export const setLoadingScreenStatus = function (status: string | undefined | nul
appStatusState.status = status
}


export const disconnect = async () => {
if (localServer) {
await saveServer()
//@ts-expect-error todo expose!
void localServer.quit() // todo investigate we should await
}
window.history.replaceState({}, '', `${window.location.pathname}`) // remove qs
bot.end('You left the server')
}

// doesn't support snapshots
export const toMajorVersion = (version) => {
const [a, b] = (String(version)).split('.')
Expand All @@ -181,35 +167,6 @@ export const reloadChunks = async () => {
await worldView.updatePosition(bot.entity.position, true)
}

export const openFilePicker = (specificCase?: 'resourcepack') => {
// create and show input picker
let picker: HTMLInputElement = document.body.querySelector('input#file-zip-picker')!
if (!picker) {
picker = document.createElement('input')
picker.type = 'file'
picker.accept = '.zip'

picker.addEventListener('change', () => {
const file = picker.files?.[0]
picker.value = ''
if (!file) return
if (!file.name.endsWith('.zip')) {
const doContinue = confirm(`Are you sure ${file.name.slice(-20)} is .zip file? Only .zip files are supported. Continue?`)
if (!doContinue) return
}
if (specificCase === 'resourcepack') {
void installTexturePack(file)
} else {
void openWorldZip(file)
}
})
picker.hidden = true
document.body.appendChild(picker)
}

picker.click()
}

export const openGithub = () => {
window.open(process.env.GITHUB_URL, '_blank')
}
Expand Down

0 comments on commit f61ed17

Please sign in to comment.