diff --git a/static/scripts/vendor.js b/static/scripts/vendor.js index d2f7a12..490d3ce 100644 --- a/static/scripts/vendor.js +++ b/static/scripts/vendor.js @@ -54,44 +54,58 @@ // } // } -const connectWebSocket = (url) => { - const ws = new WebSocket(url) +const syncUrl = new URL('https://cit.csasq.ru/ws/sync') - ws.onopen = () => { +const SyncDataType = { + TEXT: 0, + BOOLEAN: 1, +} - } +const enableSync = (url) => { + let ws = new WebSocket(url) + + document + .querySelectorAll('md-outlined-text-field[data-sync]') + .forEach(element => element.addEventListener('input', () => { + const data = JSON.stringify({ + id: element.id, + type: SyncDataType.TEXT, + value: element.value, + }) + ws.send(data) + })) + + document + .querySelectorAll('md-switch[data-sync]') + .forEach(element => element.addEventListener('change', () => { + const data = JSON.stringify({ + id: element.id, + type: SyncDataType.BOOLEAN, + value: !element.hasAttribute('selected'), + }) + ws.send(data) + })) ws.onmessage = (event) => { const data = JSON.parse(event.data) - document.querySelectorAll(`#${data.id}`).forEach(element => element.toggleAttribute('selected', data.value)) + const elements = document.querySelectorAll(`#${data.id}`) + + switch (data.type) { + case SyncDataType.TEXT: + elements.forEach(element => element.value = data.value) + break + + case SyncDataType.BOOLEAN: + elements.forEach(element => element.toggleAttribute('selected', data.value)) + break + } } - ws.onclose = () => { + ws.onclose = () => () => ws = new WebSocket(url) + ws.onerror = () => { + console.log('ws_error') } - - return ws } -const wsUrl = new URL(location) -wsUrl.protocol = 'wss' -wsUrl.pathname = '/ws' -const ws = connectWebSocket(wsUrl) - -function getSwitch(id) { - const element = document.createElement('md-switch') - element.id = id - element.onclick = (event) => { - event.preventDefault() - const data = JSON.stringify({ - id: id, - value: !event.currentTarget.hasAttribute('selected'), - }) - ws.send(data) - } - return element -} - -document.addEventListener('DOMContentLoaded', () => { - document.body.querySelector('main').append(getSwitch('qwerty')) -}) +document.addEventListener('DOMContentLoaded', () => enableSync(syncUrl)) diff --git a/templates/main.jinja2 b/templates/main.jinja2 index 4771643..6c1774d 100644 --- a/templates/main.jinja2 +++ b/templates/main.jinja2 @@ -41,11 +41,8 @@
- - - - - + +