aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/frontend/src/persistence/Compressor.ts
blob: 948783706eae067e924154378c2923a882cfb559 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
 * SPDX-FileCopyrightText: 2023 The Refinery Authors <https://refinery.tools/>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import getLogger from '../utils/getLogger';

import {
  type CompressRequest,
  CompressorResponse,
  type DecompressRequest,
} from './compressionMessages';
import CompressionWorker from './compressionWorker?worker';
import initialValue from './initialValue';

const LOG = getLogger('persistence.Compressor');

const FRAGMENT_PREFIX = '#/1/';

export default class Compressor {
  private readonly worker = new CompressionWorker();

  private readonly hashChangeHandler = () => this.updateHash();

  private fragment: string | undefined;

  private compressing = false;

  private toCompress: string | undefined;

  constructor(private readonly onDecompressed: (text: string) => void) {
    this.worker.onerror = (error) => LOG.error('Worker error', error);
    this.worker.onmessageerror = (error) =>
      LOG.error('Worker message error', error);
    this.worker.onmessage = (event) => {
      try {
        const message = CompressorResponse.parse(event.data);
        switch (message.response) {
          case 'compressed':
            this.fragment = `${FRAGMENT_PREFIX}${message.compressedText}`;
            this.compressionEnded();
            window.history.replaceState(null, '', this.fragment);
            break;
          case 'decompressed':
            this.onDecompressed(message.text);
            break;
          case 'error':
            this.compressionEnded();
            LOG.error('Error processing compressor request', message.message);
            break;
          default:
            LOG.error('Unknown response from compressor worker', event.data);
            break;
        }
      } catch (error) {
        LOG.error('Error processing worker message', event, error);
      }
    };
    window.addEventListener('hashchange', this.hashChangeHandler);
  }

  decompressInitial(): void {
    this.updateHash();
    if (this.fragment === undefined) {
      LOG.debug('Loading default source');
      this.onDecompressed(initialValue);
    }
  }

  compress(text: string): void {
    this.toCompress = text;
    if (this.compressing) {
      return;
    }
    this.compressing = true;
    this.worker.postMessage({
      request: 'compress',
      text,
    } satisfies CompressRequest);
  }

  dispose(): void {
    window.removeEventListener('hashchange', this.hashChangeHandler);
    this.worker.terminate();
  }

  private compressionEnded(): void {
    this.compressing = false;
    if (this.toCompress !== undefined) {
      this.compress(this.toCompress);
      this.toCompress = undefined;
    }
  }

  private updateHash(): void {
    if (
      window.location.hash !== this.fragment &&
      window.location.hash.startsWith(FRAGMENT_PREFIX)
    ) {
      this.fragment = window.location.hash;
      this.worker.postMessage({
        request: 'decompress',
        compressedText: this.fragment.substring(FRAGMENT_PREFIX.length),
      } satisfies DecompressRequest);
    }
  }
}