|
1 | 1 | import type { ImageElement } from './utils' |
2 | | -import { GM_registerMenuCommand, GM_setClipboard } from '$' |
| 2 | +import { GM_download, GM_registerMenuCommand, GM_setClipboard } from '$' |
3 | 3 | import { Notify } from 'notiflix/build/notiflix-notify-aio' |
| 4 | +import QRCode from 'qrcode' |
4 | 5 | import Swal from 'sweetalert' |
5 | 6 | import { ID, VERSION } from 'virtual:meta' |
| 7 | + |
6 | 8 | import { decodeQrCode, isUrl } from './utils' |
7 | 9 |
|
8 | 10 | console.log(`${ID}(v${VERSION})`) |
9 | 11 |
|
10 | 12 | let image: ImageElement | null = null |
| 13 | +let selection: string | null = null |
11 | 14 |
|
12 | | -GM_registerMenuCommand('Decode QR Code', () => { |
| 15 | +function handleDecodeQrCodeMenuClick() { |
13 | 16 | if (!image) { |
14 | 17 | return Notify.warning('未选择图片, 请先右键选择图片') |
15 | 18 | } |
@@ -87,10 +90,46 @@ GM_registerMenuCommand('Decode QR Code', () => { |
87 | 90 | Notify.failure('识别失败, 请检查图片是否有效') |
88 | 91 | console.error(error) |
89 | 92 | }).finally(() => (image = null)) |
90 | | -}) |
| 93 | +} |
| 94 | + |
| 95 | +async function handleEncodeQrCodeMenuClick() { |
| 96 | + if (selection === null) { |
| 97 | + return Notify.warning('未选择文字, 请先右键选择文字') |
| 98 | + } |
| 99 | + |
| 100 | + const dataUrl = await QRCode.toDataURL(selection) |
| 101 | + const element = document.createElement('img') |
| 102 | + element.src = dataUrl |
| 103 | + element.style.margin = '0 auto' |
| 104 | + |
| 105 | + Swal({ |
| 106 | + icon: 'success', |
| 107 | + title: '生成二维码成功', |
| 108 | + content: { |
| 109 | + element, |
| 110 | + }, |
| 111 | + buttons: { |
| 112 | + confirm: { |
| 113 | + text: '保存到本地', |
| 114 | + value: 'save', |
| 115 | + }, |
| 116 | + }, |
| 117 | + }).then((result) => { |
| 118 | + if (result === 'save') { |
| 119 | + GM_download({ name: 'qrcode.png', url: dataUrl, saveAs: true }) |
| 120 | + } |
| 121 | + }).finally(() => (selection = null)) |
| 122 | +} |
| 123 | + |
| 124 | +GM_registerMenuCommand('Decode QR Code', handleDecodeQrCodeMenuClick) |
| 125 | +GM_registerMenuCommand('Encode QR Code', handleEncodeQrCodeMenuClick) |
91 | 126 |
|
92 | 127 | document.addEventListener('contextmenu', (event) => { |
93 | 128 | if (event.target instanceof HTMLImageElement || event.target instanceof HTMLCanvasElement) { |
94 | 129 | image = event.target |
95 | 130 | } |
96 | 131 | }) |
| 132 | + |
| 133 | +document.addEventListener('selectionchange', () => { |
| 134 | + selection = document.getSelection()?.toString() || null |
| 135 | +}) |
0 commit comments