misskey/packages/frontend/src/stream.ts
かっこかり 837a8e15d8
refactor(frontend): frontend-embed/src/to-be-sharedを共通化 (#14536)
* refactor(frontend): shouldCollapsedを共通化

* refactor(frontend): config.js, worker-multi-dispatch.js, intl-const.jsを共通化

* fix(frontend-shared): fix type error

* refactor(frontend): is-link.jsと、同一の振る舞いをする記述を共通化

* fix

* fix lint

* lint fixes
2024-09-10 18:39:53 +09:00

52 lines
1.5 KiB
TypeScript

/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
import * as Misskey from 'misskey-js';
import { markRaw } from 'vue';
import { $i } from '@/account.js';
import { wsOrigin } from '@@/js/config.js';
// TODO: No WebsocketモードでStreamMockが使えそう
//import { StreamMock } from '@/scripts/stream-mock.js';
// heart beat interval in ms
const HEART_BEAT_INTERVAL = 1000 * 60;
let stream: Misskey.IStream | null = null;
let timeoutHeartBeat: number | null = null;
let lastHeartbeatCall = 0;
export function useStream(): Misskey.IStream {
if (stream) return stream;
// TODO: No Websocketモードもここで判定
stream = markRaw(new Misskey.Stream(wsOrigin, $i ? {
token: $i.token,
} : null));
if (timeoutHeartBeat) window.clearTimeout(timeoutHeartBeat);
timeoutHeartBeat = window.setTimeout(heartbeat, HEART_BEAT_INTERVAL);
// send heartbeat right now when last send time is over HEART_BEAT_INTERVAL
document.addEventListener('visibilitychange', () => {
if (
!stream
|| document.visibilityState !== 'visible'
|| Date.now() - lastHeartbeatCall < HEART_BEAT_INTERVAL
) return;
heartbeat();
});
return stream;
}
function heartbeat(): void {
if (stream != null && document.visibilityState === 'visible') {
stream.heartbeat();
}
lastHeartbeatCall = Date.now();
if (timeoutHeartBeat) window.clearTimeout(timeoutHeartBeat);
timeoutHeartBeat = window.setTimeout(heartbeat, HEART_BEAT_INTERVAL);
}