forked from educastellano/qr-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqr-code.js
More file actions
98 lines (97 loc) · 2.9 KB
/
qr-code.js
File metadata and controls
98 lines (97 loc) · 2.9 KB
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
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
}
}
static get observedAttributes() {
return Object.keys(QRCode.defaultAttributes)
}
// LifeCycle Callbacks
//
attributeChangedCallback(attributeName, oldValue, newValue) {
let fn = this[attributeName+'Changed']
if (fn && typeof fn === 'function') {
fn.call(this, oldValue, newValue)
}
this.generate()
}
// Methods
//
_defineProperty(attributeName) {
Object.defineProperty(this, attributeName, {
get: () => {
let value = this.getAttribute(attributeName)
return value === null ? QRCode.defaultAttributes[attributeName] : value
},
set: value => {
this.setAttribute(attributeName, value)
}
})
}
getOptions() {
let { modulesize, margin } = this
return {
modulesize: modulesize !== null ? parseInt(modulesize) : modulesize,
margin: margin !== null ? parseInt(margin) : margin
}
}
generate() {
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.innerHTML = '<div>qr-code: '+ this.format +' not supported!</div>'
}
}
else {
this.shadowRoot.innerHTML = '<div>qr-code: no data!</div>'
}
}
generatePNG() {
try {
let img = document.createElement('img')
img.src = _QRCode.generatePNG(this.data, this.getOptions())
this.clear()
this.shadowRoot.appendChild(img)
}
catch (e) {
this.shadowRoot.innerHTML = '<div>qr-code: no canvas support!</div>'
}
}
generateHTML() {
let div = _QRCode.generateHTML(this.data, this.getOptions())
this.clear()
this.shadowRoot.appendChild(div)
}
generateSVG() {
let div = _QRCode.generateSVG(this.data, this.getOptions())
this.clear()
this.shadowRoot.appendChild(div)
}
clear() {
while (this.shadowRoot.lastChild) {
this.shadowRoot.removeChild(this.shadowRoot.lastChild)
}
}
}