Chore: format

This commit is contained in:
Dorian Zedler 2022-12-30 13:28:28 +01:00
parent f3868abd08
commit 50de5ad59c
Signed by: dorian
GPG key ID: 989DE36109AFA354
3 changed files with 287 additions and 247 deletions

View file

@ -5,12 +5,11 @@
line-height: 1.2; line-height: 1.2;
} }
@keyframes blinker { @keyframes blinker {
50% { 50% {
opacity: 0.3; opacity: 0.3;
} }
} }
.timer.my-turn { .timer.my-turn {
color: #0f0; color: #0f0;

View file

@ -1,14 +1,14 @@
<!doctype html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1" />
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script> <script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script> <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script src="index.js"></script> <script src="index.js"></script>
<link rel="stylesheet" href="https://unpkg.com/@picocss/pico@latest/css/pico.min.css"> <link rel="stylesheet" href="https://unpkg.com/@picocss/pico@latest/css/pico.min.css" />
<link rel="stylesheet" href="index.css"> <link rel="stylesheet" href="index.css" />
</head> </head>
<body> <body>
@ -24,7 +24,9 @@
<div x-data="Timer"> <div x-data="Timer">
<div x-show="!time"> <div x-show="!time">
<div class="timer loading" href="#" aria-busy="true">please wait</div> <div class="timer loading" href="#" aria-busy="true">
please wait
</div>
</div> </div>
<div x-show="time"> <div x-show="time">
<p :class="'timer' + ($store.remoteState.isMyTurn ? ' my-turn':'') + (time < 0 ? ' over':'')" <p :class="'timer' + ($store.remoteState.isMyTurn ? ' my-turn':'') + (time < 0 ? ' over':'')"
@ -33,10 +35,13 @@
</div> </div>
<button @click="$store.remoteState.giveTurnToNextPlayer()" <button @click="$store.remoteState.giveTurnToNextPlayer()"
x-bind:disabled="$store.remoteState.currentPlayer !== $store.localState.id">I'm done!</button> x-bind:disabled="$store.remoteState.currentPlayer !== $store.localState.id">
I'm done!
</button>
<label for="nextPlayer_select">Player after me: <b <label for="nextPlayer_select">Player after me:
x-text="$store.remoteState.players[$store.localState.nextPlayer]"></b> </label> <b x-text="$store.remoteState.players[$store.localState.nextPlayer]"></b>
</label>
<select x-model="$store.localState.nextPlayer" id="nextPlayer_select"> <select x-model="$store.localState.nextPlayer" id="nextPlayer_select">
<template <template
x-for="playerId in Object.keys($store.remoteState.players).filter(id => id != $store.localState.id)" x-for="playerId in Object.keys($store.remoteState.players).filter(id => id != $store.localState.id)"
@ -47,14 +52,19 @@
<fieldset> <fieldset>
<label for="sound_enabled"> <label for="sound_enabled">
<input x-model="$store.audio.isEnabled" @click="$store.audio.testPermission()" type="checkbox" id="sound_enabled" name="sound_enabled" role="switch"> <input x-model="$store.audio.isEnabled" @click="$store.audio.testPermission()" type="checkbox"
id="sound_enabled" name="sound_enabled" role="switch" />
Enable sound Enable sound
</label> </label>
</fieldset> </fieldset>
<div class="grid"> <div class="grid">
<button class="secondary outline" @click="$store.localState.leave()">Leave</button> <button class="secondary outline" @click="$store.localState.leave()">
<button class="secondary outline" @click="$store.remoteState.clear()">Clear</button> Leave
</button>
<button class="secondary outline" @click="$store.remoteState.clear()">
Clear
</button>
</div> </div>
<p>Other players:</p> <p>Other players:</p>
@ -63,11 +73,10 @@
<li x-text="$store.remoteState.players[playerId]"></li> <li x-text="$store.remoteState.players[playerId]"></li>
</template> </template>
</ul> </ul>
</div> </div>
<div x-show="!$store.localState.joined"> <div x-show="!$store.localState.joined">
<form x-data="JoinForm()" @submit.prevent="submitForm"> <form x-data="JoinForm()" @submit.prevent="submitForm">
<input type="text" x-model="formData.name" placeholder="Name"> <input type="text" x-model="formData.name" placeholder="Name" />
<button type="submit">Join</button> <button type="submit">Join</button>
</form> </form>
</div> </div>

186
index.js
View file

@ -1,17 +1,20 @@
function JoinForm() { function JoinForm() {
return { return {
formData: { formData: {
name: "" name: "",
}, },
submitForm() { submitForm() {
Alpine.store("localState").join(this.formData.name) Alpine.store("localState").join(this.formData.name);
} },
} };
} }
function uuidv4() { function uuidv4() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) (
c ^
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
).toString(16)
); );
} }
@ -20,22 +23,22 @@ function Timer() {
time: 0, time: 0,
init() { init() {
setInterval(() => { setInterval(() => {
const lastPlayerSwitch = Alpine.store("remoteState").lastPlayerSwitch const lastPlayerSwitch = Alpine.store("remoteState").lastPlayerSwitch;
console.log(lastPlayerSwitch) console.log(lastPlayerSwitch);
if(!lastPlayerSwitch) { if (!lastPlayerSwitch) {
this.time = null this.time = null;
} } else {
else { this.time = parseInt(
this.time = parseInt((90000 - ((new Date()).getTime() - lastPlayerSwitch)) / 1000); (90000 - (new Date().getTime() - lastPlayerSwitch)) / 1000
);
} }
}, 100); }, 100);
}, },
} };
} }
document.addEventListener('alpine:init', () => { document.addEventListener("alpine:init", () => {
console.log("Alpine.js is ready to go!") console.log("Alpine.js is ready to go!");
Alpine.store("localState", { Alpine.store("localState", {
joined: false, joined: false,
@ -48,7 +51,7 @@ document.addEventListener('alpine:init', () => {
if (this.joined) { if (this.joined) {
Alpine.store("remoteState").connect(); Alpine.store("remoteState").connect();
} }
}) });
this.restore(); this.restore();
}, },
@ -58,16 +61,16 @@ document.addEventListener('alpine:init', () => {
this.name = name; this.name = name;
this.id = uuidv4(); this.id = uuidv4();
localStorage.clear(); localStorage.clear();
localStorage.setItem("joined", this.joined) localStorage.setItem("joined", this.joined);
localStorage.setItem("name", this.name); localStorage.setItem("name", this.name);
localStorage.setItem("id", this.id) localStorage.setItem("id", this.id);
}, },
leave() { leave() {
this.joined = false; this.joined = false;
this.name = ""; this.name = "";
localStorage.clear(); localStorage.clear();
localStorage.setItem("id", this.id) localStorage.setItem("id", this.id);
Alpine.store("remoteState").disconnect(); Alpine.store("remoteState").disconnect();
}, },
@ -79,7 +82,7 @@ document.addEventListener('alpine:init', () => {
this.id = localStorage.getItem("id"); this.id = localStorage.getItem("id");
} }
}, },
}) });
Alpine.store("remoteState", { Alpine.store("remoteState", {
players: [], players: [],
@ -91,40 +94,58 @@ document.addEventListener('alpine:init', () => {
init() { init() {
Alpine.effect(() => { Alpine.effect(() => {
if (this.connected && Object.keys(this.players).indexOf(Alpine.store("localState").id) === -1) { if (
this._client.publish('im.dorian.whos-turn-is-it.players', JSON.stringify({ this.connected &&
Object.keys(this.players).indexOf(Alpine.store("localState").id) ===
-1
) {
this._client.publish(
"im.dorian.whos-turn-is-it.players",
JSON.stringify({
[Alpine.store("localState").id]: Alpine.store("localState").name, [Alpine.store("localState").id]: Alpine.store("localState").name,
...this.players ...this.players,
}), { qos: 1, retain: true }) }),
{ qos: 1, retain: true }
);
} }
}) });
Alpine.effect(() => { Alpine.effect(() => {
if (this.currentPlayer == Alpine.store("localState").id) { if (this.currentPlayer == Alpine.store("localState").id) {
this.isMyTurn = true; this.isMyTurn = true;
} } else {
else {
this.isMyTurn = false; this.isMyTurn = false;
} }
}) });
Alpine.effect(() => { Alpine.effect(() => {
if (Alpine.store("localState").nextPlayer == null || Alpine.store("localState").nextPlayer == Alpine.store("localState").id || !Object.keys(this.players).includes(Alpine.store("localState").nextPlayer)) { if (
Alpine.store("localState").nextPlayer == null ||
Alpine.store("localState").nextPlayer ==
Alpine.store("localState").id ||
!Object.keys(this.players).includes(
Alpine.store("localState").nextPlayer
)
) {
const players = Object.keys(this.players).sort(); const players = Object.keys(this.players).sort();
const nextPlayer = players[(players.indexOf(Alpine.store("localState").id) + 1) % players.length] const nextPlayer =
players[
(players.indexOf(Alpine.store("localState").id) + 1) %
players.length
];
Alpine.store("localState").nextPlayer = nextPlayer; Alpine.store("localState").nextPlayer = nextPlayer;
} }
}) });
Alpine.effect(() => { Alpine.effect(() => {
if (this.isMyTurn) { if (this.isMyTurn) {
Alpine.store("audio").playDing() Alpine.store("audio").playDing();
} }
}) });
}, },
connect() { connect() {
const url = 'wss://broker.emqx.io:8084/mqtt' const url = "wss://broker.emqx.io:8084/mqtt";
const options = { const options = {
// Clean session // Clean session
@ -132,20 +153,19 @@ document.addEventListener('alpine:init', () => {
connectTimeout: 4000, connectTimeout: 4000,
// Authentication // Authentication
clientId: Alpine.store("localState").id, clientId: Alpine.store("localState").id,
} };
this._client = mqtt.connect(url, options) this._client = mqtt.connect(url, options);
const client = this._client; const client = this._client;
this._client.on('connect', function () { this._client.on("connect", function () {
// Subscribe to a topic // Subscribe to a topic
client.subscribe('im.dorian.whos-turn-is-it.players') client.subscribe("im.dorian.whos-turn-is-it.players");
client.subscribe('im.dorian.whos-turn-is-it.currentPlayer') client.subscribe("im.dorian.whos-turn-is-it.currentPlayer");
}) });
this._client.on("message", function (topic, message) {
this._client.on('message', function (topic, message) {
// message is Buffer // message is Buffer
console.log(topic, message.toString()) console.log(topic, message.toString());
if (topic === "im.dorian.whos-turn-is-it.players") { if (topic === "im.dorian.whos-turn-is-it.players") {
const data = JSON.parse(message.toString()); const data = JSON.parse(message.toString());
@ -153,37 +173,47 @@ document.addEventListener('alpine:init', () => {
Alpine.store("remoteState").connected = true; Alpine.store("remoteState").connected = true;
} }
Alpine.store("remoteState").players = data; Alpine.store("remoteState").players = data;
} } else if (topic === "im.dorian.whos-turn-is-it.currentPlayer") {
else if (topic === "im.dorian.whos-turn-is-it.currentPlayer") {
const data = JSON.parse(message.toString()); const data = JSON.parse(message.toString());
Alpine.store("remoteState").currentPlayer = data.id; Alpine.store("remoteState").currentPlayer = data.id;
Alpine.store("remoteState").lastPlayerSwitch = data.since; Alpine.store("remoteState").lastPlayerSwitch = data.since;
} }
}) });
}, },
giveTurnToNextPlayer() { giveTurnToNextPlayer() {
this._client.publish('im.dorian.whos-turn-is-it.currentPlayer', JSON.stringify({ this._client.publish(
"im.dorian.whos-turn-is-it.currentPlayer",
JSON.stringify({
id: Alpine.store("localState").nextPlayer, id: Alpine.store("localState").nextPlayer,
since: new Date().getTime() since: new Date().getTime(),
}), { qos: 1, retain: true }) }),
{ qos: 1, retain: true }
);
}, },
disconnect() { disconnect() {
this._client.end(true); this._client.end(true);
}, },
clear() { clear() {
this._client.publish('im.dorian.whos-turn-is-it.players', JSON.stringify({ this._client.publish(
"im.dorian.whos-turn-is-it.players",
JSON.stringify({
[Alpine.store("localState").id]: Alpine.store("localState").name, [Alpine.store("localState").id]: Alpine.store("localState").name,
}), { qos: 1, retain: true }) }),
this._client.publish('im.dorian.whos-turn-is-it.currentPlayer', JSON.stringify({ { qos: 1, retain: true }
);
this._client.publish(
"im.dorian.whos-turn-is-it.currentPlayer",
JSON.stringify({
id: Alpine.store("localState").id, id: Alpine.store("localState").id,
since: new Date().getTime() since: new Date().getTime(),
}), { qos: 1, retain: true }) }),
} { qos: 1, retain: true }
}) );
},
});
Alpine.store("audio", { Alpine.store("audio", {
hasBeenTested: false, hasBeenTested: false,
@ -192,31 +222,35 @@ document.addEventListener('alpine:init', () => {
audioPlayer: null, audioPlayer: null,
init() { init() {
this.audioPlayer = new Audio('silence.mp3'); this.audioPlayer = new Audio("silence.mp3");
Alpine.effect(() => { Alpine.effect(() => {
localStorage.setItem("audio_enabled", this.isEnabled) localStorage.setItem("audio_enabled", this.isEnabled);
}) });
}, },
testPermission() { testPermission() {
if (this.isEnabled) return; if (this.isEnabled) return;
this.audioPlayer.src = 'silence.mp3'; this.audioPlayer.src = "silence.mp3";
this.audioPlayer.play().then(() => { this.audioPlayer
this.isAvailable = true .play()
this.isEnabled = localStorage.getItem("audio_enabled") === false ? false : true .then(() => {
this.hasBeenTested = true this.isAvailable = true;
}).catch((error) => { this.isEnabled =
console.warn("Audio permission not granted!") localStorage.getItem("audio_enabled") === false ? false : true;
this.isAvailable = false this.hasBeenTested = true;
this.isEnabled = false
this.hasBeenTested = true
}) })
.catch((error) => {
console.warn("Audio permission not granted!");
this.isAvailable = false;
this.isEnabled = false;
this.hasBeenTested = true;
});
}, },
playDing() { playDing() {
if (!this.isEnabled) return; if (!this.isEnabled) return;
this.playSound('ding.mp3') this.playSound("ding.mp3");
}, },
playSound(soundFile) { playSound(soundFile) {
@ -228,7 +262,5 @@ document.addEventListener('alpine:init', () => {
} }
this.audioPlayer.play(); this.audioPlayer.play();
}, },
});
});
})
})