115 lines
2.1 KiB
TypeScript
115 lines
2.1 KiB
TypeScript
|
|
import { toString, QRCodeRenderersOptions } from 'qrcode';
|
|
|
|
type Colors = QRCodeRenderersOptions['color'];
|
|
|
|
export interface WifiInfo {
|
|
ssid: string;
|
|
password: string;
|
|
hidden: boolean;
|
|
encryption: 'WPA' | 'WEP' | 'None';
|
|
}
|
|
|
|
export interface MeCardInfo {
|
|
adr?: string;
|
|
bday?: string;
|
|
email?: string;
|
|
n?: string;
|
|
nickname?: string;
|
|
note?: string;
|
|
sound?: string;
|
|
tel?: string;
|
|
tel_av?: string;
|
|
url?: string;
|
|
}
|
|
|
|
// todo: css variables
|
|
export async function generate_qr_code(data: string, colors?: Colors) {
|
|
colors = colors || {
|
|
dark: 'var(--theme-text-heading, currentcolor)',
|
|
light: 'var(--theme-bg-main, transparent)'
|
|
};
|
|
|
|
const svg = await toString(data, {
|
|
type: 'svg',
|
|
color: {
|
|
dark: '#000000',
|
|
light: '#ffffff'
|
|
}
|
|
});
|
|
|
|
const colored_svg = svg.replace(/#000000/g, colors.dark).replace(/#ffffff/g, colors.light).trim();
|
|
|
|
return colored_svg.replace(/^<svg /, '<svg class="qrcode" ')
|
|
}
|
|
|
|
export function generate_wifi_qr_code(info: WifiInfo, colors?: Colors) {
|
|
const ssid = escape(info.ssid);
|
|
const password = escape(info.password);
|
|
|
|
let data = `WIFI:S:${ssid};P:${password};H:${info.hidden};`
|
|
|
|
if (info.encryption) {
|
|
data += `T:${info.encryption};`;
|
|
}
|
|
|
|
return generate_qr_code(data, colors);
|
|
}
|
|
|
|
export function generate_mecard_qr_code(info: MeCardInfo, colors?: Colors) {
|
|
let data = 'MECARD:';
|
|
|
|
if (info.adr) {
|
|
data += `ADR:${escape(info.adr)};`;
|
|
}
|
|
|
|
if (info.bday) {
|
|
data += `BDAY:${escape(info.bday)};`;
|
|
}
|
|
|
|
if (info.email) {
|
|
data += `EMAIL:${escape(info.email)};`;
|
|
}
|
|
|
|
if (info.n) {
|
|
data += `N:${escape(info.n)};`;
|
|
}
|
|
|
|
if (info.nickname) {
|
|
data += `NICKNAME:${escape(info.nickname)};`;
|
|
}
|
|
|
|
if (info.adr) {
|
|
data += `ADR:${escape(info.adr)};`;
|
|
}
|
|
|
|
if (info.adr) {
|
|
data += `ADR:${escape(info.adr)};`;
|
|
}
|
|
|
|
if (info.adr) {
|
|
data += `ADR:${escape(info.adr)};`;
|
|
}
|
|
|
|
if (info.adr) {
|
|
data += `ADR:${escape(info.adr)};`;
|
|
}
|
|
|
|
if (info.adr) {
|
|
data += `ADR:${escape(info.adr)};`;
|
|
}
|
|
|
|
data += ';';
|
|
|
|
return generate_qr_code(data, colors);
|
|
}
|
|
|
|
function escape(str: string) {
|
|
return str
|
|
.replace(/\\/g, '\\\\')
|
|
.replace(/"/g, '\\"')
|
|
.replace(/;/g, '\\;')
|
|
.replace(/,/g, '\\,')
|
|
.replace(/:/g, '\\:');
|
|
}
|