Skip to content

Commit 870848a

Browse files
committed
Adapt for webview
1 parent 3051988 commit 870848a

File tree

8 files changed

+108
-36
lines changed

8 files changed

+108
-36
lines changed

badges.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1191,7 +1191,7 @@ function updateBadges(callback) {
11911191
.then(badges => {
11921192
for (const { badgeId, newUnlock } of badges)
11931193
if (newUnlock) {
1194-
newUnlockBadges.add(newUnlock);
1194+
newUnlockBadges.add(badgeId);
11951195
showBadgeToastMessage('badgeUnlocked', 'info', badgeId);
11961196
}
11971197
badgeCache = badges;

gamecanvas.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ document.getElementById('controls-fullscreen').addEventListener('click', () => {
4545

4646
{
4747
const layout = document.getElementById('layout');
48-
if (!(layout.requestFullscreen || layout.webkitRequestFullscreen)) {
48+
if (!(layout.requestFullscreen || layout.webkitRequestFullscreen) || inWebview) {
4949
document.getElementById('controls-fullscreen').classList.add('hidden');
5050
}
5151
}

init.js

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,10 @@ const tippyConfig = {
4343
touch: /** @type {['hold', number]} */(['hold', 400]),
4444
};
4545

46+
const inWebview = '__webview__' in window;
47+
if (inWebview)
48+
document.documentElement.setAttribute('webview', '');
49+
4650
Object.defineProperty(Object.prototype, 'hasTitle', {
4751
enumerable: false,
4852
value() {
@@ -73,7 +77,9 @@ let initBlocker = Promise.resolve();
7377
async function injectScripts() {
7478
const supportsSimd = await wasmFeatureDetect.simd();
7579

76-
let scripts = [ 'chat.js', 'playerlist.js', 'friends.js', 'parties.js', 'system.js', 'preloads.js', 'locations.js', 'schedules.js', 'report.js', 'notifications.js', '2kki.js', 'play.js', 'gamecanvas.js', `ynoengine${supportsSimd ? '-simd' : ''}.js` ];
80+
let scripts = [ 'chat.js', 'playerlist.js', 'friends.js', 'parties.js', 'system.js', 'preloads.js', 'locations.js', 'schedules.js', 'report.js', 'notifications.js', '2kki.js', 'play.js', 'gamecanvas.js' ];
81+
if (!inWebview)
82+
scripts.push(`ynoengine${supportsSimd ? '-simd' : ''}.js`);
7783

7884
dependencyFiles['play.css'] = null;
7985

@@ -98,12 +104,18 @@ async function injectScripts() {
98104
if (gameId === '2kki') {
99105
gameVersion = document.querySelector('meta[name="2kkiVersion"]')?.content?.replace(' Patch ', 'p');
100106
}
107+
108+
if (inWebview && !getCookie(sessionIdKey)) {
109+
setCookie(sessionIdKey, await webviewSessionToken());
110+
}
101111

102112
easyrpgPlayerLoadFuncs.push(() => {
103-
easyrpgPlayer.initialized = true;
104-
easyrpgPlayer.api.setNametagMode(config.nametagMode);
105-
easyrpgPlayer.api.setSoundVolume(globalConfig.soundVolume);
106-
easyrpgPlayer.api.setMusicVolume(globalConfig.musicVolume);
113+
if (!inWebview) {
114+
easyrpgPlayer.initialized = true;
115+
easyrpgPlayer.api.setNametagMode(config.nametagMode);
116+
easyrpgPlayer.api.setSoundVolume(globalConfig.soundVolume);
117+
easyrpgPlayer.api.setMusicVolume(globalConfig.musicVolume);
118+
}
107119
const loadingOverlay = document.getElementById('loadingOverlay');
108120
removeLoader(loadingOverlay);
109121
checkShowVersionUpdate().then(() => loadingOverlay.classList.add('loaded'));
@@ -114,14 +126,19 @@ async function injectScripts() {
114126
setInterval(checkDependenciesModified, 300000);
115127
}, 10000);
116128
window.onbeforeunload = function () {
117-
return localizedMessages.leavePage;
129+
if (!inWebview)
130+
return localizedMessages.leavePage;
118131
};
119132
});
120133
if (typeof onResize !== 'undefined')
121134
easyrpgPlayerLoadFuncs.push(onResize);
122135

123136
await initBlocker;
124137

138+
if (inWebview)
139+
for (let loadFunc of easyrpgPlayerLoadFuncs)
140+
loadFunc();
141+
else
125142
createEasyRpgPlayer(easyrpgPlayer)
126143
.then(function(Module) {
127144
// Module is ready
@@ -816,7 +833,7 @@ function loadOrInitConfig(configObj, global, configName) {
816833
case 'rulesReviewed':
817834
break;
818835
}
819-
} else {
836+
} else { // !global
820837
switch (key) {
821838
case 'privateMode':
822839
if (value)

play.css

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -775,6 +775,10 @@ body.fullBg #background {
775775
margin: 0 -8px;
776776
}
777777

778+
html[webview] #bottom {
779+
display: none;
780+
}
781+
778782
#header, #layout {
779783
display: flex;
780784
margin: 0 auto;
@@ -937,6 +941,10 @@ body.fullBg #background {
937941
z-index: 2;
938942
}
939943

944+
html[webview] #mainContainer {
945+
min-height: 28px;
946+
}
947+
940948
/* Fix for a fullscreen bug that shifts the game canvas when focus is changed */
941949
#layout:fullscreen #mainContainer {
942950
padding-top: 0px;
@@ -1032,6 +1040,10 @@ body.fullBg #background {
10321040
height: 100%;
10331041
}
10341042

1043+
html[webview] #canvasContainer {
1044+
display: none;
1045+
}
1046+
10351047
#canvas {
10361048
display: block;
10371049
top: 0;
@@ -3332,17 +3344,31 @@ form .uiTheme {
33323344
border-inline-start: 24px solid transparent;
33333345
}
33343346

3347+
html[webview] #chatboxContainer {
3348+
height: calc(100vh - 370px);
3349+
max-height: unset;
3350+
}
3351+
33353352
#chatbox {
33363353
height: calc(100vh - 590px);
33373354
min-height: 200px;
33383355
max-height: 340px;
33393356
}
33403357

3358+
html[webview] #chatbox {
3359+
height: calc(100vh - 362px);
3360+
max-height: unset;
3361+
}
3362+
33413363
#content.downscale #chatboxContainer {
33423364
width: 100%;
33433365
height: calc(100vh - 474px);
33443366
}
33453367

3368+
html[webview] #content.downscale #chatboxContainer {
3369+
height: unset;
3370+
}
3371+
33463372
#content.loggedIn.downscale #layout.explorer:not(:fullscreen) #chatboxContainer {
33473373
height: calc(100vh - (464px - max(min(100vh - 512px, 284px), 150px)));
33483374
max-height: 640px;
@@ -3362,7 +3388,7 @@ form .uiTheme {
33623388
height: unset;
33633389
}
33643390

3365-
#content.downscale #chatbox {
3391+
html:not[webview] #content.downscale #chatbox {
33663392
height: calc(100vh - 470px);
33673393
}
33683394

play.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,8 @@ function fetchAndUpdatePlayerInfo() {
210210
const isLogout = !cookieSessionId && loginToken && cookieSessionId !== loginToken;
211211
if (isLogin || isLogout) {
212212
loginToken = isLogin ? cookieSessionId : null;
213-
easyrpgPlayer.api.setSessionToken(isLogin ? loginToken : '');
213+
if (!inWebview)
214+
easyrpgPlayer.api.setSessionToken(isLogin ? loginToken : '');
214215
playerTooltipCache.clear();
215216
}
216217
navigator.serviceWorker?.getRegistration('/').then(registration => {
@@ -533,6 +534,8 @@ function syncLocationChange() {
533534
const locationNames = cachedLocations ? cachedLocations.map(l => get2kkiWikiLocationName(l)) : [];
534535

535536
sendSessionCommand('l', locationNames);
537+
if (window.webviewSetLocation)
538+
window.webviewSetLocation(locationNames.join(' | '));
536539
}
537540

538541
// EXTERNAL

session.js

Lines changed: 40 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ let sessionCommandCallbackQueue = {};
77
let hasConnected;
88

99
function initSessionWs(attempt) {
10+
if (inWebview) {
11+
postInitSession();
12+
return Promise.resolve();
13+
}
1014
return new Promise(resolve => {
1115
if (sessionWs)
1216
closeSessionWs();
@@ -33,34 +37,46 @@ function initSessionWs(attempt) {
3337
setTimeout(() => initSessionWs(1), 5000);
3438
};
3539
easyrpgPlayer.api.sessionReady();
36-
if (config.privateMode)
37-
sendSessionCommand('pr', [ 1 ]);
38-
if (config.hideLocation)
39-
sendSessionCommand('hl', [ 1 ]);
40-
if (!hasConnected) {
41-
syncChatHistory()
42-
.catch(err => console.error(err))
43-
.finally(addChatTip);
44-
hasConnected = true;
45-
} else
46-
syncChatHistory()
47-
.catch(err => console.error(err));
40+
postInitSession();
4841
resolve();
4942
};
5043
sessionWs.onmessage = event => {
5144
const args = event.data.split(wsDelim);
5245
const command = args[0];
53-
if (command in sessionCommandHandlers) {
54-
const params = args.slice(1);
55-
if (sessionCommandHandlers[command])
56-
sessionCommandHandlers[command](params);
57-
while (sessionCommandCallbackQueue[command].length)
58-
sessionCommandCallbackQueue[command].shift()(params);
59-
}
46+
receiveSessionMessage(command, args);
6047
};
6148
});
6249
}
6350

51+
function postInitSession() {
52+
if (config.privateMode)
53+
sendSessionCommand('pr', [ 1 ]);
54+
if (config.hideLocation)
55+
sendSessionCommand('hl', [ 1 ]);
56+
if (!hasConnected) {
57+
syncChatHistory()
58+
.catch(err => console.error(err))
59+
.finally(addChatTip);
60+
hasConnected = true;
61+
} else
62+
syncChatHistory()
63+
.catch(err => console.error(err));
64+
}
65+
66+
function receiveSessionMessage(command, args) {
67+
if (command in sessionCommandHandlers) {
68+
let params;
69+
if (!Array.isArray(args))
70+
params = args.split(wsDelim);
71+
else
72+
params = args.slice(1);
73+
if (sessionCommandHandlers[command])
74+
sessionCommandHandlers[command](params);
75+
while (sessionCommandCallbackQueue[command].length)
76+
sessionCommandCallbackQueue[command].shift()(params);
77+
}
78+
}
79+
6480
function closeSessionWs() {
6581
if (!sessionWs)
6682
return;
@@ -75,7 +91,7 @@ function addSessionCommandHandler(command, handler) {
7591
}
7692

7793
function sendSessionCommand(command, commandParams, callbackFunc, callbackCommand) {
78-
if (!sessionWs)
94+
if (!sessionWs && !inWebview)
7995
return;
8096

8197
let args = [ command ];
@@ -88,6 +104,8 @@ function sendSessionCommand(command, commandParams, callbackFunc, callbackComman
88104
if (sessionCommandCallbackQueue.hasOwnProperty(callbackCommand))
89105
sessionCommandCallbackQueue[callbackCommand].push(callbackFunc);
90106
}
91-
92-
sessionWs.send(args.join(wsDelim));
107+
if (inWebview)
108+
webviewSendSession(args.join(wsDelim));
109+
else
110+
sessionWs.send(args.join(wsDelim));
93111
}

types.d.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,8 @@ declare class FastdomPromised {
3737
mutate<T extends () => void>(task: T, context?: any): Promise<Awaited<ReturnType<T>>>;
3838
}
3939

40-
declare const fastdom: FastdomPromised;
40+
declare const fastdom: FastdomPromised;
41+
42+
/** only available with `isWebview` */
43+
declare function webviewSendSession(data: string): void;
44+
declare function webviewSessionToken(): Promise<string>;

vendor/fastdom.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,14 @@ var debug = 0 ? console.log.bind(console, '[fastdom]') : function() {};
2525
*
2626
* @type {Function}
2727
*/
28-
var raf = win.requestAnimationFrame
28+
var rafBase = win.requestAnimationFrame
2929
|| win.webkitRequestAnimationFrame
3030
|| win.mozRequestAnimationFrame
3131
|| win.msRequestAnimationFrame
3232
|| function(cb) { return setTimeout(cb, 16); };
3333

34+
const raf = task => document.hidden ? setTimeout(task, 16) : rafBase(task);
35+
3436
/**
3537
* Initialize a `FastDom`.
3638
*
@@ -57,7 +59,9 @@ FastDom.prototype = {
5759
*/
5860
runTasks: function(tasks) {
5961
debug('run tasks');
60-
var task; while (task = tasks.shift()) task();
62+
for (let i = 0; i < tasks.length; ++i)
63+
tasks[i]();
64+
tasks.length = 0;
6165
},
6266

6367
/**

0 commit comments

Comments
 (0)