Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Гиззатуллин Урал #35

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import timeout from "./timeout.mjs";
import drawer from "./drawer.mjs";
import picker from "./picker.mjs";

document.querySelector("#start").addEventListener("submit", e => {
e.preventDefault();
main(new FormData(e.currentTarget).get("apiKey"));
document.querySelector(".container").classList.add("ready");
});


/* --4-- */
const onFieldRecieved = (message) =>{
const result = JSON.parse(message?.['data']);

if (result['type'] == 'place')
drawer.putArray(result['payload']['place']);
}


const main = apiKey => {
const ws = connect(apiKey);
ws.addEventListener("message", onFieldRecieved);

timeout.next = new Date();
drawer.onClick = (x, y) => {
drawer.put(x, y, picker.color);
//отправляем на сервер
/* --5-- */
ws.send(JSON.stringify({
type: "click",
payload: {x: x, y: y, color: picker.color}
}));
};
};

const connect = apiKey => {
const url = `${location.origin.replace(/^http/, "ws")}?apiKey=${apiKey}`;
return new WebSocket(url);
};
65 changes: 65 additions & 0 deletions picker.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const setAttributes = (element, object) => {
for (const [key, value] of Object.entries(object)) {
element.setAttribute(key, value);
}
};

const drawPalette = async () => {
const reply = await fetch("/api/getColors");
const colors = await reply.json();

pickedColor = colors[0];
/* --1-- */
const palette = document.querySelector("#palette");
const fragment = document.createDocumentFragment();

for (const color of colors) {
const label = document.createElement("label");
label.setAttribute("class", "palette__color");
const input = document.createElement("input");
setAttributes(input, {
class: "palette__checkbox",
type: "radio",
name: "color",
value: color
});
if (color === pickedColor) {
input.setAttribute("checked", "");
}
input.addEventListener("input", e => {
pickedColor = e.target.value;
});
const span = document.createElement("span");
setAttributes(span, {
class: "palette__name",
style: `background-color: ${color}`
});
label.appendChild(input);
label.appendChild(span);
fragment.appendChild(label);
}
palette.appendChild(fragment);
};

const hardcodedColors = [
"#140c1c",
"#30346d",
"#854c30",
"#d04648",
"#597dce",
"#8595a1",
"#d2aa99",
"#dad45e",
];

let pickedColor = null;

drawPalette().catch(console.error);

const picker = {
get color() {
return pickedColor;
}
};

export default picker;
62 changes: 62 additions & 0 deletions server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const apiKeys = new Set([
"4a226908-aa3e-4a34-a57d-1f3d1f6cba84",
]);


const colors = [
"#140c1c",
"#442434",
Expand Down Expand Up @@ -43,6 +44,11 @@ const app = express();

app.use(express.static(path.join(process.cwd(), "client")));

/* --1-- */
app.get("/api/getColors", (_, res) => {
res.json(colors);
});

app.get("/*", (_, res) => {
res.send("Place(holder)");
});
Expand All @@ -60,3 +66,59 @@ server.on("upgrade", (req, socket, head) => {
wss.emit("connection", ws, req);
});
});

/* --2-- */
/* --10-- */
server.on("upgrade", (req, socket, head) => {
const url = new URL(req.url, req.headers.origin);
const userApiKey = url.searchParams.get('apiKey');
if (!apiKeys.has(userApiKey)) {
req.destroy(new Error('Incorrect API key'));
return;
}

wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit('connection', ws, req);
});
});


/* --7-- */
const insertIntoPlace = (payload) => {
place[size * payload.y + payload.x] = payload.color;

wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
sendField(client);
}
});
}

const sendField = (ws) => {
const result = {
type: "place", // тип сообщения
payload: {
place: place,
}
}

ws.send(JSON.stringify(result));
}

/* --3-- */
/* --8-- */
wss.on('connection', function connection(ws) {
ws.on('message', function message(data) {
//перехватываем на сервере
const parsedData = JSON.parse(data);
console.log('received: %s', parsedData);
/* --6-- */
switch (parsedData['type']) {
case ("click"):
insertIntoPlace(parsedData['payload'])
}
});

sendField(ws);
});