From 39a2aedd6d945a45f165b5c82b74a73151c1c52a Mon Sep 17 00:00:00 2001 From: Radoslav Karaivanov Date: Mon, 23 Nov 2026 13:03:49 +0200 Subject: [PATCH 1/7] feat(qr-code): encode the value in mixed-mode segments Split the value into numeric, alphanumeric and byte segments with the fewest bits, by a shortest path over the characters for each count field width group. Neighbors that tie on bits merge into one segment. A value with a long digit or uppercase run in other text can get a smaller version. Export the QrCornerDotStyle type. Document that the code writes UTF-8 with no ECI header. The single-mode property spec now checks the bits against the best single mode. New properties check the version of mixed data and decode the matrix with zxing, through a shared prepareQrDecoder() helper that the component spec also uses. --- .github/CODING_GUIDELINES.md | 1 + CHANGELOG.md | 1 + public-api.json | 1 + src/components/qr-code/model/encode.ts | 336 ++++++++++++------ .../qr-code/model/qr-model.property.spec.ts | 133 ++++++- src/components/qr-code/model/qr-model.spec.ts | 40 +++ src/components/qr-code/qr-code.spec.ts | 31 +- src/components/qr-code/spec.md | 17 +- src/components/qr-code/types.ts | 2 +- src/index.ts | 1 + src/internals/testing/qr-decoder.spec.ts | 13 + 11 files changed, 431 insertions(+), 145 deletions(-) create mode 100644 src/internals/testing/qr-decoder.spec.ts diff --git a/.github/CODING_GUIDELINES.md b/.github/CODING_GUIDELINES.md index d11afb104..b3e45cedc 100644 --- a/.github/CODING_GUIDELINES.md +++ b/.github/CODING_GUIDELINES.md @@ -633,6 +633,7 @@ Each component has tests in `[component].spec.ts`. They cover: | `helpers.spec.js` | Animation, focus, scroll and style helpers, and `axeReflectedRelationsOptions` | | `fast-check-setup.spec.js` | `fc` with the seed, `SLOW_PROPERTY_RUNS`, `orderedPair` and `withFixture` | | `date-arbitraries.spec.js` | Date arbitraries, wall clocks and `assumeWallClock` for date properties | + | `qr-decoder.spec.js` | `prepareQrDecoder`, which loads the zxing decoder for QR scan specs | Use the simulated events, not `element.click()` or a hand-built `KeyboardEvent`. They send the full event sequence of a real user interaction. diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e090c75d..ea32dd478 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - #### Library - The library supports the last 2 major versions of Chrome, Edge, Firefox, Opera and Safari. The fallbacks for older browsers are removed, and the styles no longer have vendor prefixes for them. - #### QR code + - The code splits its value into numeric, alphanumeric and byte segments with the fewest bits. A value that mixes long runs of digits or uppercase letters with other text, such as an order number in a URL, can get a smaller version. A scanner reads the same text. - The cutout under the logo holds whole modules, so it cuts no module in part. - `logoSize` is a share of the code without its quiet zone, so `margin` no longer changes the logo. At the default `margin`, logos are smaller than before: 28% smaller in side on a version 1 code, and 4% on a version 40 code. - #### Radio diff --git a/public-api.json b/public-api.json index 45080f5da..09f1816d5 100644 --- a/public-api.json +++ b/public-api.json @@ -213,6 +213,7 @@ "QrCodeCopyOptions", "QrCodeExportFormat", "QrCodeExportOptions", + "QrCornerDotStyle", "QrCornerSquareStyle", "QrDotStyle", "QrErrorCorrectionLevel", diff --git a/src/components/qr-code/model/encode.ts b/src/components/qr-code/model/encode.ts index e1d14be73..1e19d227f 100644 --- a/src/components/qr-code/model/encode.ts +++ b/src/components/qr-code/model/encode.ts @@ -12,98 +12,222 @@ const ALPHANUMERIC_MAP = new Map( const PAD_BYTES = [0xec, 0x11]; const TEXT_ENCODER = new TextEncoder(); -function getAlphanumericValue(char: string): number { - return ALPHANUMERIC_MAP.get(char)!; +type Mode = { + name: QrEncodingMode; + indicator: number; + /** + * The count field widths for versions 1-9, 10-26 and 27-40. A count too large for its field + * needs more bits than the last version of the group holds. + */ + countBits: readonly number[]; + /** + * The cost of `char` in sixths of a bit, so that 10 bits for 3 digits and 11 bits for + * 2 alphanumeric characters are whole numbers, or `Infinity`. + */ + cost(char: string): number; + /** Writes the count field of `text`, `width` bits wide, and its data. */ + write(bits: number[], text: string, width: number): void; +}; + +/** Each mode encodes all the characters of the modes before it. */ +const MODES: readonly Mode[] = [ + { + name: 'numeric', + indicator: 0b0001, + countBits: [10, 12, 14], + cost: (char) => + char >= '0' && char <= '9' ? 20 : Number.POSITIVE_INFINITY, + write(bits, text, width) { + pushBits(bits, text.length, width); + for (let i = 0; i < text.length; i += 3) { + const chunk = text.slice(i, i + 3); + pushBits(bits, Number.parseInt(chunk, 10), chunk.length * 3 + 1); + } + }, + }, + { + name: 'alphanumeric', + indicator: 0b0010, + countBits: [9, 11, 13], + cost: (char) => + ALPHANUMERIC_MAP.has(char) ? 33 : Number.POSITIVE_INFINITY, + write(bits, text, width) { + pushBits(bits, text.length, width); + for (let i = 0; i < text.length; i += 2) { + const value = ALPHANUMERIC_MAP.get(text[i])!; + + if (i + 1 < text.length) { + pushBits(bits, value * 45 + ALPHANUMERIC_MAP.get(text[i + 1])!, 11); + } else { + pushBits(bits, value, 6); + } + } + }, + }, + { + name: 'byte', + indicator: 0b0100, + countBits: [8, 16, 16], + cost(char) { + // The UTF-8 length; `TextEncoder` writes a lone surrogate as 3 bytes. + const code = char.codePointAt(0)!; + return 48 * (code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4); + }, + write(bits, text, width) { + const bytes = TEXT_ENCODER.encode(text); + pushBits(bits, bytes.length, width); + for (const byte of bytes) { + pushBits(bits, byte, 8); + } + }, + }, +]; + +/** The last version of each count field group. */ +const GROUP_LAST_VERSIONS = [9, 26, 40]; + +/** A run of characters in one mode, by its index in `MODES`. */ +type Segment = { mode: number; text: string }; + +function pushBits(bits: number[], value: number, length: number): void { + for (let i = length - 1; i >= 0; i--) { + bits.push((value >> i) & 1); + } } -function isNumeric(str: string): boolean { - return /^\d+$/.test(str); +function getSegmentBits({ mode, text }: Segment, group: number): number { + let cost = 0; + for (const char of text) { + cost += MODES[mode].cost(char); + } + return 4 + MODES[mode].countBits[group] + Math.ceil(cost / 6); } -function isAlphanumeric(str: string): boolean { - for (const char of str) { - if (!ALPHANUMERIC_MAP.has(char)) { - return false; +/** + * Splits `chars` into the segments with the fewest bits for the count fields of `group`, by a + * shortest path over the characters. Then neighbors merge when that costs no bits. + */ +function splitSegments(chars: string[], group: number): Segment[] { + const modeCount = MODES.length; + const headers = MODES.map( + (_, mode) => getSegmentBits({ mode, text: '' }, group) * 6 + ); + // The cheapest path whose next character is in each mode. + const costs = headers.slice(); + const stayCosts = headers.map(() => 0); + // At `i * modeCount + m`, the mode of character `i` on the path in `costs[m]`. + const steps = new Int8Array(chars.length * modeCount); + + for (let i = 0; i < chars.length; i++) { + for (let m = 0; m < modeCount; m++) { + stayCosts[m] = costs[m] + MODES[m].cost(chars[i]); + } + + for (let to = 0; to < modeCount; to++) { + costs[to] = stayCosts[to]; + steps[i * modeCount + to] = to; + + for (let from = 0; from < modeCount; from++) { + // A segment ends on a whole bit. + const switched = Math.ceil(stayCosts[from] / 6) * 6 + headers[to]; + if (switched < costs[to]) { + costs[to] = switched; + steps[i * modeCount + to] = from; + } + } } } - return true; -} -function detectEncodingMode(data: string): QrEncodingMode { - if (isNumeric(data)) return 'numeric'; - if (isAlphanumeric(data)) return 'alphanumeric'; - return 'byte'; -} + const modes = new Int8Array(chars.length); + let mode = costs.indexOf(Math.min(...costs)); -function getCharacterCountBits(mode: QrEncodingMode, version: number): number { - switch (mode) { - case 'numeric': - return version < 10 ? 10 : version < 27 ? 12 : 14; - case 'alphanumeric': - return version < 10 ? 9 : version < 27 ? 11 : 13; - case 'byte': - return version < 10 ? 8 : 16; - default: - throw new Error(`Unsupported encoding mode: ${mode}`); + for (let i = chars.length - 1; i >= 0; i--) { + mode = steps[i * modeCount + mode]; + modes[i] = mode; } -} -const MODE_INDICATORS: Record = { - numeric: 0b0001, - alphanumeric: 0b0010, - byte: 0b0100, -}; + const segments: Segment[] = []; -function pushBits(bits: number[], value: number, length: number): void { - for (let i = length - 1; i >= 0; i--) { - bits.push((value >> i) & 1); + for (let start = 0, end = 1; end <= chars.length; end++) { + if (end < chars.length && modes[end] === modes[start]) continue; + + let segment: Segment = { + mode: modes[start], + text: chars.slice(start, end).join(''), + }; + start = end; + + while (segments.length > 0) { + const last = segments.at(-1)!; + const merged: Segment = { + mode: Math.max(last.mode, segment.mode), + text: last.text + segment.text, + }; + + if ( + getSegmentBits(merged, group) > + getSegmentBits(last, group) + getSegmentBits(segment, group) + ) { + break; + } + + segments.pop(); + segment = merged; + } + + segments.push(segment); } + + return segments; } -function encodeData( - data: string, - mode: QrEncodingMode, - version: number -): number[] { +function encodeSegments(segments: Segment[], group: number): number[] { const bits: number[] = []; - const byteEncoded = mode === 'byte' ? TEXT_ENCODER.encode(data) : null; - pushBits(bits, MODE_INDICATORS[mode], 4); + for (const { mode, text } of segments) { + pushBits(bits, MODES[mode].indicator, 4); + MODES[mode].write(bits, text, MODES[mode].countBits[group]); + } - const charCount = byteEncoded ? byteEncoded.length : data.length; - pushBits(bits, charCount, getCharacterCountBits(mode, version)); + return bits; +} - switch (mode) { - case 'numeric': - for (let i = 0; i < data.length; i += 3) { - const chunk = data.slice(i, i + 3); - const value = Number.parseInt(chunk, 10); +/** + * Returns the smallest version from `first` to `last` that holds `chars`, with the segments + * and the bits for it, or `null`. + */ +function fitVersion( + chars: string[], + ecIndex: number, + first: number, + last: number +): { version: number; segments: Segment[]; bits: number[] } | null { + for (const [group, groupLast] of GROUP_LAST_VERSIONS.entries()) { + const start = Math.max(first, (GROUP_LAST_VERSIONS[group - 1] ?? 0) + 1); + const end = Math.min(last, groupLast); - if (chunk.length === 3) pushBits(bits, value, 10); - else if (chunk.length === 2) pushBits(bits, value, 7); - else pushBits(bits, value, 4); - } - break; - case 'alphanumeric': - for (let i = 0; i < data.length; i += 2) { - if (i + 1 < data.length) { - const value = - getAlphanumericValue(data[i]) * 45 + - getAlphanumericValue(data[i + 1]); - pushBits(bits, value, 11); - } else { - pushBits(bits, getAlphanumericValue(data[i]), 6); - } - } - break; - default: - for (const byte of byteEncoded!) { - pushBits(bits, byte, 8); + // Even as digits, at 10 bits for 3, the characters need more bits than the group holds. + if ( + start > end || + chars.length * 10 > getDataCodewordsCount(end, ecIndex) * 24 + ) { + continue; + } + + const segments = splitSegments(chars, group); + const bits = encodeSegments(segments, group); + + for (let version = start; version <= end; version++) { + if ( + Math.ceil((bits.length + 4) / 8) <= + getDataCodewordsCount(version, ecIndex) + ) { + return { version, segments, bits }; } - break; + } } - return bits; + return null; } function bitsToBytes(bits: number[]): number[] { @@ -132,8 +256,10 @@ function padData(data: number[], totalBytes: number): number[] { export type EncodeResult = { /** Interleaved data + ECC codewords ready for matrix placement. */ codewords: number[]; - /** Encoding mode that was applied to the input string. */ - mode: QrEncodingMode; + /** The mode of the single segment of the data, or `'mixed'`. */ + mode: QrEncodingMode | 'mixed'; + /** The length of the segments in bits, without the terminator and the padding. */ + dataBits: number; /** QR version (1–40) used for this code. */ version: number; /** Numeric index of the error correction level (L=0, M=1, Q=2, H=3). */ @@ -150,7 +276,8 @@ export function isValidVersion(version: unknown): version is number { /** * Encodes a string into QR codewords (data + error correction), selecting the - * smallest version that fits unless `requestedVersion` is specified. + * smallest version that fits unless `requestedVersion` is specified. The data is split + * into the numeric, alphanumeric and byte segments with the fewest bits. * * @throws When `data` is empty, the requested version is out of range, or the * data exceeds the capacity of the requested version. @@ -163,54 +290,28 @@ export function encodeQR( if (data.length === 0) { throw new Error('Data cannot be empty'); } + if (requestedVersion != null && !isValidVersion(requestedVersion)) { + throw new Error('Requested version must be an integer between 1 and 40'); + } const ecIndex = EC_LEVEL_INDEX[ecLevel]; - const mode = detectEncodingMode(data); - const fits = (v: number, candidate: number[]) => - Math.ceil((candidate.length + 4) / 8) <= getDataCodewordsCount(v, ecIndex); - - let version = 1; - let bits: number[]; - - if (requestedVersion != null) { - if (!isValidVersion(requestedVersion)) { - throw new Error('Requested version must be an integer between 1 and 40'); - } - version = requestedVersion; - bits = encodeData(data, mode, version); - if (!fits(version, bits)) { - throw new Error( - `Data too long for version ${version} and error correction level ${ecLevel}` - ); - } - } else { - bits = []; - // Only the count field width depends on the version. - let candidate: number[] = []; - let countBits = 0; - - for (let v = 1; v <= 40; v++) { - const width = getCharacterCountBits(mode, v); - - if (width !== countBits) { - countBits = width; - candidate = encodeData(data, mode, v); - } - if (fits(v, candidate)) { - version = v; - bits = candidate; - break; - } - } + const fit = fitVersion( + Array.from(data), + ecIndex, + requestedVersion ?? 1, + requestedVersion ?? 40 + ); - // `encodeData()` never returns empty bits, so no version fits the data. - if (bits.length === 0) { - throw new Error( - `Data too long to fit in any QR version (1-40) at error correction level '${ecLevel}'` - ); - } + if (!fit) { + throw new Error( + requestedVersion == null + ? `Data too long to fit in any QR version (1-40) at error correction level '${ecLevel}'` + : `Data too long for version ${requestedVersion} and error correction level ${ecLevel}` + ); } + const { version, segments, bits } = fit; + const dataBits = bits.length; const capacity = getDataCodewordsCount(version, ecIndex); const maxBits = capacity * 8; @@ -229,7 +330,8 @@ export function encodeQR( return { codewords, - mode, + mode: segments.length === 1 ? MODES[segments[0].mode].name : 'mixed', + dataBits, version, ecLevelIndex: ecIndex, }; diff --git a/src/components/qr-code/model/qr-model.property.spec.ts b/src/components/qr-code/model/qr-model.property.spec.ts index f11e0758c..50ee407e9 100644 --- a/src/components/qr-code/model/qr-model.property.spec.ts +++ b/src/components/qr-code/model/qr-model.property.spec.ts @@ -1,9 +1,11 @@ import { expect } from '@open-wc/testing'; +import { readBarcodes } from 'zxing-wasm/reader'; import { fc, SLOW_PROPERTY_RUNS, } from '#internals/testing/fast-check-setup.spec.js'; +import { prepareQrDecoder } from '#internals/testing/qr-decoder.spec.js'; import type { QrErrorCorrectionLevel } from '../types.js'; import { EC_LEVEL_INDEX, encodeQR } from './encode.js'; import { EC_BLOCKS_TABLE, getDataCodewordsCount } from './error-correction.js'; @@ -11,6 +13,7 @@ import { generateQRCodeMatrix } from './matrix.js'; const EC_LEVELS = Object.keys(EC_LEVEL_INDEX) as QrErrorCorrectionLevel[]; const ALPHANUMERIC = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:'; +const TEXT_ENCODER = new TextEncoder(); /** * Returns the total codewords of a version, from its module count (ISO/IEC 18004). The @@ -42,7 +45,86 @@ const data = fc.oneof( fc.string({ unit: 'binary', minLength: 1, maxLength: 100 }) ); +/** Runs that favor different modes, so that the encoder splits the value into segments. */ +const mixedData = fc + .array( + fc.oneof( + fc.stringMatching(/^\d{1,40}$/), + fc + .array(fc.constantFrom(...ALPHANUMERIC), { + minLength: 1, + maxLength: 40, + }) + .map((chars) => chars.join('')), + fc.string({ unit: 'grapheme', minLength: 1, maxLength: 20 }) + ), + { minLength: 1, maxLength: 8 } + ) + .map((runs) => runs.join('')); + +const anyData = fc.oneof(data, mixedData); + +const SINGLE_MODES = ['numeric', 'alphanumeric', 'byte'] as const; + +/** + * Returns the bits of `value` as one segment of `mode` in a code of `version`, or `Infinity` + * when the mode cannot encode it (ISO/IEC 18004, 7.4). The oracle does not use the encoder. + */ +function singleModeBits( + value: string, + mode: (typeof SINGLE_MODES)[number], + version: number +): number { + const group = version < 10 ? 0 : version < 27 ? 1 : 2; + const length = value.length; + + switch (mode) { + case 'numeric': + return /^\d+$/.test(value) + ? 4 + + [10, 12, 14][group] + + 10 * Math.floor(length / 3) + + [0, 4, 7][length % 3] + : Number.POSITIVE_INFINITY; + case 'alphanumeric': + return [...value].every((c) => ALPHANUMERIC.includes(c)) + ? 4 + + [9, 11, 13][group] + + 11 * Math.floor(length / 2) + + 6 * (length % 2) + : Number.POSITIVE_INFINITY; + default: + return 4 + [8, 16, 16][group] + 8 * TEXT_ENCODER.encode(value).length; + } +} + +/** Draws `matrix` with 4 pixels for each module and a quiet zone of 4 modules. */ +function toImageData(matrix: boolean[][]): ImageData { + const scale = 4; + const offset = 4 * scale; + const side = matrix.length * scale + 2 * offset; + const image = new ImageData(side, side); + image.data.fill(255); + + for (const [row, modules] of matrix.entries()) { + for (const [col, dark] of modules.entries()) { + if (!dark) continue; + + for (let y = 0; y < scale; y++) { + const start = (offset + row * scale + y) * side + offset + col * scale; + for (let x = start; x < start + scale; x++) { + image.data.fill(0, x * 4, x * 4 + 3); + } + } + } + } + + return image; +} + describe('QR model properties', () => { + before(prepareQrDecoder); + it('holds as many codewords per version as the symbol has room for', () => { fc.assert( fc.property(version, fc.nat(3), (v, ecIndex) => { @@ -77,22 +159,53 @@ describe('QR model properties', () => { ); }); - it('picks the most compact mode for the characters of the data', () => { + it('encodes mixed data into the smallest version that holds it', () => { + fc.assert( + fc.property(mixedData, ecLevel, (value, level) => { + const result = encodeQR(value, level); + + expect(result.codewords).to.have.lengthOf( + totalCodewords(result.version) + ); + if (result.version > 1) { + expect(() => encodeQR(value, level, result.version - 1)).to.throw( + /Data too long/ + ); + } + expect(encodeQR(value, level, result.version)).to.deep.equal(result); + }) + ); + }); + + it('the segments never take more bits than the best single mode', () => { fc.assert( - fc.property(data, (value) => { - const { mode } = encodeQR(value, 'L'); - - if (/^\d+$/.test(value)) { - expect(mode).to.equal('numeric'); - } else if ([...value].every((c) => ALPHANUMERIC.includes(c))) { - expect(mode).to.equal('alphanumeric'); - } else { - expect(mode).to.equal('byte'); + fc.property(anyData, ecLevel, (value, level) => { + const { mode, dataBits, version: v } = encodeQR(value, level); + const single = SINGLE_MODES.map((m) => singleModeBits(value, m, v)); + + expect(dataBits).to.be.at.most(Math.min(...single)); + if (mode !== 'mixed') { + expect(dataBits).to.equal(single[SINGLE_MODES.indexOf(mode)]); } }) ); }); + it('gives a decoder the bytes of the data back', async () => { + await fc.assert( + fc.asyncProperty(anyData, ecLevel, async (value, level) => { + const { matrix } = generateQRCodeMatrix(value, level); + const [result] = await readBarcodes(toImageData(matrix), { + formats: ['QRCode'], + maxNumberOfSymbols: 1, + }); + + expect(result?.bytes).to.deep.equal(TEXT_ENCODER.encode(value)); + }), + { numRuns: SLOW_PROPERTY_RUNS } + ); + }); + it('builds a square matrix of the version size', () => { fc.assert( fc.property(data, ecLevel, (value, level) => { diff --git a/src/components/qr-code/model/qr-model.spec.ts b/src/components/qr-code/model/qr-model.spec.ts index d467925eb..800e54235 100644 --- a/src/components/qr-code/model/qr-model.spec.ts +++ b/src/components/qr-code/model/qr-model.spec.ts @@ -47,6 +47,46 @@ describe('QR model - encodeQR', () => { }); }); + describe('Segments', () => { + it('puts a long digit run in its own segment', () => { + const result = encodeQR('https://example.com/order/12345678901234567890'); + expect(result.mode).to.equal('mixed'); + // Byte mode alone: 4 + 8 + 46 * 8 bits. + expect(result.dataBits).to.be.below(380); + }); + + it('selects a smaller version than one byte segment would need', () => { + // One byte segment: 4 + 8 + 31 * 8 = 260 bits, version 3 at level M. + // Byte 'a' and 30 digits: 20 + 114 = 134 bits, version 2. + const result = encodeQR(`a${'1'.repeat(30)}`, 'M'); + expect(result.mode).to.equal('mixed'); + expect(result.version).to.equal(2); + }); + + it('keeps one segment when a switch costs more than it saves', () => { + expect(encodeQR('item 12').mode).to.equal('byte'); + expect(encodeQR('ORDER-12345').mode).to.equal('alphanumeric'); + }); + + it('keeps one segment when a switch saves no bits', () => { + // Byte alone and 'Test' + numeric '123' both take 68 bits. + const result = encodeQR('Test123'); + expect(result.mode).to.equal('byte'); + expect(result.dataBits).to.equal(68); + + // One alphanumeric segment and 'A' + numeric '1111111' both take 57 bits. + expect(encodeQR('A1111111').mode).to.equal('alphanumeric'); + expect(encodeQR('1111111A').mode).to.equal('alphanumeric'); + }); + + it('splits the data at code points', () => { + const result = encodeQR(`😀${'7'.repeat(20)}😀`); + expect(result.mode).to.equal('mixed'); + // Two byte segments of 4 bytes and one numeric segment of 20 digits. + expect(result.dataBits).to.equal(2 * (4 + 8 + 32) + (4 + 10 + 67)); + }); + }); + describe('Auto version selection', () => { it('selects version 1 for short numeric data at level M', () => { const result = encodeQR('42', 'M'); diff --git a/src/components/qr-code/qr-code.spec.ts b/src/components/qr-code/qr-code.spec.ts index 0d2d9cb20..7ecdcb34f 100644 --- a/src/components/qr-code/qr-code.spec.ts +++ b/src/components/qr-code/qr-code.spec.ts @@ -7,8 +7,9 @@ import { } from '@open-wc/testing'; import { ifDefined } from 'lit/directives/if-defined.js'; import { restore, type SinonStub, stub } from 'sinon'; -import { prepareZXingModule, readBarcodes } from 'zxing-wasm/reader'; +import { readBarcodes } from 'zxing-wasm/reader'; import { defineComponents } from '#internals/definitions/defineComponents.js'; +import { prepareQrDecoder } from '#internals/testing/qr-decoder.spec.js'; import { asNumber } from '#internals/utils/math.js'; import { configureTheme } from '#theming/config.js'; import IgcQrCodeComponent from './qr-code.js'; @@ -1698,17 +1699,7 @@ describe('IgcQrCodeComponent', () => { let el: IgcQrCodeComponent; - before(() => { - // Load the decoder from the package, not from its default CDN. - prepareZXingModule({ - overrides: { - locateFile: (path: string, prefix: string) => - path.endsWith('.wasm') - ? '/node_modules/zxing-wasm/dist/reader/zxing_reader.wasm' - : prefix + path, - }, - }); - }); + before(prepareQrDecoder); beforeEach(async () => { el = await fixture( @@ -1817,5 +1808,21 @@ describe('IgcQrCodeComponent', () => { } }); } + + it('reads values that mix numeric, alphanumeric and byte segments', async () => { + for (const value of [ + 'https://example.com/order/12345678901234567890', + 'TICKET 2026-11-23 SEAT 0042 GATE B7 - have a nice trip', + `a${'1'.repeat(30)}`, + `😀${'7'.repeat(20)}😀`, + ]) { + el.value = value; + expect(await scan(), value).to.equal(value); + + el.logoSrc = solidLogo('#000'); + expect(await scan(), `${value}, logo`).to.equal(value); + el.logoSrc = undefined; + } + }); }); }); diff --git a/src/components/qr-code/spec.md b/src/components/qr-code/spec.md index 3cbc3eb4e..e1541db68 100644 --- a/src/components/qr-code/spec.md +++ b/src/components/qr-code/spec.md @@ -60,6 +60,7 @@ | 5 | 2026-10-20 | `copyToClipboard()`; exports read `size` after the pending render | | 6 | 2026-10-21 | An invalid `version` falls back to the automatic version | | 7 | 2026-11-17 | Shapes, `cornerDotStyle`, `dotScale`, logo cutout and version fit | +| 8 | 2026-11-23 | Mixed-mode segments; UTF-8 without an ECI header | ## Overview @@ -74,8 +75,8 @@ authentication setup URLs, contact sharing and linking printed material to digit ### Key features -- **Automatic encoding**: the most compact mode — numeric, alphanumeric or byte — and the smallest version that - fits the value, unless a `version` is pinned. +- **Automatic encoding**: the value split into numeric, alphanumeric and byte segments with the fewest bits, and the + smallest version that fits it, unless a `version` is pinned. - **Configurable error correction** across `L`, `M`, `Q` and `H`, trading capacity for resilience. - **Center logo** with the modules beneath it masked out, and, when `error-level` is not set, an automatic escalation from `M` to the smallest level that keeps the code scannable at the requested logo size. @@ -91,7 +92,8 @@ authentication setup URLs, contact sharing and linking printed material to digit ### Acceptance criteria - The component must render an SVG whenever a non-empty `value` is set, and nothing when it is not. -- It must pick an encoding mode and a version that fit the value, unless a `version` is pinned. +- It must split the value into the segments with the fewest bits and pick a version that fits them, unless a + `version` is pinned. - `error-level` must drive the error correction of the generated matrix. - `size` and `margin` must control the rendered pixels and the quiet zone without touching the encoded data. - A valid `logo-src` must be centered over the code with the whole modules beneath it masked out. @@ -472,8 +474,9 @@ None. The SVG is rendered entirely from the properties of the component. 33. Each version and error correction level holds as many codewords as the symbol has room for, checked against the module count of ISO/IEC 18004. -34. Generated numeric, alphanumeric and byte data encodes into the smallest version that holds it, with the - codeword count of that version, and the encoding mode matches the characters of the data. +34. Generated numeric, alphanumeric, byte and mixed data encodes into the smallest version that holds it, with the + codeword count of that version, and never takes more bits than one segment of the best single mode. A decoder + reads the bytes of the data back from the matrix. 35. The matrix is square, with the side length of its version, and data over the capacity of a version throws the capacity error. A requested version that is not an integer from 1 to 40 throws. @@ -493,6 +496,7 @@ each module. level. 40. A white, black or gray logo on codes of version 1 to 3 decodes at each error correction level, at the default and the largest `logoSize`, and so does a logo on a pinned version 1, 2 or 3. +41. Values that mix numeric, alphanumeric and byte segments decode, with and without a logo. ### Not covered by the suite @@ -504,6 +508,9 @@ each module. ## Assumptions and limitations +- The code writes text as UTF-8 in byte mode, with no ECI header. Phone readers assume UTF-8, and many readers ignore + an ECI header, so the component does not write one. A reader that follows the ISO default reads non-ASCII text as + ISO-8859-1. - The readability rule for a logo counts every codeword with a hidden module as lost. A real logo spoils fewer codewords, so the rule can select a larger version than a scanner needs. - On 2026-11-17, zxing-cpp did not read some codes of version 8 and above with `square-style="circle"` at some image diff --git a/src/components/qr-code/types.ts b/src/components/qr-code/types.ts index 05d51c736..398f4a2a9 100644 --- a/src/components/qr-code/types.ts +++ b/src/components/qr-code/types.ts @@ -14,7 +14,7 @@ export type QrCornerSquareStyle = 'square' | 'circle' | 'rounded' | 'squircle'; export type QrErrorCorrectionLevel = 'L' | 'M' | 'Q' | 'H'; /** - * QR data encoding mode, selected automatically based on the input string. + * QR data encoding mode of a segment. The encoder splits the value into the segments with the fewest bits. * - `numeric` - digits only; `alphanumeric` - digits + uppercase letters + a few symbols; `byte` - arbitrary UTF-8. */ export type QrEncodingMode = 'numeric' | 'alphanumeric' | 'byte'; diff --git a/src/index.ts b/src/index.ts index 9d579f4bc..433b18938 100644 --- a/src/index.ts +++ b/src/index.ts @@ -240,6 +240,7 @@ export type { QrCodeCopyOptions, QrCodeExportFormat, QrCodeExportOptions, + QrCornerDotStyle, QrCornerSquareStyle, QrDotStyle, QrErrorCorrectionLevel, diff --git a/src/internals/testing/qr-decoder.spec.ts b/src/internals/testing/qr-decoder.spec.ts new file mode 100644 index 000000000..5b7a06a38 --- /dev/null +++ b/src/internals/testing/qr-decoder.spec.ts @@ -0,0 +1,13 @@ +import { prepareZXingModule } from 'zxing-wasm/reader'; + +/** Loads the zxing decoder from the package, not from its default CDN. */ +export function prepareQrDecoder(): void { + prepareZXingModule({ + overrides: { + locateFile: (path: string, prefix: string) => + path.endsWith('.wasm') + ? '/node_modules/zxing-wasm/dist/reader/zxing_reader.wasm' + : prefix + path, + }, + }); +} From 67c3d0f68d483764fcc72d3bfac5ca0f11971224 Mon Sep 17 00:00:00 2001 From: Radoslav Karaivanov Date: Mon, 23 Nov 2026 13:33:23 +0200 Subject: [PATCH 2/7] feat(qr-code): add payload helpers for Wi-Fi, vCard, EPC and events Add igniteui-webcomponents/extras/qr-payloads with createWifiPayload(), createVCardPayload(), createEpcPayload() and createEventPayload(). Each builds the value of a code that a phone turns into an action, escapes the text, and throws a RangeError for input that its format does not allow. The formats are WIFI:, vCard 3.0, EPC version 002 in UTF-8, and an iCalendar VEVENT in UTC. Property specs read the escapes back with independent parsers. Move each extra into its own folder with a README that the main README links, and give the payload helpers a specification. The subpaths do not change. The Generator story uses the helpers and adds a payment and an event. New stories show the mailto:, tel:, SMSTO: and geo: recipes and a "Scan me" frame. The QR scan specs share readQr() and readQrMatrix(). --- .agents/context/project.md | 3 +- .github/CODING_GUIDELINES.md | 7 +- CHANGELOG.md | 1 + README.md | 22 +- package.json | 3 +- scripts/_package.json | 8 +- .../qr-code/model/qr-model.property.spec.ts | 39 +- src/components/qr-code/qr-code.spec.ts | 12 +- src/components/qr-code/spec.md | 36 +- src/extras/chat-markdown-renderer/README.md | 69 ++++ .../chat-markdown-renderer.spec.ts | 2 +- .../chat-markdown-renderer.ts | 2 +- src/extras/combo-data-source/README.md | 71 ++++ .../combo-data-source.spec.ts | 8 +- .../combo-data-source.ts | 8 +- src/extras/index.ts | 2 +- src/extras/qr-payloads/README.md | 138 +++++++ .../qr-payloads/qr-payloads.property.spec.ts | 111 ++++++ src/extras/qr-payloads/qr-payloads.spec.ts | 359 ++++++++++++++++++ src/extras/qr-payloads/qr-payloads.ts | 332 ++++++++++++++++ src/extras/qr-payloads/spec.md | 294 ++++++++++++++ src/internals/testing/qr-decoder.spec.ts | 43 ++- stories/qr-code.stories.ts | 240 ++++++++++-- 23 files changed, 1695 insertions(+), 115 deletions(-) create mode 100644 src/extras/chat-markdown-renderer/README.md rename src/extras/{ => chat-markdown-renderer}/chat-markdown-renderer.spec.ts (99%) rename src/extras/{ => chat-markdown-renderer}/chat-markdown-renderer.ts (99%) create mode 100644 src/extras/combo-data-source/README.md rename src/extras/{ => combo-data-source}/combo-data-source.spec.ts (98%) rename src/extras/{ => combo-data-source}/combo-data-source.ts (96%) create mode 100644 src/extras/qr-payloads/README.md create mode 100644 src/extras/qr-payloads/qr-payloads.property.spec.ts create mode 100644 src/extras/qr-payloads/qr-payloads.spec.ts create mode 100644 src/extras/qr-payloads/qr-payloads.ts create mode 100644 src/extras/qr-payloads/spec.md diff --git a/.agents/context/project.md b/.agents/context/project.md index 6a0e27a6c..97e317a57 100644 --- a/.agents/context/project.md +++ b/.agents/context/project.md @@ -24,7 +24,8 @@ Read them before making changes; if they disagree with this file, they win. `#internals/*`, `#theming/*` and `#animations/*` aliases. The theme aggregator of a component is imported through `#themes/*`. - `src/extras/`: opt-in add-ons, published under `igniteui-webcomponents/extras`. A new add-on gets its own - subpath export, so an import pulls in only its own dependencies + directory with a `README.md` that the main README links, and its own subpath export, so an import pulls in only its + own dependencies - `src/styles/`: global SCSS utilities, mixins and themes - `src/index.ts`: the public entry point of the package - `stories/`: Storybook stories, one per component tag diff --git a/.github/CODING_GUIDELINES.md b/.github/CODING_GUIDELINES.md index b3e45cedc..e0698edfd 100644 --- a/.github/CODING_GUIDELINES.md +++ b/.github/CODING_GUIDELINES.md @@ -40,7 +40,7 @@ entry in `package.json` holds the same list. src/ ├── animations/ # Animation players and presets → #animations/* ├── components/ # One directory per component, each with its own spec.md -├── extras/ # Opt-in add-ons, published under `igniteui-webcomponents/extras` +├── extras/ # Opt-in add-ons, one directory each with a README.md, published under `igniteui-webcomponents/extras` ├── internals/ # Shared building blocks, never public API → #internals/* ├── styles/ # Global SCSS: utilities, mixins, themes ├── theming/ # Theming controller and types → #theming/* @@ -633,7 +633,7 @@ Each component has tests in `[component].spec.ts`. They cover: | `helpers.spec.js` | Animation, focus, scroll and style helpers, and `axeReflectedRelationsOptions` | | `fast-check-setup.spec.js` | `fc` with the seed, `SLOW_PROPERTY_RUNS`, `orderedPair` and `withFixture` | | `date-arbitraries.spec.js` | Date arbitraries, wall clocks and `assumeWallClock` for date properties | - | `qr-decoder.spec.js` | `prepareQrDecoder`, which loads the zxing decoder for QR scan specs | + | `qr-decoder.spec.js` | `prepareQrDecoder`, `readQr` for an image and `readQrMatrix` for a QR matrix | Use the simulated events, not `element.click()` or a hand-built `KeyboardEvent`. They send the full event sequence of a real user interaction. @@ -1059,7 +1059,8 @@ edits. ## Specifications -Each public component directory has a `spec.md`: the behavioral contract of the component. +Each public component directory has a `spec.md`: the behavioral contract of the component. An extra that no component +specification covers, such as `src/extras/qr-payloads`, has one too. JSDoc documents one API member. The specification documents the whole component: its purpose, its behavior, its keyboard and assistive technology support, its test coverage, and its limits. diff --git a/CHANGELOG.md b/CHANGELOG.md index ea32dd478..6b66ca26f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - `dot-style`, `square-style` and `corner-dot-style` take `squircle`, a square with soft corners. - `corner-dot-style` sets the shape of the inner corner dots. When you do not set it, the inner corner dots use `dot-style`, as before. - `dot-scale` sets the size of the data modules, from 0.7 to 1 of their cell, to leave a gap between them. The corners keep their full size. + - `createWifiPayload()`, `createVCardPayload()`, `createEpcPayload()` and `createEventPayload()` from `igniteui-webcomponents/extras/qr-payloads` build the value of a code that a phone turns into a Wi-Fi login, a contact card, a SEPA payment or a calendar event. They escape the text and throw a `RangeError` for input that the format does not allow. ### Changed - #### Chip diff --git a/README.md b/README.md index 2d9a1f7fe..ebc21d565 100644 --- a/README.md +++ b/README.md @@ -189,23 +189,11 @@ The condition names are `igc-theme-material`, `igc-theme-bootstrap`, `igc-theme- The extras are opt-in add-ons that build on the public API of the components. A bundle that does not import them does not contain them. Each one has its own entry point, so it needs only its own dependencies. -- `createMarkdownRenderer()` from `igniteui-webcomponents/extras` renders the chat messages from Markdown, with syntax highlighting. It imports the optional peer dependencies `marked` and `dompurify`, and loads `shiki` for the highlighting. -- `bindComboDataSource()` from `igniteui-webcomponents/extras/combo-data-source` binds a combo to a server that searches and pages. It sets `totalItemCount` from the total of the server, so the list shows a placeholder row for each item to load, and `loading` while a search waits or a page loads. - -```ts -import { bindComboDataSource } from 'igniteui-webcomponents/extras/combo-data-source'; - -const binding = bindComboDataSource(combo, { - load: async ({ searchText, caseSensitive, startIndex, count }, signal) => { - const query = `q=${encodeURIComponent(searchText)}&case=${caseSensitive}&skip=${startIndex}&top=${count}`; - const response = await fetch(`/api/cities?${query}`, { signal }); - const { items, total } = await response.json(); - return { items, totalCount: total }; - }, -}); - -binding.dispose(); // removes the listeners, aborts the request in flight and clears `totalItemCount` and `loading` -``` +| Extra | Entry point | Use | +| ----- | ----------- | --- | +| [Chat Markdown renderer](./src/extras/chat-markdown-renderer/README.md) | `igniteui-webcomponents/extras` | Renders the chat messages from Markdown, with syntax highlighting. | +| [Combo data source](./src/extras/combo-data-source/README.md) | `igniteui-webcomponents/extras/combo-data-source` | Binds a combo to a server that searches and pages. | +| [QR payloads](./src/extras/qr-payloads/README.md) | `igniteui-webcomponents/extras/qr-payloads` | Builds QR code values for a Wi-Fi login, a contact card, a SEPA payment and a calendar event. | ## Browser support diff --git a/package.json b/package.json index 270e64c7e..2bfd4ff1a 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,8 @@ ".": "./src/index.js", "./types": "./src/types.js", "./extras": "./src/extras/index.js", - "./extras/combo-data-source": "./src/extras/combo-data-source.js" + "./extras/combo-data-source": "./src/extras/combo-data-source/combo-data-source.js", + "./extras/qr-payloads": "./src/extras/qr-payloads/qr-payloads.js" }, "imports": { "#internals/*.js": "./src/internals/*.ts", diff --git a/scripts/_package.json b/scripts/_package.json index 12067d728..cc4193693 100644 --- a/scripts/_package.json +++ b/scripts/_package.json @@ -16,8 +16,12 @@ "default": "./extras/index.js" }, "./extras/combo-data-source": { - "types": "./extras/combo-data-source.d.ts", - "default": "./extras/combo-data-source.js" + "types": "./extras/combo-data-source/combo-data-source.d.ts", + "default": "./extras/combo-data-source/combo-data-source.js" + }, + "./extras/qr-payloads": { + "types": "./extras/qr-payloads/qr-payloads.d.ts", + "default": "./extras/qr-payloads/qr-payloads.js" } }, "imports": { diff --git a/src/components/qr-code/model/qr-model.property.spec.ts b/src/components/qr-code/model/qr-model.property.spec.ts index 50ee407e9..536e38050 100644 --- a/src/components/qr-code/model/qr-model.property.spec.ts +++ b/src/components/qr-code/model/qr-model.property.spec.ts @@ -1,11 +1,13 @@ import { expect } from '@open-wc/testing'; -import { readBarcodes } from 'zxing-wasm/reader'; import { fc, SLOW_PROPERTY_RUNS, } from '#internals/testing/fast-check-setup.spec.js'; -import { prepareQrDecoder } from '#internals/testing/qr-decoder.spec.js'; +import { + prepareQrDecoder, + readQrMatrix, +} from '#internals/testing/qr-decoder.spec.js'; import type { QrErrorCorrectionLevel } from '../types.js'; import { EC_LEVEL_INDEX, encodeQR } from './encode.js'; import { EC_BLOCKS_TABLE, getDataCodewordsCount } from './error-correction.js'; @@ -98,30 +100,6 @@ function singleModeBits( } } -/** Draws `matrix` with 4 pixels for each module and a quiet zone of 4 modules. */ -function toImageData(matrix: boolean[][]): ImageData { - const scale = 4; - const offset = 4 * scale; - const side = matrix.length * scale + 2 * offset; - const image = new ImageData(side, side); - image.data.fill(255); - - for (const [row, modules] of matrix.entries()) { - for (const [col, dark] of modules.entries()) { - if (!dark) continue; - - for (let y = 0; y < scale; y++) { - const start = (offset + row * scale + y) * side + offset + col * scale; - for (let x = start; x < start + scale; x++) { - image.data.fill(0, x * 4, x * 4 + 3); - } - } - } - } - - return image; -} - describe('QR model properties', () => { before(prepareQrDecoder); @@ -195,12 +173,9 @@ describe('QR model properties', () => { await fc.assert( fc.asyncProperty(anyData, ecLevel, async (value, level) => { const { matrix } = generateQRCodeMatrix(value, level); - const [result] = await readBarcodes(toImageData(matrix), { - formats: ['QRCode'], - maxNumberOfSymbols: 1, - }); - - expect(result?.bytes).to.deep.equal(TEXT_ENCODER.encode(value)); + expect(await readQrMatrix(matrix)).to.deep.equal( + TEXT_ENCODER.encode(value) + ); }), { numRuns: SLOW_PROPERTY_RUNS } ); diff --git a/src/components/qr-code/qr-code.spec.ts b/src/components/qr-code/qr-code.spec.ts index 7ecdcb34f..e6034d96d 100644 --- a/src/components/qr-code/qr-code.spec.ts +++ b/src/components/qr-code/qr-code.spec.ts @@ -7,9 +7,11 @@ import { } from '@open-wc/testing'; import { ifDefined } from 'lit/directives/if-defined.js'; import { restore, type SinonStub, stub } from 'sinon'; -import { readBarcodes } from 'zxing-wasm/reader'; import { defineComponents } from '#internals/definitions/defineComponents.js'; -import { prepareQrDecoder } from '#internals/testing/qr-decoder.spec.js'; +import { + prepareQrDecoder, + readQr, +} from '#internals/testing/qr-decoder.spec.js'; import { asNumber } from '#internals/utils/math.js'; import { configureTheme } from '#theming/config.js'; import IgcQrCodeComponent from './qr-code.js'; @@ -1717,11 +1719,7 @@ describe('IgcQrCodeComponent', () => { const image = await el.toImage({ scale: Math.ceil((6 * modules) / el.size), }); - const [result] = await readBarcodes(image, { - formats: ['QRCode'], - maxNumberOfSymbols: 1, - }); - return result?.text; + return (await readQr(image))?.text; } for (const [index, dotStyle] of SHAPES.entries()) { diff --git a/src/components/qr-code/spec.md b/src/components/qr-code/spec.md index e1541db68..3dc3b43cc 100644 --- a/src/components/qr-code/spec.md +++ b/src/components/qr-code/spec.md @@ -19,6 +19,7 @@ - [Theming colors](#theming-colors) - [Exporting](#exporting) - [Copying to the clipboard](#copying-to-the-clipboard) + - [Payloads](#payloads) - [Programmatic control](#programmatic-control) - [Localization](#localization) - [Keyboard interactions](#keyboard-interactions) @@ -60,12 +61,12 @@ | 5 | 2026-10-20 | `copyToClipboard()`; exports read `size` after the pending render | | 6 | 2026-10-21 | An invalid `version` falls back to the automatic version | | 7 | 2026-11-17 | Shapes, `cornerDotStyle`, `dotScale`, logo cutout and version fit | -| 8 | 2026-11-23 | Mixed-mode segments; UTF-8 without an ECI header | +| 8 | 2026-11-23 | Mixed-mode segments; no ECI header; payload helpers; export holds only the code | ## Overview The `igc-qr-code` renders a scannable QR code as an inline SVG, generated on the client from a string `value`. It -implements the QR model — the data encoding, the error correction and the placement of the modules — internally, +implements the QR model (the data encoding, the error correction and the placement of the modules) internally, with no external QR library and no network request. The component also supports visual customization: the shape of the data modules and of the finder-pattern corners, @@ -87,6 +88,8 @@ authentication setup URLs, contact sharing and linking printed material to digit - **Configurable size and margin**, the second one expressed in modules. - **Export** to an SVG blob, or to a PNG, JPEG, WebP or SVG file, optionally scaled and downloaded. - **Copy to the clipboard** as a PNG or SVG image. +- **Payload helpers** in [`igniteui-webcomponents/extras/qr-payloads`](../../extras/qr-payloads/spec.md) for a Wi-Fi + login, a contact card, a SEPA payment and a calendar event. - **Safe by default**: unsafe logo URL schemes and non-image `data:` URIs are rejected. ### Acceptance criteria @@ -132,6 +135,7 @@ As a developer, I expect to be able to: - theme the colors through CSS custom properties and target the internals through parts; - export the code as a file or a blob, so that it can be printed or stored; - copy the code to the clipboard from a button, without clipboard code of my own; +- encode a Wi-Fi login, a contact card, a SEPA payment or a calendar event without learning its format; - provide a custom `aria-label` for what assistive technology announces. ## Functionality @@ -250,7 +254,7 @@ present. `toImage(options)` exports a file. `scale` multiplies the `size` of the component, `format` takes `png`, `jpeg`, `webp` or `svg`, `fileName` names the file and gets the extension of the format appended, and `download` opens the -browser download dialog. The export waits for pending property changes to render and then reads `size`, so a `size` +browser download dialog. An export holds only the code: a frame or a caption around the element is not part of it. The export waits for pending property changes to render and then reads `size`, so a `size` set right after the call applies to the image. ```ts @@ -286,6 +290,12 @@ The method rejects when the component has no value, on an unsupported format or Clipboard API (an insecure context), and when the browser refuses the write, for example in a document that does not have focus. +#### Payloads + +Scanner apps turn some text formats into an action. `igniteui-webcomponents/extras/qr-payloads` builds the `value` for +a Wi-Fi login, a contact card, a SEPA payment and a calendar event, and escapes the text. See its +[README](../../extras/qr-payloads/README.md) and its [specification](../../extras/qr-payloads/spec.md). + #### Programmatic control ```ts @@ -312,18 +322,18 @@ Not applicable. The component is presentational, is not part of the tab order an | Property | Attribute | Reflected | Type | Default | Description | | ------------- | -------------- | --------- | ----------------------------------- | ------- | ------------------------------------------------------------------------ | -| `value` | `value` | no | `string \| undefined` | — | The value encoded in the QR code. | -| `version` | `version` | no | `number \| undefined` | — | The version, 1 to 40; the smallest fitting one when unset or invalid. | +| `value` | `value` | no | `string \| undefined` | Not set | The value encoded in the QR code. | +| `version` | `version` | no | `number \| undefined` | Not set | The version, 1 to 40; the smallest fitting one when unset or invalid. | | `errorLevel` | `error-level` | no | `"L" \| "M" \| "Q" \| "H"` | `M` | The error correction level. | | `size` | `size` | no | `number` | `128` | The rendered width and height in pixels. | | `margin` | `margin` | no | `number` | `4` | The quiet-zone margin, in modules. | -| `logoSrc` | `logo-src` | no | `string \| undefined` | — | The source of the centered logo image. | +| `logoSrc` | `logo-src` | no | `string \| undefined` | Not set | The source of the centered logo image. | | `logoSize` | `logo-size` | no | `number` | `0.4` | The logo size, as a ratio of the safe area. | -| `logoMargin` | `logo-margin` | no | `number \| undefined` | — | The whitespace around the logo, in pixels. | +| `logoMargin` | `logo-margin` | no | `number \| undefined` | Not set | The whitespace around the logo, in pixels. | | `dotStyle` | `dot-style` | no | `QrDotStyle` | `square`| The shape of the data modules, and of the inner corner dot by default. | | `dotScale` | `dot-scale` | no | `number` | `1` | The size of the data modules, from 0.7 to 1 of their cell. | | `squareStyle` | `square-style` | no | `QrCornerSquareStyle` | `square`| The shape of the outer finder-pattern corner squares. | -| `cornerDotStyle` | `corner-dot-style` | no | `QrCornerDotStyle \| undefined` | — | The shape of the inner corner dots; follows `dotStyle` when unset. | +| `cornerDotStyle` | `corner-dot-style` | no | `QrCornerDotStyle \| undefined` | Not set | The shape of the inner corner dots; follows `dotStyle` when unset. | `QrDotStyle`, `QrCornerSquareStyle` and `QrCornerDotStyle` are `"square" | "circle" | "rounded" | "squircle"`. @@ -374,8 +384,8 @@ None. The SVG is rendered entirely from the properties of the component. | ---------------------------------- | ------- | ---------------------------------------------------------------------------------- | | `--ig-qr-code-background` | `white` | The background color of the code. | | `--ig-qr-code-dark-color` | `black` | The color of the data modules, and of the corners unless they are overridden. | -| `--ig-qr-code-corner-square-color` | — | The color of the outer corner squares; falls back to `--ig-qr-code-dark-color`. | -| `--ig-qr-code-corner-dot-color` | — | The color of the inner corner dots; falls back to `--ig-qr-code-dark-color`. | +| `--ig-qr-code-corner-square-color` | Not set | The color of the outer corner squares; falls back to `--ig-qr-code-dark-color`. | +| `--ig-qr-code-corner-dot-color` | Not set | The color of the inner corner dots; falls back to `--ig-qr-code-dark-color`. | ## Test scenarios @@ -516,8 +526,8 @@ each module. - On 2026-11-17, zxing-cpp did not read some codes of version 8 and above with `square-style="circle"` at some image sizes, with or without a logo. The same codes fail in earlier releases. - The component is presentational: it has no events, no slots and no keyboard interaction. -- `logoSize` is a ratio of the safe area of the resolved error correction level — at most about 9% of the area of - the code — and not of the whole code. +- `logoSize` is a ratio of the safe area of the resolved error correction level (at most about 9% of the area of + the code), not of the whole code. - Logo sources are validated for their scheme and their media type, not for their content. - The application owns a `version` that cannot hold the value, and a value too long for version 40. The component then renders nothing and warns, `toBlob()` and `toImage()` reject with the encoder error, and `copyToClipboard()` @@ -547,5 +557,5 @@ Not applicable. The component renders a static graphic and takes no focus. ### Right to Left support -The layout of a QR code — its finder patterns and its data modules — is fixed by the QR standard and must not be +The layout of a QR code, its finder patterns and its data modules, is fixed by the QR standard and must not be mirrored in a Right-to-Left context. No RTL configuration is required or supported. diff --git a/src/extras/chat-markdown-renderer/README.md b/src/extras/chat-markdown-renderer/README.md new file mode 100644 index 000000000..e6b49e068 --- /dev/null +++ b/src/extras/chat-markdown-renderer/README.md @@ -0,0 +1,69 @@ +# Chat Markdown renderer + +`createMarkdownRenderer()` renders the messages of `igc-chat` from Markdown. It highlights the code blocks with +[shiki](https://shiki.style) and sanitizes the HTML with [DOMPurify](https://github.com/cure53/DOMPurify). + +```ts +import { createMarkdownRenderer } from 'igniteui-webcomponents/extras'; +``` + +## Install + +The renderer uses three optional peer dependencies. Install them in the application: + +```sh +npm install marked dompurify shiki +``` + +The renderer loads shiki only when it highlights code, and only the languages and themes that you give it. + +## Usage + +Give the renderer to the `messageContent` renderer of the chat: + +```ts +const markdown = await createMarkdownRenderer({ + languages: ['typescript', 'html', 'shellscript'], +}); + +chat.options = { + renderers: { + messageContent: ({ message }) => markdown(message), + }, +}; +``` + +The returned function takes a chat message and resolves to a Lit template. It keeps the result for each message object +and converts the message again only when its `text` changes. + +To convert Markdown outside the chat, use `setupMarkdownRenderer()`. Its `parse(text)` resolves to the sanitized HTML, +and its `marked` property gives the [marked](https://marked.js.org) instance for extensions. + +```ts +import { setupMarkdownRenderer } from 'igniteui-webcomponents/extras'; + +const renderer = await setupMarkdownRenderer({ noHighlighter: true }); +const html = await renderer.parse('**Hello**'); +``` + +## Options + +| Option | Type | Default | Description | +| ------------------- | ---------------------------------------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------- | +| `languages` | `string[]` | `['javascript', 'typescript', 'html', 'css']` | The languages to highlight. | +| `theme` | `string \| { light?: string; dark?: string }` | `{ light: 'github-light', dark: 'github-dark' }` | The shiki theme, or one theme for the light mode and one for the dark mode. | +| `noHighlighter` | `boolean` | `false` | Turns off the highlighting, so shiki does not load. | +| `colorReplacements` | `Record` | Not set | Maps the hex colors of the theme to CSS variables, for all themes. | +| `sanitizer` | `(html: string) => string` | DOMPurify | Replaces the sanitizer. It must make the HTML safe, because the chat renders it as is. | + +## Links + +With the default sanitizer, an `http` or `https` link to another origin opens in a new tab, with +`rel="noopener noreferrer"`. Other links open in the same tab. A custom sanitizer gets these attributes on the +Markdown links only. The chat emits `igcNavigate` when the user opens a link, see +[Links in messages](../../components/chat/spec.md#links-in-messages). + +## Code colors + +With the default GitHub themes, CSS variables such as `--shiki-bg` and `--shiki-red` set the colors of the code. See +[Code highlighting](../../components/chat/spec.md#code-highlighting) in the chat specification. diff --git a/src/extras/chat-markdown-renderer.spec.ts b/src/extras/chat-markdown-renderer/chat-markdown-renderer.spec.ts similarity index 99% rename from src/extras/chat-markdown-renderer.spec.ts rename to src/extras/chat-markdown-renderer/chat-markdown-renderer.spec.ts index 0365a9cf6..31d77ad23 100644 --- a/src/extras/chat-markdown-renderer.spec.ts +++ b/src/extras/chat-markdown-renderer/chat-markdown-renderer.spec.ts @@ -1,7 +1,7 @@ import { expect, fixture, html } from '@open-wc/testing'; import DOMPurify from 'dompurify'; import { spy, stub } from 'sinon'; -import type { IgcChatMessage } from '../components/chat/types.js'; +import type { IgcChatMessage } from '../../components/chat/types.js'; import { createMarkdownRenderer, type MarkdownRenderer, diff --git a/src/extras/chat-markdown-renderer.ts b/src/extras/chat-markdown-renderer/chat-markdown-renderer.ts similarity index 99% rename from src/extras/chat-markdown-renderer.ts rename to src/extras/chat-markdown-renderer/chat-markdown-renderer.ts index 35c38a716..233a193a8 100644 --- a/src/extras/chat-markdown-renderer.ts +++ b/src/extras/chat-markdown-renderer/chat-markdown-renderer.ts @@ -3,7 +3,7 @@ import { unsafeHTML } from 'lit/directives/unsafe-html.js'; import { Marked, Renderer, type Tokens } from 'marked'; import type { Highlighter } from 'shiki/bundle/web'; import { getOrInsertComputed } from '#internals/utils/objects.js'; -import type { IgcChatMessage } from '../components/chat/types.js'; +import type { IgcChatMessage } from '../../components/chat/types.js'; const DEFAULT_LANGUAGES = ['javascript', 'typescript', 'html', 'css']; const DEFAULT_THEME = { diff --git a/src/extras/combo-data-source/README.md b/src/extras/combo-data-source/README.md new file mode 100644 index 000000000..52293370d --- /dev/null +++ b/src/extras/combo-data-source/README.md @@ -0,0 +1,71 @@ +# Combo data source + +`bindComboDataSource()` binds an `igc-combo` to a server that searches and pages. The combo then loads its items one +page at a time, while the user scrolls and types. + +```ts +import { bindComboDataSource } from 'igniteui-webcomponents/extras/combo-data-source'; +``` + +## Usage + +Give the binder a `load` function that returns one page: + +```ts +const binding = bindComboDataSource(combo, { + load: async ({ searchText, caseSensitive, startIndex, count }, signal) => { + const query = `q=${encodeURIComponent(searchText)}&case=${caseSensitive}&skip=${startIndex}&top=${count}`; + const response = await fetch(`/api/cities?${query}`, { signal }); + const { items, total } = await response.json(); + return { items, totalCount: total }; + }, +}); +``` + +The binding: + +- sets `filteringOptions.mode` of the combo to `remote`; +- loads the first page when the list opens with no items, and after a pause in the typing; +- loads the next page when the list scrolls to the items that it does not have yet; +- sets `totalItemCount` from `totalCount`, so the list shows a placeholder row for each item to load; +- sets `loading` while a search waits or a page loads; +- aborts the older requests when a new search starts. Pass `signal` to `fetch`. + +A page without `totalCount` keeps the current total, and a next page with no items ends the results. + +## Selected values that are not loaded + +A combo with a `valueKey` can have values whose items are not on a loaded page, such as the values of a saved filter. +Give the binder a `resolve` function that loads these items: + +```ts +bindComboDataSource(combo, { + load: loadPage, + resolve: async (values, signal) => { + const response = await fetch(`/api/cities?ids=${values.join(',')}`, { signal }); + return response.json(); + }, +}); +``` + +It runs when the binding starts, after each load and when the list opens, one time for each value. + +## Options + +The third argument takes these options: + +| Option | Type | Default | Description | +| ------------ | ---------------------------- | ------- | ------------------------------------------------------------------------------------------- | +| `debounce` | `number` | `300` | The pause in the typing, in milliseconds, before a search loads. | +| `pageSize` | `number` | `50` | The smallest number of items that a request loads. | +| `loadOnOpen` | `boolean` | `true` | Whether the first page loads when the user opens the list with no items. | +| `onError` | `(error: unknown) => void` | Not set | Gets the error of a failed request. The combo keeps its items. | + +## Binding + +| Member | Description | +| ----------- | ----------------------------------------------------------------------------------------------------------------- | +| `refresh()` | Loads the first page of the current search text again. Call it after a change of `filteringOptions.caseSensitive` in code, or after `show()`, which emits no events. | +| `dispose()` | Removes the listeners, aborts the requests in flight, gives the combo back its filtering mode, and clears `totalItemCount` and `loading`. | + +See [Remote data](../../components/combo/spec.md#remote-data) in the combo specification and the `RemoteData` story. diff --git a/src/extras/combo-data-source.spec.ts b/src/extras/combo-data-source/combo-data-source.spec.ts similarity index 98% rename from src/extras/combo-data-source.spec.ts rename to src/extras/combo-data-source/combo-data-source.spec.ts index c02beb930..4e7e16b27 100644 --- a/src/extras/combo-data-source.spec.ts +++ b/src/extras/combo-data-source/combo-data-source.spec.ts @@ -13,10 +13,10 @@ import { simulateClick, simulateInput, } from '#internals/testing/simulate.spec.js'; -import IgcComboComponent from '../components/combo/combo.js'; -import { newResultsHints } from '../components/combo/controllers/results-hint.js'; -import type IgcInputComponent from '../components/input/input.js'; -import type IgcVirtualScrollComponent from '../components/virtualization/virtualization.js'; +import IgcComboComponent from '../../components/combo/combo.js'; +import { newResultsHints } from '../../components/combo/controllers/results-hint.js'; +import type IgcInputComponent from '../../components/input/input.js'; +import type IgcVirtualScrollComponent from '../../components/virtualization/virtualization.js'; import { bindComboDataSource, type ComboDataBinding, diff --git a/src/extras/combo-data-source.ts b/src/extras/combo-data-source/combo-data-source.ts similarity index 96% rename from src/extras/combo-data-source.ts rename to src/extras/combo-data-source/combo-data-source.ts index 1b5f1aaab..2afa04689 100644 --- a/src/extras/combo-data-source.ts +++ b/src/extras/combo-data-source/combo-data-source.ts @@ -1,8 +1,8 @@ import { createTimer } from '#internals/timing.js'; -import type IgcComboComponent from '../components/combo/combo.js'; -import { newResultsHints } from '../components/combo/controllers/results-hint.js'; -import type { IgcComboSearchInputEventArgs } from '../components/combo/types.js'; -import type { VirtualScrollDataRequest } from '../components/virtualization/types.js'; +import type IgcComboComponent from '../../components/combo/combo.js'; +import { newResultsHints } from '../../components/combo/controllers/results-hint.js'; +import type { IgcComboSearchInputEventArgs } from '../../components/combo/types.js'; +import type { VirtualScrollDataRequest } from '../../components/virtualization/types.js'; /** A request for one page of the results of a search. */ export interface ComboDataRequest { diff --git a/src/extras/index.ts b/src/extras/index.ts index bbcf52e3d..acb8d0c91 100644 --- a/src/extras/index.ts +++ b/src/extras/index.ts @@ -1 +1 @@ -export * from './chat-markdown-renderer.js'; +export * from './chat-markdown-renderer/chat-markdown-renderer.js'; diff --git a/src/extras/qr-payloads/README.md b/src/extras/qr-payloads/README.md new file mode 100644 index 000000000..aa6b0fc8f --- /dev/null +++ b/src/extras/qr-payloads/README.md @@ -0,0 +1,138 @@ +# QR payloads + +Scanner apps turn some text formats into an action: they join a Wi-Fi network, save a contact, start a payment or add +a calendar event. These helpers build the text for `igc-qr-code`. They escape the special characters, and they throw a +`RangeError` for input that the format does not allow. + +```ts +import { + createEpcPayload, + createEventPayload, + createVCardPayload, + createWifiPayload, +} from 'igniteui-webcomponents/extras/qr-payloads'; + +qrCode.value = createWifiPayload({ ssid: 'Guest Wi-Fi', password: 'welcome;2026' }); +``` + +The helpers are plain functions with no dependencies. A bundle that does not import them does not contain them. + +## Wi-Fi login + +`createWifiPayload()` writes the `WIFI:` format that ZXing defined and phone cameras read. + +```ts +createWifiPayload({ ssid: 'Guest Wi-Fi', password: 'welcome;2026' }); +// WIFI:T:WPA;S:Guest Wi-Fi;P:welcome\;2026;; +``` + +| Option | Type | Default | Description | +| ---------- | -------------------------------------- | ------- | -------------------------------------------------------------- | +| `ssid` | `string` | Required | The name of the network. | +| `password` | `string` | Not set | The password. Required, except for an open network. | +| `security` | `'WPA' \| 'WEP' \| 'SAE' \| 'none'` | `'WPA'` | `WPA` also covers WPA2, and `SAE` is WPA3. | +| `hidden` | `boolean` | `false` | Whether the network hides its name. | + +Enterprise (EAP) networks are not supported, because few phone cameras read them. + +## Contact card + +`createVCardPayload()` writes a vCard 3.0, the version that phone cameras read most reliably. + +```ts +createVCardPayload({ + name: { given: 'Maria', family: 'Ivanova' }, + organization: 'Example Ltd.', + phones: [{ value: '+1 555 0100', type: 'cell' }], + emails: [{ value: 'maria@example.com', type: 'work' }], +}); +``` + +| Option | Type | Description | +| -------------- | ------------------------------------------------------------------------------- | ----------------------------------------------------------------- | +| `name` | `{ given?, family?, prefix?, suffix? }` | The name. At least one part is required. | +| `organization` | `string` | The company. | +| `title` | `string` | The job title. | +| `phones` | `{ value: string; type?: string }[]` | Phone numbers. `type` is a vCard type, such as `cell` or `work`. | +| `emails` | `{ value: string; type?: string }[]` | Email addresses. | +| `url` | `string` | A website. | +| `address` | `{ street?, locality?, region?, postalCode?, country?, type? }` | The postal address. | +| `note` | `string` | A note. | + +There is no photo, because the image data makes a code too large to scan. + +## SEPA payment + +`createEpcPayload()` writes a SEPA credit transfer in the EPC QR format, version 002 with UTF-8. Banking apps in the +euro area read it. + +```ts +createEpcPayload({ + name: 'Example Charity e.V.', + iban: 'DE89 3704 0044 0532 0130 00', + amount: 25, + text: 'Donation 2026', +}); +``` + +| Option | Type | Limit | Description | +| ------------- | -------- | ------------------------ | -------------------------------------------------------------- | +| `name` | `string` | 70 characters | The name of the beneficiary. Required. | +| `iban` | `string` | 34 characters | The IBAN. Required. The helper removes the spaces. | +| `bic` | `string` | 8 or 11 characters | The BIC. Optional in the EEA. | +| `amount` | `number` | 0.01 to 999,999,999.99 | The amount in euros, with up to 2 decimals. | +| `purpose` | `string` | 4 characters | A purpose code, such as `CHAR`. | +| `reference` | `string` | 35 characters | A structured creditor reference. Do not set it with `text`. | +| `text` | `string` | 140 characters | The remittance text. Do not set it with `reference`. | +| `information` | `string` | 70 characters | A note to the payer. | + +The whole payload can have up to 331 bytes. The EPC guideline asks for error correction level M, so keep the default +`error-level` and do not add a logo to a payment code. + +## Calendar event + +`createEventPayload()` writes an iCalendar `VEVENT`. + +```ts +createEventPayload({ + summary: 'Team meetup', + start: new Date(2026, 11, 4, 18), + end: new Date(2026, 11, 4, 21), + location: 'Main hall', +}); +``` + +| Option | Type | Description | +| ------------- | --------- | ----------------------------------------------------------------------------------- | +| `summary` | `string` | The title. | +| `start` | `Date` | The start. Required. | +| `end` | `Date` | The end. For an all-day event, the last day of the event. | +| `allDay` | `boolean` | Whether the event takes whole days. Default `false`. | +| `location` | `string` | The place. | +| `description` | `string` | The details. | + +A timed event is written in UTC, so the phone shows it in its own time zone. An all-day event uses the local dates of +`start` and `end`. + +## Errors + +A helper throws a `RangeError` when the format does not allow the input: an empty network name, an EPC field over its +limit, an amount with 3 decimals, an invalid date and so on. It does not cut a value to fit. It does not check what a +value means, for example the checksum of an IBAN or an email address. + +## Links that open an app + +An email draft, a phone call, a text message or a place on a map needs no helper. `mailto:`, `tel:` and `geo:` are +URLs: encode their text parts with `encodeURIComponent()`. `SMSTO:` is a ZXing convention, not a URL, so its message +stays as it is: + +| Action | Value | +| -------------- | ---------------------------------------------------------------------- | +| Email draft | `` `mailto:support@example.com?subject=${encodeURIComponent(subject)}` `` | +| Phone call | `tel:+15550100` | +| Text message | `SMSTO:+15550100:Table 12 is ready` | +| Place on a map | `geo:42.6977,23.3219` | + +Readers differ in how they fill in a text message, so test such a code on the phones of the users. + +The [specification](./spec.md) describes the formats and the test coverage in full. diff --git a/src/extras/qr-payloads/qr-payloads.property.spec.ts b/src/extras/qr-payloads/qr-payloads.property.spec.ts new file mode 100644 index 000000000..feb8b9af6 --- /dev/null +++ b/src/extras/qr-payloads/qr-payloads.property.spec.ts @@ -0,0 +1,111 @@ +import { expect } from '@open-wc/testing'; + +import { createDate } from '#internals/date/model.js'; +import { fc } from '#internals/testing/fast-check-setup.spec.js'; +import { + createEpcPayload, + createEventPayload, + createVCardPayload, + createWifiPayload, +} from './qr-payloads.js'; + +const text = fc.string({ unit: 'grapheme', minLength: 1, maxLength: 40 }); + +/** Reads a field of a `WIFI:` payload. A `:` in a value is always escaped. */ +function readWifiField(payload: string, key: string): string | undefined { + const match = new RegExp( + `(?:^WIFI:|;)${key}:((?:\\\\[\\s\\S]|[^\\\\;])*);` + ).exec(payload); + return match?.[1].replace(/\\([\s\S])/g, '$1'); +} + +/** Reverses the TEXT escaping of RFC 2426 and RFC 5545. */ +function unescapeText(value: string): string { + return value.replace(/\\([\s\S])/g, (_, char: string) => + char === 'n' ? '\n' : char + ); +} + +const pad = (value: number, length = 2) => String(value).padStart(length, '0'); + +describe('QR payloads properties', () => { + it('gives back the SSID and the password of a Wi-Fi payload', () => { + fc.assert( + fc.property(text, text, fc.boolean(), (ssid, password, hidden) => { + const payload = createWifiPayload({ ssid, password, hidden }); + + expect(readWifiField(payload, 'S')).to.equal(ssid); + expect(readWifiField(payload, 'P')).to.equal(password); + expect(readWifiField(payload, 'H')).to.equal( + hidden ? 'true' : undefined + ); + }) + ); + }); + + it('keeps each vCard value on its line and gives the text back', () => { + fc.assert( + fc.property(text, text, (organization, note) => { + const lines = createVCardPayload({ + name: { given: 'A' }, + organization, + note, + }).split('\r\n'); + const value = (key: string) => + unescapeText( + lines + .find((line) => line.startsWith(`${key}:`))! + .slice(key.length + 1) + ); + + expect(lines.every((line) => !/[\r\n]/.test(line))).to.be.true; + expect(value('ORG')).to.equal(organization.replace(/\r\n|\r/g, '\n')); + expect(value('NOTE')).to.equal(note.replace(/\r\n|\r/g, '\n')); + }) + ); + }); + + it('writes any amount in whole cents exactly', () => { + fc.assert( + fc.property(fc.integer({ min: 1, max: 99_999_999_999 }), (cents) => { + const line = createEpcPayload({ + name: 'A', + iban: 'X', + amount: cents / 100, + }).split('\n')[7]; + + expect(line).to.equal( + `EUR${Math.trunc(cents / 100)}.${pad(cents % 100)}` + ); + }) + ); + }); + + it('writes a timed event in UTC and an all-day event on its local dates', () => { + const date = fc.date({ + min: new Date(Date.UTC(1, 0, 2)), + max: new Date(Date.UTC(9999, 11, 30)), + noInvalidDate: true, + }); + + fc.assert( + fc.property(date, (start) => { + const timed = createEventPayload({ start }); + const allDay = createEventPayload({ start, end: start, allDay: true }); + const next = createDate( + start.getFullYear(), + start.getMonth(), + start.getDate() + 1 + ); + const local = (day: Date) => + `${pad(day.getFullYear(), 4)}${pad(day.getMonth() + 1)}${pad(day.getDate())}`; + + expect(timed).to.contain( + `DTSTART:${pad(start.getUTCFullYear(), 4)}${pad(start.getUTCMonth() + 1)}${pad(start.getUTCDate())}T${pad(start.getUTCHours())}${pad(start.getUTCMinutes())}${pad(start.getUTCSeconds())}Z` + ); + expect(allDay).to.contain(`DTSTART;VALUE=DATE:${local(start)}`); + expect(allDay).to.contain(`DTEND;VALUE=DATE:${local(next)}`); + }) + ); + }); +}); diff --git a/src/extras/qr-payloads/qr-payloads.spec.ts b/src/extras/qr-payloads/qr-payloads.spec.ts new file mode 100644 index 000000000..8d6e4e64a --- /dev/null +++ b/src/extras/qr-payloads/qr-payloads.spec.ts @@ -0,0 +1,359 @@ +import { expect } from '@open-wc/testing'; + +import { createDate } from '#internals/date/model.js'; +import { + prepareQrDecoder, + readQrMatrix, +} from '#internals/testing/qr-decoder.spec.js'; +import { generateQRCodeMatrix } from '../../components/qr-code/model/matrix.js'; +import { + createEpcPayload, + createEventPayload, + createVCardPayload, + createWifiPayload, +} from './qr-payloads.js'; + +const crlf = (...lines: string[]) => lines.join('\r\n'); + +describe('QR payloads', () => { + describe('Wi-Fi', () => { + it('builds a WPA payload by default', () => { + expect(createWifiPayload({ ssid: 'Home', password: 'secret' })).to.equal( + 'WIFI:T:WPA;S:Home;P:secret;;' + ); + }); + + it('writes the security type and a hidden network', () => { + expect( + createWifiPayload({ + ssid: 'Lab', + password: 'k3y', + security: 'SAE', + hidden: true, + }) + ).to.equal('WIFI:T:SAE;S:Lab;P:k3y;H:true;;'); + expect( + createWifiPayload({ ssid: 'Old', password: 'abc', security: 'WEP' }) + ).to.equal('WIFI:T:WEP;S:Old;P:abc;;'); + }); + + it('writes an open network without a password', () => { + expect( + createWifiPayload({ ssid: 'Cafe', password: 'x', security: 'none' }) + ).to.equal('WIFI:T:nopass;S:Cafe;;'); + }); + + it('escapes the special characters without quotes', () => { + expect( + createWifiPayload({ ssid: 'a;b,c:d"e\\f', password: '"12345678"' }) + ).to.equal(String.raw`WIFI:T:WPA;S:a\;b\,c\:d\"e\\f;P:\"12345678\";;`); + }); + + it('throws for an empty SSID or a missing password', () => { + expect(() => createWifiPayload({ ssid: '', password: 'x' })).to.throw( + RangeError + ); + expect(() => createWifiPayload({ ssid: 'Home' })).to.throw(RangeError); + expect(() => + createWifiPayload({ ssid: 'Home', password: '', security: 'WEP' }) + ).to.throw(RangeError); + }); + }); + + describe('vCard', () => { + it('builds a vCard 3.0 with CRLF line ends', () => { + expect( + createVCardPayload({ + name: { given: 'Maria', family: 'Ivanova', prefix: 'Dr.' }, + organization: 'Infragistics', + title: 'Engineer', + phones: [{ value: '+1 555 0100', type: 'cell' }], + emails: [ + { value: 'maria@example.com', type: 'work' }, + { value: 'maria@home.example' }, + ], + url: 'https://example.com/?a=1,b=2;c', + address: { + street: '1 Main St', + locality: 'Springfield', + postalCode: '12345', + country: 'USA', + type: 'work', + }, + note: 'Met at the expo', + }) + ).to.equal( + crlf( + 'BEGIN:VCARD', + 'VERSION:3.0', + 'N:Ivanova;Maria;;Dr.;', + 'FN:Dr. Maria Ivanova', + 'ORG:Infragistics', + 'TITLE:Engineer', + 'TEL;TYPE=cell:+1 555 0100', + 'EMAIL;TYPE=work:maria@example.com', + 'EMAIL:maria@home.example', + 'URL:https://example.com/?a=1,b=2;c', + 'ADR;TYPE=work:;;1 Main St;Springfield;;12345;USA', + 'NOTE:Met at the expo', + 'END:VCARD' + ) + ); + }); + + it('leaves out the fields that are not set', () => { + expect(createVCardPayload({ name: { family: 'Lee' } })).to.equal( + crlf('BEGIN:VCARD', 'VERSION:3.0', 'N:Lee;;;;', 'FN:Lee', 'END:VCARD') + ); + }); + + it('escapes the text values and their line breaks', () => { + const card = createVCardPayload({ + name: { given: 'A;B', family: 'C,D' }, + organization: 'R&D\\Labs', + note: 'Line 1\r\nLine 2\nLine 3', + }); + + expect(card).to.contain(String.raw`N:C\,D;A\;B;;;`); + expect(card).to.contain(String.raw`FN:A\;B C\,D`); + expect(card).to.contain(String.raw`ORG:R&D\\Labs`); + expect(card).to.contain(String.raw`NOTE:Line 1\nLine 2\nLine 3`); + }); + + it('throws for an empty name, a bad type and a line break in a raw value', () => { + expect(() => createVCardPayload({ name: {} })).to.throw(RangeError); + expect(() => + createVCardPayload({ + name: { given: 'A' }, + phones: [{ value: '1', type: 'cell;x' }], + }) + ).to.throw(RangeError); + expect(() => + createVCardPayload({ + name: { given: 'A' }, + phones: [{ value: '1\n2' }], + }) + ).to.throw(RangeError); + expect(() => + createVCardPayload({ name: { given: 'A' }, url: 'https://a\r\nb' }) + ).to.throw(RangeError); + }); + }); + + describe('EPC', () => { + it('builds a version 002 payload in UTF-8', () => { + expect( + createEpcPayload({ + name: 'Red Cross of Belgium', + iban: 'BE72 0000 0000 1616', + bic: 'BPOT BEB1', + amount: 1, + purpose: 'CHAR', + text: 'Urgency fund', + information: 'Sample EPC QR code', + }) + ).to.equal( + [ + 'BCD', + '002', + '1', + 'SCT', + 'BPOTBEB1', + 'Red Cross of Belgium', + 'BE72000000001616', + 'EUR1.00', + 'CHAR', + '', + 'Urgency fund', + 'Sample EPC QR code', + ].join('\n') + ); + }); + + it('keeps the empty fields as empty lines', () => { + expect( + createEpcPayload({ name: 'Shop', iban: 'DE02120300000000202051' }) + ).to.equal( + // The amount, purpose, reference, text and information lines are empty. + [ + 'BCD', + '002', + '1', + 'SCT', + '', + 'Shop', + 'DE02120300000000202051', + '', + '', + '', + '', + '', + ].join('\n') + ); + }); + + it('writes the amount in euros with 2 decimals', () => { + const amount = (value: number) => + createEpcPayload({ name: 'A', iban: 'X', amount: value }).split( + '\n' + )[7]; + + expect(amount(12.3)).to.equal('EUR12.30'); + expect(amount(0.1 + 0.2)).to.equal('EUR0.30'); + expect(amount(0.01)).to.equal('EUR0.01'); + expect(amount(134_217_782.86)).to.equal('EUR134217782.86'); + expect(amount(999_999_999.99)).to.equal('EUR999999999.99'); + }); + + it('throws for an amount out of range or with more than 2 decimals', () => { + for (const amount of [0, 0.001, 12.345, 1e9, -5, Number.NaN]) { + expect( + () => createEpcPayload({ name: 'A', iban: 'X', amount }), + String(amount) + ).to.throw(RangeError); + } + }); + + it('throws for a field over its limit or with a line break', () => { + const base = { name: 'A', iban: 'X' }; + + for (const options of [ + { ...base, name: '' }, + { ...base, iban: ' ' }, + { ...base, name: 'n'.repeat(71) }, + { ...base, iban: 'I'.repeat(35) }, + { ...base, bic: 'ABCDEFGHI' }, + { ...base, purpose: 'ABCDE' }, + { ...base, reference: 'r'.repeat(36) }, + { ...base, text: 't'.repeat(141) }, + { ...base, information: 'i'.repeat(71) }, + { ...base, text: 'two\nlines' }, + { ...base, reference: 'RF18', text: 'and a text' }, + ]) { + expect( + () => createEpcPayload(options), + JSON.stringify(options) + ).to.throw(RangeError); + } + }); + + it('counts the limits in characters and the payload in bytes', () => { + // 70 characters of 2 bytes each fit the name limit. + expect(() => + createEpcPayload({ name: 'ä'.repeat(70), iban: 'X' }) + ).not.to.throw(); + // 140 + 70 + 70 characters of 2 bytes each are over 331 bytes. + expect(() => + createEpcPayload({ + name: 'ä'.repeat(70), + iban: 'X', + text: 'ä'.repeat(140), + information: 'ä'.repeat(70), + }) + ).to.throw(RangeError); + }); + }); + + describe('Calendar event', () => { + it('writes a timed event in UTC', () => { + expect( + createEventPayload({ + summary: 'Launch', + start: new Date(Date.UTC(2026, 11, 24, 18, 0, 0)), + end: new Date(Date.UTC(2026, 11, 24, 19, 30, 5)), + location: 'Hall 2', + description: 'Doors open at 17:30', + }) + ).to.equal( + crlf( + 'BEGIN:VEVENT', + 'SUMMARY:Launch', + 'DTSTART:20261224T180000Z', + 'DTEND:20261224T193005Z', + 'LOCATION:Hall 2', + 'DESCRIPTION:Doors open at 17:30', + 'END:VEVENT' + ) + ); + }); + + it('writes an all-day event with the local dates and an exclusive end', () => { + expect( + createEventPayload({ + start: new Date(2026, 11, 30), + end: new Date(2026, 11, 31, 23, 59), + allDay: true, + }) + ).to.equal( + crlf( + 'BEGIN:VEVENT', + 'DTSTART;VALUE=DATE:20261230', + 'DTEND;VALUE=DATE:20270101', + 'END:VEVENT' + ) + ); + }); + + it('writes a year below 100 with 4 digits', () => { + expect( + createEventPayload({ start: createDate(50), allDay: true }) + ).to.contain('DTSTART;VALUE=DATE:00500101'); + }); + + it('escapes the text values', () => { + expect( + createEventPayload({ + summary: 'Party; bring snacks, drinks', + start: new Date(Date.UTC(2026, 0, 1)), + description: 'A\\B\nC', + }) + ) + .to.contain(String.raw`SUMMARY:Party\; bring snacks\, drinks`) + .and.to.contain(String.raw`DESCRIPTION:A\\B\nC`); + }); + + it('throws for an invalid date or a year over 9999', () => { + expect(() => + createEventPayload({ start: new Date(Number.NaN) }) + ).to.throw(RangeError); + expect(() => + createEventPayload({ + start: new Date(2026, 0, 1), + end: new Date(Date.UTC(10_000, 0, 1)), + }) + ).to.throw(RangeError); + }); + }); + + describe('Scanning', () => { + before(prepareQrDecoder); + + it('gives a decoder each payload back', async () => { + const encoder = new TextEncoder(); + + for (const payload of [ + createWifiPayload({ ssid: 'Guest; Wi-Fi', password: 'welcome:2026' }), + createVCardPayload({ + name: { given: 'Mária', family: 'Ivanova' }, + phones: [{ value: '+1 555 0100' }], + note: 'Two\nlines', + }), + createEpcPayload({ + name: 'Red Cross of Belgium', + iban: 'BE72000000001616', + amount: 1, + text: 'Urgency fund', + }), + createEventPayload({ + summary: 'Launch, part 2', + start: new Date(Date.UTC(2026, 11, 24, 18)), + }), + ]) { + const { matrix } = generateQRCodeMatrix(payload, 'M'); + expect(await readQrMatrix(matrix), payload).to.deep.equal( + encoder.encode(payload) + ); + } + }); + }); +}); diff --git a/src/extras/qr-payloads/qr-payloads.ts b/src/extras/qr-payloads/qr-payloads.ts new file mode 100644 index 000000000..46b836483 --- /dev/null +++ b/src/extras/qr-payloads/qr-payloads.ts @@ -0,0 +1,332 @@ +import { isValidDate } from '#internals/date/converters.js'; + +/** + * Builders for the text of QR codes that scanner apps turn into an action: a Wi-Fi login, a + * contact card, a SEPA payment and a calendar event. + */ + +export interface WifiPayloadOptions { + /** The name of the network. */ + ssid: string; + /** The password. Required, except for an open network, which ignores it. */ + password?: string; + /** + * The security of the network. `'WPA'` also covers WPA2, and `'SAE'` is WPA3. + * @default 'WPA' + */ + security?: 'WPA' | 'WEP' | 'SAE' | 'none'; + /** Whether the network hides its name. */ + hidden?: boolean; +} + +/** A phone number or an email address of a contact card. */ +export interface VCardContact { + /** The phone number or the email address. */ + value: string; + /** A vCard type, such as `'work'`, `'home'` or `'cell'`. */ + type?: string; +} + +/** The postal address of a contact card. */ +export interface VCardAddress { + /** The street and the number. */ + street?: string; + /** The city or the town. */ + locality?: string; + /** The state or the province. */ + region?: string; + postalCode?: string; + country?: string; + /** A vCard type, such as `'work'` or `'home'`. */ + type?: string; +} + +export interface VCardPayloadOptions { + /** The name of the contact. At least one part is required. */ + name: { given?: string; family?: string; prefix?: string; suffix?: string }; + /** The company. */ + organization?: string; + /** The job title. */ + title?: string; + phones?: VCardContact[]; + emails?: VCardContact[]; + /** A website. */ + url?: string; + address?: VCardAddress; + note?: string; +} + +export interface EpcPayloadOptions { + /** The name of the beneficiary, up to 70 characters. */ + name: string; + /** The IBAN of the beneficiary, up to 34 characters without the spaces. */ + iban: string; + /** The BIC of the bank, 8 or 11 characters. Optional in the EEA. */ + bic?: string; + /** The amount in euros, from 0.01 to 999,999,999.99, with up to 2 decimals. */ + amount?: number; + /** The purpose code, up to 4 characters, such as `'CHAR'`. */ + purpose?: string; + /** A structured creditor reference, up to 35 characters. Not together with `text`. */ + reference?: string; + /** The remittance text, up to 140 characters. Not together with `reference`. */ + text?: string; + /** A note to the payer, up to 70 characters. */ + information?: string; +} + +export interface EventPayloadOptions { + /** The title of the event. */ + summary?: string; + /** The start of the event. */ + start: Date; + /** The end of the event. For an all-day event, its last day. */ + end?: Date; + /** Whether the event takes whole days, on the local dates of `start` and `end`. */ + allDay?: boolean; + /** The place of the event. */ + location?: string; + /** The details of the event. */ + description?: string; +} + +const LINE_BREAK = /[\r\n]/; +const EPC_MAX_BYTES = 331; + +function assert(condition: unknown, message: string): asserts condition { + if (!condition) { + throw new RangeError(message); + } +} + +function assertSingleLine(value: string, label: string): string { + assert(!LINE_BREAK.test(value), `The ${label} cannot hold a line break.`); + return value; +} + +function escapeWifi(value: string): string { + return value.replace(/[\\;,:"]/g, '\\$&'); +} + +/** Escapes a text value of a vCard or an iCalendar event (RFC 2426, RFC 5545). */ +function escapeText(value = ''): string { + return value + .replace(/[\\;,]/g, '\\$&') + .replace(/\r\n|\r|\n/g, String.raw`\n`); +} + +/** Returns a structured vCard value: escaped text parts joined with `;`. */ +function compound(...parts: (string | undefined)[]): string { + return parts.map((part) => escapeText(part)).join(';'); +} + +function textLine(key: string, value: string | undefined): string | undefined { + return value ? `${key}:${escapeText(value)}` : undefined; +} + +/** Joins the lines that have a value with CRLF. */ +function joinLines(lines: (string | undefined)[]): string { + return lines.filter(Boolean).join('\r\n'); +} + +function vCardKey(key: string, type: string | undefined): string { + assert( + !type || /^[a-z\d-]+$/i.test(type), + `"${type}" is not a vCard type: use letters, digits and hyphens.` + ); + return type ? `${key};TYPE=${type}` : key; +} + +function epcField(label: string, value: string, max: number): string { + assert( + Array.from(value).length <= max, + `The EPC ${label} has more than ${max} characters.` + ); + return assertSingleLine(value, `EPC ${label}`); +} + +function pad(value: number, length = 2): string { + return String(value).padStart(length, '0'); +} + +/** + * Returns a `WIFI:` payload, the format that ZXing defined and phone cameras read. + * + * @throws {RangeError} When a value breaks a rule of the format. + */ +export function createWifiPayload({ + ssid, + password = '', + security = 'WPA', + hidden = false, +}: WifiPayloadOptions): string { + const open = security === 'none'; + + assert(ssid, 'A Wi-Fi payload needs an SSID.'); + assert(open || password, `A ${security} network needs a password.`); + + return [ + `WIFI:T:${open ? 'nopass' : security};S:${escapeWifi(ssid)};`, + open ? '' : `P:${escapeWifi(password)};`, + hidden ? 'H:true;' : '', + ';', + ].join(''); +} + +/** + * Returns a contact card in the vCard 3.0 format (RFC 2426). + * + * @throws {RangeError} When a value breaks a rule of the format. + */ +export function createVCardPayload({ + name: { given, family, prefix, suffix }, + organization, + title, + phones = [], + emails = [], + url, + address, + note, +}: VCardPayloadOptions): string { + const fullName = [prefix, given, family, suffix].filter(Boolean).join(' '); + + assert(fullName, 'A vCard payload needs a name.'); + + return joinLines([ + 'BEGIN:VCARD', + 'VERSION:3.0', + `N:${compound(family, given, '', prefix, suffix)}`, + textLine('FN', fullName), + textLine('ORG', organization), + textLine('TITLE', title), + // A phone number and a URL are not text values, so they are not escaped. + ...phones.map( + ({ value, type }) => + `${vCardKey('TEL', type)}:${assertSingleLine(value, 'vCard phone number')}` + ), + ...emails.map( + ({ value, type }) => `${vCardKey('EMAIL', type)}:${escapeText(value)}` + ), + url && `URL:${assertSingleLine(url, 'vCard URL')}`, + address && + `${vCardKey('ADR', address.type)}:${compound( + '', + '', + address.street, + address.locality, + address.region, + address.postalCode, + address.country + )}`, + textLine('NOTE', note), + 'END:VCARD', + ]); +} + +/** + * Returns a SEPA credit transfer in the EPC QR format, version 002 with UTF-8 (EPC069-12). The + * guideline asks for error correction level M, so keep the default level and do not add a logo. + * + * @throws {RangeError} When a value breaks a rule of the format. + */ +export function createEpcPayload({ + name, + iban, + bic = '', + amount, + purpose = '', + reference = '', + text = '', + information = '', +}: EpcPayloadOptions): string { + const compactIban = iban.replace(/\s/g, ''); + const compactBic = bic.replace(/\s/g, ''); + + assert(name, 'An EPC payload needs the name of the beneficiary.'); + assert(compactIban, 'An EPC payload needs an IBAN.'); + assert( + [0, 8, 11].includes(compactBic.length), + 'The EPC BIC must have 8 or 11 characters.' + ); + assert( + !(reference && text), + 'An EPC payload takes a reference or a text, not both.' + ); + + let euros = ''; + if (amount !== undefined) { + const cents = Math.round(amount * 100); + assert( + Number.isFinite(amount) && + // The float error of `amount * 100` grows with the amount. + Math.abs(amount * 100 - cents) <= cents * Number.EPSILON * 4 && + cents >= 1 && + cents <= 99_999_999_999, + 'The EPC amount must be from 0.01 to 999999999.99 euros, with up to 2 decimals.' + ); + euros = `EUR${(cents / 100).toFixed(2)}`; + } + + const payload = [ + 'BCD', + '002', + '1', + 'SCT', + compactBic, + epcField('name', name, 70), + epcField('IBAN', compactIban, 34), + euros, + epcField('purpose', purpose, 4), + epcField('reference', reference, 35), + epcField('text', text, 140), + epcField('information', information, 70), + ].join('\n'); + + assert( + new TextEncoder().encode(payload).length <= EPC_MAX_BYTES, + `An EPC payload can have up to ${EPC_MAX_BYTES} bytes.` + ); + return payload; +} + +/** + * Returns a calendar event as an iCalendar `VEVENT` (RFC 5545), without the `VCALENDAR` + * wrapper, as scanner apps read it. A timed event is in UTC. + * + * @throws {RangeError} When a value breaks a rule of the format. + */ +export function createEventPayload({ + summary, + start, + end, + allDay = false, + location, + description, +}: EventPayloadOptions): string { + /** Returns the parameters and the value of a date property. */ + const dateValue = (value: Date, days = 0) => { + assert(isValidDate(value), 'An event date must be a valid date.'); + + // `setDate`, because `new Date(year, …)` reads the years 0-99 as 1900-1999. + const day = new Date(value); + day.setDate(day.getDate() + days); + const year = allDay ? day.getFullYear() : value.getUTCFullYear(); + + assert(year >= 0 && year <= 9999, 'An event year must be from 0 to 9999.'); + + return allDay + ? `;VALUE=DATE:${pad(year, 4)}${pad(day.getMonth() + 1)}${pad(day.getDate())}` + : `:${value.toISOString().replace(/[-:]|\.\d{3}/g, '')}`; + }; + + return joinLines([ + 'BEGIN:VEVENT', + textLine('SUMMARY', summary), + `DTSTART${dateValue(start)}`, + // The end date of an all-day event is the day after the event. + end && `DTEND${dateValue(end, 1)}`, + textLine('LOCATION', location), + textLine('DESCRIPTION', description), + 'END:VEVENT', + ]); +} diff --git a/src/extras/qr-payloads/spec.md b/src/extras/qr-payloads/spec.md new file mode 100644 index 000000000..9253d1a7c --- /dev/null +++ b/src/extras/qr-payloads/spec.md @@ -0,0 +1,294 @@ +# QR payloads specification + +- [QR payloads specification](#qr-payloads-specification) + - [Revision history](#revision-history) + - [Overview](#overview) + - [Key features](#key-features) + - [Acceptance criteria](#acceptance-criteria) + - [User stories](#user-stories) + - [End-user stories](#end-user-stories) + - [Developer stories](#developer-stories) + - [Functionality](#functionality) + - [End-user experience](#end-user-experience) + - [Developer experience](#developer-experience) + - [Wi-Fi login](#wi-fi-login) + - [Contact card](#contact-card) + - [SEPA payment](#sepa-payment) + - [Calendar event](#calendar-event) + - [Errors](#errors) + - [Links that open an app](#links-that-open-an-app) + - [Localization](#localization) + - [Keyboard interactions](#keyboard-interactions) + - [API](#api) + - [Functions](#functions) + - [Types](#types) + - [Test scenarios](#test-scenarios) + - [Wi-Fi](#wi-fi) + - [vCard](#vcard) + - [EPC](#epc) + - [Calendar event](#calendar-event-1) + - [Scanning](#scanning) + - [QR payloads properties](#qr-payloads-properties) + - [Not covered by the suite](#not-covered-by-the-suite) + - [Assumptions and limitations](#assumptions-and-limitations) + - [Accessibility](#accessibility) + - [ARIA roles and properties](#aria-roles-and-properties) + - [Keyboard support](#keyboard-support) + - [Right to Left support](#right-to-left-support) + +## Revision history + +| Version | Date | Notes | +| ------: | ---------- | --------------------- | +| 1 | 2026-11-23 | Initial specification | + +## Overview + +`igniteui-webcomponents/extras/qr-payloads` builds the text of a QR code in a format that a scanner app turns into an +action: a Wi-Fi login, a contact card, a SEPA credit transfer or a calendar event. The application sets the text as +the `value` of an [`igc-qr-code`](../../components/qr-code/spec.md). The helpers are plain functions with no +dependencies, in an entry point of their own, so a bundle that does not import them does not contain them. + +### Key features + +- **Four formats**: `WIFI:`, vCard 3.0, EPC QR version 002 and an iCalendar `VEVENT`. +- **Escaping** of the special characters of each format. +- **Strict input**: a `RangeError` for input that the format does not allow, never a silent cut. +- **No dependencies** and no network request. + +### Acceptance criteria + +- Each helper must return the text of its format for valid input, with the special characters escaped. +- Each helper must throw a `RangeError` for input that its format does not allow, and must not change a value to make + it fit. +- A helper must not check what a value means, such as the checksum of an IBAN or the address of an email. +- A decoder must read each payload back from its code unchanged. + +## User stories + +### End-user stories + +As an end-user, I expect to be able to: + +- scan a code and join a Wi-Fi network without typing its password; +- scan a code and save a contact with its name, phone numbers and addresses; +- scan a code on an invoice and get a payment form that my banking app fills in; +- scan a code and add an event to my calendar at the correct time in my time zone. + +### Developer stories + +As a developer, I expect to be able to: + +- build these codes without learning their formats; +- trust that a special character in a name or a password does not break the code; +- get an error at once for input that would make a code that a scanner rejects. + +## Functionality + +### End-user experience + +None applicable. The helpers return text. The end-user sees the code that `igc-qr-code` renders from it, and the action +of the scanner app. + +### Developer experience + +#### Wi-Fi login + +`createWifiPayload()` writes the `WIFI:` format that ZXing defined and phone cameras read: + +```text +WIFI:T:;S:;P:;H:true;; +``` + +- `T` is `WPA` (also WPA2, the default), `WEP`, `SAE` (WPA3) or `nopass` for `security: 'none'`. +- An open network has no `P` field, and the helper ignores `password` for it. +- `H:true` marks a hidden network. A visible network has no `H` field. +- The helper escapes `\`, `;`, `,`, `:` and `"` with a backslash. It does not put quotes around a value, because + readers differ in how they read quotes. + +#### Contact card + +`createVCardPayload()` writes a vCard 3.0 (RFC 2426) with CRLF line ends, in this order: `BEGIN`, `VERSION`, `N`, `FN`, +`ORG`, `TITLE`, one `TEL` for each phone, one `EMAIL` for each email address, `URL`, `ADR`, `NOTE` and `END`. A field +that is not set has no line. + +- `N` holds the family name, the given name, an empty additional name, the prefix and the suffix. `FN` joins the + prefix, the given name, the family name and the suffix with spaces. +- A text value escapes `\`, `,` and `;` with a backslash, and writes a line break as `\n`. +- A phone number and a URL are not text values in vCard 3.0, so they are not escaped. +- A `type` becomes a `TYPE` parameter, for example `TEL;TYPE=cell`. +- `ADR` holds an empty post office box, an empty extended address, the street, the locality, the region, the postal + code and the country. +- The lines are not folded at 75 octets: folding is optional, and it adds bytes to the code. + +#### SEPA payment + +`createEpcPayload()` writes a SEPA credit transfer in the EPC QR format (EPC069-12), with LF line ends: + +| Line | Content | +| ---: | ------------------------------------------- | +| 1 | `BCD` | +| 2 | `002`, the version with an optional BIC | +| 3 | `1`, the UTF-8 character set | +| 4 | `SCT` | +| 5 | The BIC, or empty | +| 6 | The name of the beneficiary | +| 7 | The IBAN | +| 8 | The amount, such as `EUR25.00`, or empty | +| 9 | The purpose code, or empty | +| 10 | The structured reference, or empty | +| 11 | The remittance text, or empty | +| 12 | The information to the payer, or empty | + +- The helper removes the spaces of the IBAN and the BIC. +- It writes the amount with 2 decimals. It accepts a sum that floating point makes inexact, such as `0.1 + 0.2`. +- It keeps the empty lines, so the payload always has 12 lines. +- The length limits count characters (code points), and the whole payload can have up to 331 bytes: the byte + capacity of a version 13 code at level M. +- The EPC guideline asks for error correction level M. The application keeps the default `error-level` of the code and + does not add a logo. The helper cannot check this. + +#### Calendar event + +`createEventPayload()` writes an iCalendar `VEVENT` (RFC 5545) with CRLF line ends, in this order: `BEGIN`, `SUMMARY`, +`DTSTART`, `DTEND`, `LOCATION`, `DESCRIPTION` and `END`. It has no `VCALENDAR` wrapper and no `UID` or `DTSTAMP`, +because scanner apps read the event without them, and they add bytes. + +- A timed event is in UTC, such as `DTSTART:20261224T180000Z`, so the phone shows it in its own time zone and the + code does not depend on time zone data. +- An all-day event uses the local dates of `start` and `end`, such as `DTSTART;VALUE=DATE:20261224`. `end` is the last + day of the event, and the helper writes the day after it, because the end date of the format is exclusive. +- A text value escapes `\`, `;` and `,` with a backslash, and writes a line break as `\n`. +- The lines are not folded. + +#### Errors + +A helper throws a `RangeError` when: + +- **Wi-Fi**: `ssid` is empty, or `password` is empty for a secured network; +- **vCard**: the name has no part, a `type` has a character other than a letter, a digit or a hyphen, or a phone + number or the URL has a line break; +- **EPC**: `name` or the IBAN is empty, a field is longer than its limit or has a line break, the BIC does not have 8 + or 11 characters, the amount is out of range or has more than 2 decimals, both `reference` and `text` are set, or + the payload is over 331 bytes; +- **Calendar event**: `start` or `end` is not a valid date, or its year is not from 0 to 9999. + +#### Links that open an app + +An email draft, a phone call, a text message and a place on a map need no helper. The +[README](./README.md#links-that-open-an-app) gives the recipes: the `mailto:`, `tel:` and `geo:` URLs, and the `SMSTO:` +convention of ZXing, whose message is not percent-encoded. + +### Localization + +None applicable. The helpers write the text that the application gives them. The formats have no localized words. + +### Keyboard interactions + +None applicable. + +## API + +### Functions + +| Function | Signature | Description | +| -------------------- | ----------------------------------------------- | ------------------------------------------------------- | +| `createWifiPayload` | `(options: WifiPayloadOptions) => string` | Returns a `WIFI:` payload, the format that ZXing defined and phone cameras read. | +| `createVCardPayload` | `(options: VCardPayloadOptions) => string` | Returns a contact card in the vCard 3.0 format (RFC 2426). | +| `createEpcPayload` | `(options: EpcPayloadOptions) => string` | Returns a SEPA credit transfer in the EPC QR format, version 002 with UTF-8 (EPC069-12). | +| `createEventPayload` | `(options: EventPayloadOptions) => string` | Returns a calendar event as an iCalendar `VEVENT` (RFC 5545), without the `VCALENDAR` wrapper. | + +### Types + +Each function takes one options interface: `WifiPayloadOptions`, `VCardPayloadOptions` (with `VCardContact` and +`VCardAddress`), `EpcPayloadOptions` and `EventPayloadOptions`. The [README](./README.md) lists their options, +defaults and limits. + +## Test scenarios + +| Suite | File | +| ------------------------ | ---------------------------------------------------------------- | +| `QR payloads` | [`qr-payloads.spec.ts`](./qr-payloads.spec.ts) | +| `QR payloads properties` | [`qr-payloads.property.spec.ts`](./qr-payloads.property.spec.ts) | + +### Wi-Fi + +1. The payload is WPA by default. +2. It writes the security type and a hidden network. +3. It writes an open network without a password. +4. It escapes `\ ; , : "` without quotes. +5. It throws for an empty SSID and for a secured network without a password. + +### vCard + +6. The payload is a vCard 3.0 with CRLF line ends, with all the fields in order. +7. It leaves out the fields that are not set. +8. It escapes the text values and their line breaks. +9. It throws for an empty name, a type that is not a vCard token, and a line break in a phone number or a URL. + +### EPC + +10. The payload is version 002 in UTF-8, with the spaces of the IBAN and the BIC removed. +11. It keeps the empty fields as empty lines. +12. It writes the amount in euros with 2 decimals, also for `0.1 + 0.2` and for an amount over 2^27 euros. +13. It throws for an amount out of range or with more than 2 decimals. +14. It throws for an empty name or IBAN, a field over its limit or with a line break, a BIC that does not have 8 or 11 + characters, and both a reference and a text. +15. It counts the limits in characters and the payload in bytes. + +### Calendar event + +16. A timed event is in UTC. +17. An all-day event uses the local dates and an exclusive end, also across the end of a year. +18. A year below 100 has 4 digits. +19. It escapes the text values. +20. It throws for an invalid date and for a year over 9999. + +### Scanning + +A decoder (zxing-cpp, from the `zxing-wasm` package) reads the code of each payload. + +21. A decoder reads each payload back unchanged, with special characters, non-ASCII text and line breaks. + +### QR payloads properties + +22. A Wi-Fi payload gives back any SSID and password, and the hidden flag, through an independent reader of its + escapes. +23. A vCard keeps each value on its own line, and gives back any organization and note through an independent reader + of the TEXT escapes. +24. An EPC payload writes any amount in whole cents, up to 999,999,999.99 euros, exactly. +25. A timed event writes its UTC time, and an all-day event writes its local date and the next day as its end, for any + date from year 1 to 9999. + +### Not covered by the suite + +- A scan with the camera of a phone, and the action that the phone takes for each format. +- A banking app that reads the EPC payload. + +## Assumptions and limitations + +- The `WIFI:` format has no formal specification. The helper follows the ZXing description, which phone cameras read. +- WPA2-Enterprise (EAP) networks are not supported: few phone cameras read their fields. +- The contact card has no photo, because the image data makes a code too large to scan. +- vCard 4.0 is not written: a public Apple forum report says that the iOS reader garbles non-ASCII text in it. +- The calendar event has no `VCALENDAR` wrapper, `UID` or `DTSTAMP`, which RFC 5545 asks for. Scanner apps read the + event without them. +- The helpers check the format, not the meaning. A wrong IBAN or an end before the start makes a valid code. + +## Accessibility + +The helpers return text and have no user interface. The default accessible name of `igc-qr-code` is +`QR code: `, so a screen reader would read the whole payload, a Wi-Fi password included. Give the code an +`aria-label` that says what it does, such as `Wi-Fi login for Guest Wi-Fi`. + +### ARIA roles and properties + +None applicable. + +### Keyboard support + +None applicable. + +### Right to Left support + +None applicable. The formats store the text in logical order, and the code reads the same in any direction. diff --git a/src/internals/testing/qr-decoder.spec.ts b/src/internals/testing/qr-decoder.spec.ts index 5b7a06a38..d4bd1f3be 100644 --- a/src/internals/testing/qr-decoder.spec.ts +++ b/src/internals/testing/qr-decoder.spec.ts @@ -1,4 +1,8 @@ -import { prepareZXingModule } from 'zxing-wasm/reader'; +import { + prepareZXingModule, + type ReadResult, + readBarcodes, +} from 'zxing-wasm/reader'; /** Loads the zxing decoder from the package, not from its default CDN. */ export function prepareQrDecoder(): void { @@ -11,3 +15,40 @@ export function prepareQrDecoder(): void { }, }); } + +/** Returns the first QR code that the decoder reads from `image`. */ +export async function readQr( + image: Blob | ImageData +): Promise { + const [result] = await readBarcodes(image, { + formats: ['QRCode'], + maxNumberOfSymbols: 1, + }); + return result; +} + +/** + * Draws a module matrix with 4 pixels for each module and a quiet zone of 4 modules, and + * returns the bytes that the decoder reads from it. + */ +export async function readQrMatrix( + matrix: boolean[][] +): Promise { + const scale = 4; + const side = (matrix.length + 8) * scale; + const context = new OffscreenCanvas(side, side).getContext('2d')!; + + context.fillStyle = '#fff'; + context.fillRect(0, 0, side, side); + context.fillStyle = '#000'; + + for (const [row, modules] of matrix.entries()) { + for (const [col, dark] of modules.entries()) { + if (dark) { + context.fillRect((col + 4) * scale, (row + 4) * scale, scale, scale); + } + } + } + + return (await readQr(context.getImageData(0, 0, side, side)))?.bytes; +} diff --git a/stories/qr-code.stories.ts b/stories/qr-code.stories.ts index 33d68e3f6..3dc627463 100644 --- a/stories/qr-code.stories.ts +++ b/stories/qr-code.stories.ts @@ -8,7 +8,14 @@ import { IgcSwitchComponent, type QrCodeCopyFormat, type QrCodeExportFormat, + type QrErrorCorrectionLevel, } from 'igniteui-webcomponents'; +import { + createEpcPayload, + createEventPayload, + createVCardPayload, + createWifiPayload, +} from 'igniteui-webcomponents/extras/qr-payloads'; import { html } from 'lit'; import { ifDefined } from 'lit/directives/if-defined.js'; import { disableStoryControls } from './story.js'; @@ -252,6 +259,10 @@ const samples = html` max-width: 12rem; text-align: center; } + + .qr-samples code { + overflow-wrap: anywhere; + } `; @@ -578,40 +589,51 @@ export const WithLogo: Story = { }, }; -type Payload = 'url' | 'wifi' | 'contact' | 'text'; - -/** Escapes the special characters of a `WIFI:` string field. */ -function escapeWifi(value: string): string { - return value.replace(/([\\;,:"])/g, '\\$1'); -} - -/** Escapes the special characters of a vCard text value. */ -function escapeVCard(value: string): string { - return value.replace(/([\\;,])/g, '\\$1').replace(/\n/g, '\\n'); -} +type Payload = 'url' | 'wifi' | 'contact' | 'payment' | 'event' | 'text'; const payloads: Record< Payload, - { label: string; encode: (fields: Record) => string } + { + label: string; + encode: (fields: Record) => string; + errorLevel?: QrErrorCorrectionLevel; + } > = { url: { label: 'Website link', encode: (f) => f.url }, wifi: { label: 'Wi-Fi network', - encode: (f) => - `WIFI:T:WPA;S:${escapeWifi(f.ssid)};P:${escapeWifi(f.password)};;`, + encode: (f) => createWifiPayload({ ssid: f.ssid, password: f.password }), }, contact: { label: 'Contact card', encode: (f) => - [ - 'BEGIN:VCARD', - 'VERSION:3.0', - `N:${escapeVCard(f.last)};${escapeVCard(f.first)}`, - `FN:${escapeVCard(`${f.first} ${f.last}`.trim())}`, - `TEL:${escapeVCard(f.phone)}`, - `EMAIL:${escapeVCard(f.email)}`, - 'END:VCARD', - ].join('\n'), + createVCardPayload({ + name: { given: f.first, family: f.last }, + organization: f.organization, + phones: f.phone ? [{ value: f.phone, type: 'cell' }] : [], + emails: f.email ? [{ value: f.email, type: 'work' }] : [], + }), + }, + payment: { + label: 'SEPA payment', + errorLevel: 'M', + encode: (f) => + createEpcPayload({ + name: f.beneficiary, + iban: f.iban, + amount: f.amount ? Number(f.amount) : undefined, + text: f.remittance, + }), + }, + event: { + label: 'Calendar event', + encode: (f) => + createEventPayload({ + summary: f.summary, + start: new Date(`${f.date}T${f.start}`), + end: new Date(`${f.date}T${f.end}`), + location: f.location, + }), }, text: { label: 'Plain text', encode: (f) => f.text }, }; @@ -622,7 +644,7 @@ export const Generator: Story = { docs: { description: { story: - 'A QR code generator. The content type decides how the fields are encoded: a URL, a `WIFI:` string that a phone uses to join the network, a vCard that a phone saves as a contact, or plain text. The code updates on each keystroke, and `aria-label` gives the code a name that describes its content. The encoded payload shows under the code.', + 'A QR code generator. The content type decides how the fields are encoded: a URL, a Wi-Fi login, a contact card, a SEPA payment, a calendar event or plain text. The helpers of `igniteui-webcomponents/extras/qr-payloads` build the formats and escape the text. A helper throws a `RangeError` for input that its format does not allow, such as an amount with 3 decimals, and the message shows under the fields. The SEPA payment keeps the default error correction level M, as the EPC guideline asks. The code updates on each keystroke, and `aria-label` gives the code a name that describes its content. The encoded payload shows under the code.', }, }, }, @@ -632,6 +654,7 @@ export const Generator: Story = { '.qr-generator' )!; const type = root.querySelector('igc-select')!.value as Payload; + const status = root.querySelector('[role="status"]')!; const qr = root.querySelector('igc-qr-code')!; const fields = Object.fromEntries( Array.from(root.querySelectorAll('igc-input'), (input) => [ @@ -644,9 +667,15 @@ export const Generator: Story = { group.hidden = group.dataset.type !== type; } - qr.value = payloads[type].encode(fields); - qr.ariaLabel = `${payloads[type].label} QR code`; - root.querySelector('pre')!.textContent = qr.value; + try { + qr.value = payloads[type].encode(fields); + qr.errorLevel = payloads[type].errorLevel ?? 'Q'; + qr.ariaLabel = `${payloads[type].label} QR code`; + status.textContent = ''; + } catch (error) { + status.textContent = (error as Error).message; + } + root.querySelector('pre')!.textContent = qr.value ?? ''; }; const download = async (event: Event) => { @@ -746,6 +775,12 @@ export const Generator: Story = { value="Ivanova" @igcInput=${update} > + + + + +