aboutsummaryrefslogtreecommitdiff
path: root/src/tools/qr-code-generator/useQRCode.ts
blob: 44b72a728120b8f58ec431503bddd809cf170662 (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
import { get, type MaybeRef } from '@vueuse/core';
import QRCode, { type QRCodeErrorCorrectionLevel, type QRCodeToDataURLOptions } from 'qrcode';
import { ref, watch, isRef } from 'vue';

export function useQRCode({
  text,
  color: { background, foreground },
  errorCorrectionLevel,
  options,
}: {
  text: MaybeRef<string>;
  color: { foreground: MaybeRef<string>; background: MaybeRef<string> };
  errorCorrectionLevel?: MaybeRef<QRCodeErrorCorrectionLevel>;
  options?: QRCodeToDataURLOptions;
}) {
  const qrcode = ref('');

  watch(
    [text, background, foreground, errorCorrectionLevel].filter(isRef),
    async () => {
      if (get(text))
        qrcode.value = await QRCode.toDataURL(get(text), {
          color: {
            dark: get(foreground),
            light: get(background),
            ...options?.color,
          },
          errorCorrectionLevel: get(errorCorrectionLevel) ?? 'M',
          ...options,
        });
    },
    { immediate: true },
  );

  return { qrcode };
}