Rocket QR Code Pro

Rocket is currently in alpha – available in the Datastar Pro repo.

Dynamic QR code generation using the qr-creator library.

Demo

Explanation #

The QR Code component demonstrates Rocket’s ability to integrate external JavaScript libraries while maintaining reactive data binding. The component uses the qr-creator library loaded dynamically via CDN and automatically regenerates the QR code when props change.

Usage Example #

1<rocket-qrcode
2    data-attr:text="$qrText"
3    data-attr:size="$qrSize"
4    data-attr:error-level="$qrErrorLevel"
5    data-attr:color-dark="$qrColorDark"
6    data-attr:color-light="$qrColorLight"
7></rocket-qrcode>

Rocket Component #

 1<template data-rocket:rocket-qrcode
 2          data-schema:hex-color="str trim (prefix '#') upper (maxLength 7)"
 3          data-prop:text="str trim (= 'Hello World')"
 4          data-prop:size="int (clamp 50 1000) (= 200)"
 5          data-prop:error-level="or (L M Q H) (= L)"
 6          data-prop:color-dark="hexColor (= '#000000')"
 7          data-prop:color-light="hexColor (= '#ffffff')"
 8          data-import:qr="https://cdn.jsdelivr.net/npm/[email protected]/+esm"
 9>
10  <script>
11    $$errorText = ''
12
13    effect(() => {
14      const messages = []
15      const isHexColor = (value) => /^#[0-9A-F]{6}$/.test(String(value ?? ''))
16
17      if (!$$text) {
18        messages.push('Text is required')
19      }
20
21      if ($$size < 50 || $$size > 1000) {
22        messages.push('Size must be 50-1000px')
23      }
24      if (!isHexColor($$colorDark) || !isHexColor($$colorLight)) {
25        messages.push('Colors must be valid hex codes')
26      }
27
28      if (messages.length) {
29        $$errorText = messages.join(', ') || 'Validation failed'
30        return
31      }
32
33      if (!$$canvas) return
34
35      try {
36        qr.render({
37          text: $$text,
38          radius: 0,
39          ecLevel: $$errorLevel,
40          fill: $$colorDark,
41          background: $$colorLight,
42          size: $$size
43        }, $$canvas)
44        // Clear error on success
45        if ($$errorText) {
46          $$errorText = ''
47        }
48      } catch (error) {
49        console.error('[Rocket QR] Error generating QR code:', error)
50        $$errorText = `QR generation failed: ${error.message}`
51      }
52    })
53  </script>
54
55  <div data-style="{width: $$size + 'px', height: $$size + 'px', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', position: 'relative'}">
56    <template data-if="!$$errorText">
57      <canvas data-ref="canvas" style="display: block;"></canvas>
58    </template>
59    <template data-else>
60      <div data-text="$$errorText" style="font-weight: bold; text-align: center;"></div>
61    </template>
62  </div>
63</template>