-
Notifications
You must be signed in to change notification settings - Fork 83
/
qr-code.js
117 lines (104 loc) · 2.74 KB
/
qr-code.js
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
109
110
111
112
113
114
115
116
117
import _QRCode from 'qrjs'
export default class QRCode extends HTMLElement {
constructor() {
super()
// method bindings
this._defineProperty = this._defineProperty.bind(this)
// Shadow DOM
this.attachShadow({ mode: 'open' })
// Define Properties
Object.keys(QRCode.defaultAttributes).map(this._defineProperty)
}
static get defaultAttributes() {
return {
data: null,
format: 'png',
modulesize: 5,
margin: 4,
unit: 'px',
ratio: 1
}
}
static get observedAttributes() {
return Object.keys(QRCode.defaultAttributes)
}
// LifeCycle Callbacks
//
attributeChangedCallback(attributeName, oldValue, newValue) {
const fn = this[attributeName+'Changed']
if (fn && typeof fn === 'function') {
fn.call(this, oldValue, newValue)
}
this.generate()
}
// Methods
//
_defineProperty(attributeName) {
Object.defineProperty(this, attributeName, {
get: () => {
const value = this.getAttribute(attributeName)
return value === null ? QRCode.defaultAttributes[attributeName] : value
},
set: value => {
this.setAttribute(attributeName, value)
}
})
}
getOptions() {
const { modulesize, margin, unit, ratio } = this
return {
margin: margin !== null ? parseInt(margin) : margin,
modulesize: modulesize !== null ? parseInt(modulesize) : modulesize,
unit: unit || 'px',
ratio: ratio || 1
}
}
generate() {
try {
this.clear()
if (this.data !== null) {
if (this.format === 'png') {
this.generatePNG()
}
else if (this.format === 'html') {
this.generateHTML()
}
else if (this.format === 'svg') {
this.generateSVG()
}
else {
this.shadowRoot.textContent = `qr-code: ${this.format} not supported!`
}
}
else {
this.shadowRoot.textContent = 'qr-code: no data!'
}
}
catch (e) {
console.error(e)
this.shadowRoot.textContent = 'qr-code: error!'
}
}
generatePNG() {
const img = document.createElement('img')
img.src = _QRCode.generatePNG(this.data, this.getOptions())
img.setAttribute('part', 'img')
this.shadowRoot.appendChild(img)
}
generateHTML() {
const div = _QRCode.generateHTML(this.data, this.getOptions())
const table = div.firstChild
table.setAttribute('part', 'table')
this.shadowRoot.appendChild(table)
}
generateSVG() {
const svg = _QRCode.generateSVG(this.data, this.getOptions())
svg.setAttribute('part', 'svg')
this.shadowRoot.appendChild(svg)
}
clear() {
while (this.shadowRoot.lastChild) {
this.shadowRoot.removeChild(this.shadowRoot.lastChild)
}
}
}