|
1 | | -import * as htmx from "htmx.org"; |
2 | | -import { showErrorToast } from "./modules/toast.js"; |
3 | | -import "htmx.org/dist/ext/ws.js"; |
| 1 | +import * as htmx from 'htmx.org'; |
| 2 | +import { showErrorToast } from './modules/toast.js'; |
| 3 | +import 'htmx.org/dist/ext/ws.js'; |
4 | 4 |
|
5 | 5 | // https://github.com/bigskysoftware/idiomorph#htmx |
6 | | -import "idiomorph/dist/idiomorph-ext.js"; |
| 6 | +import 'idiomorph/dist/idiomorph-ext.js'; |
7 | 7 |
|
8 | 8 | // https://htmx.org/reference/#config |
9 | | -htmx.config.requestClass = "is-loading"; |
| 9 | +htmx.config.requestClass = 'is-loading'; |
10 | 10 | htmx.config.scrollIntoViewOnBoost = false; |
11 | 11 |
|
12 | 12 | // https://htmx.org/events/#htmx:sendError |
13 | | -document.body.addEventListener("htmx:sendError", (e) => { |
| 13 | +document.body.addEventListener('htmx:sendError', (e) => { |
14 | 14 | // TODO: add translations |
15 | 15 | showErrorToast(`Network error when calling ${e.detail.requestConfig.path}`); |
16 | 16 | }); |
17 | 17 |
|
18 | 18 | // https://htmx.org/events/#htmx:responseError |
19 | | -document.body.addEventListener("htmx:responseError", (e) => { |
| 19 | +document.body.addEventListener('htmx:responseError', (e) => { |
20 | 20 | // TODO: add translations |
21 | 21 | showErrorToast( |
22 | 22 | `Error ${e.detail.xhr.status} when calling ${e.detail.requestConfig.path}` |
23 | 23 | ); |
24 | 24 | }); |
25 | 25 |
|
26 | | -// eslint-disable-next-line no-import-assign |
| 26 | +let webSocket; |
| 27 | + |
| 28 | +// TODO: move websocket creation to shared webworker |
27 | 29 | htmx.createWebSocket = (url) => { |
28 | | - // TODO: reuse websocket from shared webworker |
29 | | - const sock = new WebSocket(url, []); |
30 | | - sock.binaryType = htmx.config.wsBinaryType; |
31 | | - g; |
32 | | - return sock; |
| 30 | + if (![0, 1].includes(webSocket?.readyState)) return webSocket; |
| 31 | + const ws = new WebSocket(url, []); |
| 32 | + ws.binaryType = htmx.config.wsBinaryType; |
| 33 | + webSocket = ws; |
| 34 | + return ws; |
33 | 35 | }; |
34 | | -document.body.addEventListener("htmx:wsOpen", (e) => { |
| 36 | + |
| 37 | +document.body.addEventListener('htmx:wsOpen', (e) => { |
35 | 38 | const socket = e.detail.socketWrapper; |
36 | 39 | socket.send( |
37 | | - JSON.stringify({ action: "subscribe", data: { url: window.location.href } }) |
| 40 | + JSON.stringify({ action: 'subscribe', data: { url: window.location.href } }) |
38 | 41 | ); |
39 | 42 | }); |
0 commit comments