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 edb9f8c0e..635e9b302 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/* @@ -637,6 +637,7 @@ Each component has tests in `[component].spec.ts`. They cover: | `value-state.spec.js` | `runValueStateMotionTests` | | `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`, `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. @@ -1062,7 +1063,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 f584d82bc..f90d3e177 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,12 @@ 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. + - The `alignment` CSS part styles the alignment patterns. They take `--ig-qr-code-dark-color`. + - `dot-style` takes `diamond`, `plus`, `liquid`, `horizontal-bars` and `vertical-bars`. `liquid` fills the inside corners where `rounded` modules join. A bar style draws each run of dark modules in a row or a column as one bar with round ends. Without `corner-dot-style`, the corner dots draw `diamond` and `plus` as `square`, and the other new styles as `rounded`. + - `square-style` and `corner-dot-style` take `leaf`, a square with two opposite round corners on the diagonal toward the center of the code. In a `circle` corner square, a `leaf` corner dot draws as a circle. + - `gradient` paints the data modules, the alignment patterns and the corners with a `linear` or `radial` gradient, from `--ig-qr-code-gradient-start` to `--ig-qr-code-gradient-end`. `gradient-angle` turns a linear gradient. An explicit `--ig-qr-code-corner-square-color` or `--ig-qr-code-corner-dot-color` wins for its part. Keep both colors much darker than the background. + - `logo-shape` clips the logo to a `circle`, `rounded` or `squircle` shape that fills the logo box. The cutout removes only the modules under the shape. + - `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 - #### Button group, Checkbox, Chip, Color picker, Combo, Date picker, Date range picker, Date time input, File input, Input, List, Mask input, Navigation drawer, Radio, Select, Switch, Textarea, Tree @@ -39,8 +45,12 @@ 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. + - `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. The old size covered more than the safe area of level `M`: 5.9% of a version 3 code at the default `margin`, against 4%. + - Each module covers a whole number of pixels, so the edges are sharp. The pixels that are left over widen the quiet zone, so the code can be smaller than `size`, and `margin` is a minimum. An export gets whole pixels at its own size. + - The alignment patterns take the shapes of the corners: a ring of `square-style` around a dot of the corner dot style. A `rounded` module no longer joins them. + - With a logo, a `rounded` module ends round at the edge of the cutout, and so do the `liquid` modules and the bars. Before, a `rounded` module next to the cutout was cut straight. - #### Radio - Each radio keeps its own default, as a native radio does. The `checked` attribute of one radio no longer clears `defaultChecked` of the other radios of its group. As before, the last radio with the `checked` attribute is checked at the start and after a form reset. - `checkValidity()` and `reportValidity()` emit `invalid` on the radios of the group in DOM order. Before, the other radios emitted it first, and the called radio last. @@ -95,6 +105,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - A formatted value that you empty submits nothing. Before, the form submitted the empty mask, such as `__-__`. - #### QR code - A logo no longer makes a short value unreadable. The component selects a larger version, so that the logo hides no more codewords than the error correction recovers. When you set `version`, the logo gets smaller. + - A code with `square-style="circle"` no longer fails to scan at some sizes, about 1 time in 10. For this fix, a `square` corner dot in a `circle` corner square draws as a circle. - #### Radio - The validity of a group changes at once when a radio joins or leaves the group, and on a form reset. A radio joins or leaves by `name`, by form owner or by a DOM change. A removed radio has the validity of a group of its own, as a native radio does. Before, the other radios kept the old validity. A group stayed invalid after its required radio left. After a form reset, the validity was correct only after the next render. - A checked radio that joins a group, by connect, `name` or form owner, unchecks the other radios of the group, as a native radio does. Before, two radios of the group could stay checked. 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/api-reference/igc-qr-code.md b/api-reference/igc-qr-code.md index 7a1959482..2605a710b 100644 --- a/api-reference/igc-qr-code.md +++ b/api-reference/igc-qr-code.md @@ -31,10 +31,14 @@ defineComponents(IgcQrCodeComponent); `undefined` or remove the attribute. - `size`: `number`. Default: `128`. Attribute: `size`. The size of the QR code in pixels. This determines the width and height of the generated QR code. The default value is 128 pixels. + + Each module covers a whole number of pixels, so the edges stay sharp. The pixels that are + left over widen the quiet zone, and the code can be smaller than `size`. An exported image + gets whole pixels at its own size. - `margin`: `number`. Default: `4`. Attribute: `margin`. The margin (quiet zone) around the QR code, expressed as a number of QR code modules rather than pixels. This is the blank border area surrounding the code, which helps ensure that it - can be properly scanned. + can be properly scanned. It is a minimum: spare pixels make the quiet zone wider. - `logoSrc`: `string | undefined`. Attribute: `logo-src`. The source URL of an optional logo image at the center of the QR code. The component does not render a logo that fails to load, a `javascript:` or `vbscript:` URL, @@ -56,21 +60,48 @@ defineComponents(IgcQrCodeComponent); - `logoMargin`: `number | undefined`. Attribute: `logo-margin`. The margin around the logo in pixels. This is the whitespace area surrounding the logo within the QR code, which helps ensure that the logo does not interfere with the QR code's scannability. -- `dotStyle`: `'square' | 'circle' | 'rounded' | 'squircle'`. Default: `'square'`. Attribute: `dot-style`. +- `logoShape`: `'square' | 'circle' | 'rounded' | 'squircle'`. Default: `'square'`. Attribute: `logo-shape`. + The shape of the logo: 'square', 'circle', 'rounded' or 'squircle'. The shape fills the logo + box, so a 'circle' logo with a wide image is an ellipse. The image is clipped to the shape, + and the cutout holds only the modules that the shape covers, in part or in full. +- `dotStyle`: `'square' | 'circle' | 'rounded' | 'squircle' | 'diamond' | 'plus' | 'liquid' | 'horizontal-bars' | 'vertical-bars'`. Default: `'square'`. Attribute: `dot-style`. The style of the data modules (dots) in the QR code. This can be 'square', 'circle', - 'rounded', or 'squircle'. The inner dot of each finder-pattern corner uses the same style - unless `cornerDotStyle` is set. + 'rounded', 'squircle', 'diamond', 'plus', 'liquid', 'horizontal-bars' or 'vertical-bars'. + 'liquid' is 'rounded' with a smooth fill in the inside corners where modules join. The bar + styles draw each run of dark modules in a row or a column as one bar with round ends. + + The inner dot of each finder-pattern corner uses the same style unless `cornerDotStyle` is + set. It draws 'diamond' and 'plus' as 'square', and 'liquid' and the bar styles as + 'rounded'. - `dotScale`: `number`. Default: `1`. Attribute: `dot-scale`. The size of each data module, as a ratio of its cell in the module grid. The value is a number from 0.7 to 1. Other values are clamped. A value below 1 leaves a gap between the - modules, so 'rounded' modules do not join their neighbors. The finder-pattern corners keep - their full size. A smaller value can make the code harder to scan with a camera. -- `squareStyle`: `'square' | 'circle' | 'rounded' | 'squircle'`. Default: `'square'`. Attribute: `square-style`. + modules, so 'rounded' modules do not join their neighbors, and 'liquid' draws as 'rounded'. + For the bar styles, it sets the thickness of the bars and shortens their ends. The + finder-pattern corners keep their full size. A smaller value can make the code harder to + scan with a camera. +- `squareStyle`: `'square' | 'circle' | 'rounded' | 'squircle' | 'leaf'`. Default: `'square'`. Attribute: `square-style`. The style of the corner squares in the QR code. This can be 'square', 'circle', 'rounded', - or 'squircle'. -- `cornerDotStyle`: `'square' | 'circle' | 'rounded' | 'squircle' | undefined`. Attribute: `corner-dot-style`. + 'squircle' or 'leaf'. A 'leaf' has two opposite round corners on the diagonal toward the + center of the code. The rings of the alignment patterns use the same style, and a 'leaf' + ring there has the shape of the top-left corner square. +- `cornerDotStyle`: `'square' | 'circle' | 'rounded' | 'squircle' | 'leaf' | undefined`. Attribute: `corner-dot-style`. The style of the inner dot of each finder-pattern corner. This can be 'square', 'circle', - 'rounded', or 'squircle'. When it is not set, the inner dot uses `dotStyle`. + 'rounded', 'squircle' or 'leaf'. When it is not set, the inner dot uses `dotStyle`. The + centers of the alignment patterns use the same style. + + In a 'circle' corner square, a 'square' or 'leaf' dot draws as 'circle', because scanners + do not find the pattern reliably with corners in a round ring. +- `gradient`: `'linear' | 'radial' | undefined`. Attribute: `gradient`. + The gradient of the dark modules: 'linear' or 'radial'. When it is not set, or has another + value, the modules have one color. The gradient goes from `--ig-qr-code-gradient-start` to + `--ig-qr-code-gradient-end` over the code without its quiet zone. It also paints the corners, + unless `--ig-qr-code-corner-square-color` or `--ig-qr-code-corner-dot-color` is set. + + Keep both colors much darker than the background. +- `gradientAngle`: `number`. Default: `0`. Attribute: `gradient-angle`. + The angle of a 'linear' gradient in degrees, clockwise. At 0 the gradient goes from left to + right, and at 90 from top to bottom. ## Methods @@ -109,10 +140,13 @@ defineComponents(IgcQrCodeComponent); - `dots`: The data modules (dots) of the QR code. - `corner-square`: The outer corner (finder-pattern) squares of the QR code. - `corner-dot`: The inner corner (finder-pattern) dots of the QR code. +- `alignment`: The alignment patterns of the QR code, from version 2. ## CSS custom properties - `--ig-qr-code-background`: The background color of the QR code. Default is `white`. -- `--ig-qr-code-dark-color`: The color of the data modules (dots), and the corner square/dot colors unless overridden below. Default is `black`. +- `--ig-qr-code-dark-color`: The color of the data modules (dots) and the alignment patterns, and the corner square/dot colors unless overridden below. Default is `black`. - `--ig-qr-code-corner-square-color`: The color of the outer finder-pattern corner squares. Defaults to `--ig-qr-code-dark-color`. - `--ig-qr-code-corner-dot-color`: The color of the inner finder-pattern corner dots. Defaults to `--ig-qr-code-dark-color`. +- `--ig-qr-code-gradient-start`: The start color of the `gradient`. Defaults to `--ig-qr-code-dark-color`. +- `--ig-qr-code-gradient-end`: The end color of the `gradient`. Defaults to `--ig-qr-code-dark-color`. 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/public-api.json b/public-api.json index 45080f5da..b1076c174 100644 --- a/public-api.json +++ b/public-api.json @@ -213,9 +213,12 @@ "QrCodeCopyOptions", "QrCodeExportFormat", "QrCodeExportOptions", + "QrCornerDotStyle", "QrCornerSquareStyle", "QrDotStyle", "QrErrorCorrectionLevel", + "QrGradient", + "QrLogoShape", "RangeTextSelectMode", "RegisterIconOptions", "SelectionRangeDirection", @@ -2874,30 +2877,36 @@ "igc-qr-code": { "class": "IgcQrCodeComponent", "attributes": { - "corner-dot-style": "QrCornerDotStyle | undefined ('circle' | 'rounded' | 'square' | 'squircle' | undefined)", + "corner-dot-style": "QrCornerDotStyle | undefined ('circle' | 'leaf' | 'rounded' | 'square' | 'squircle' | undefined)", "dot-scale": "number", - "dot-style": "QrDotStyle ('circle' | 'rounded' | 'square' | 'squircle')", + "dot-style": "QrDotStyle ('circle' | 'diamond' | 'horizontal-bars' | 'liquid' | 'plus' | 'rounded' | 'square' | 'squircle' | 'vertical-bars')", "error-level": "QrErrorCorrectionLevel ('H' | 'L' | 'M' | 'Q')", + "gradient": "QrGradient | undefined ('linear' | 'radial' | undefined)", + "gradient-angle": "number", "logo-margin": "number | undefined", + "logo-shape": "QrLogoShape ('circle' | 'rounded' | 'square' | 'squircle')", "logo-size": "number", "logo-src": "string | undefined", "margin": "number", "size": "number", - "square-style": "QrCornerSquareStyle ('circle' | 'rounded' | 'square' | 'squircle')", + "square-style": "QrCornerSquareStyle ('circle' | 'leaf' | 'rounded' | 'square' | 'squircle')", "value": "string | undefined", "version": "number | undefined" }, "properties": { - "cornerDotStyle": "QrCornerDotStyle | undefined ('circle' | 'rounded' | 'square' | 'squircle' | undefined)", + "cornerDotStyle": "QrCornerDotStyle | undefined ('circle' | 'leaf' | 'rounded' | 'square' | 'squircle' | undefined)", "dotScale": "number", - "dotStyle": "QrDotStyle ('circle' | 'rounded' | 'square' | 'squircle')", + "dotStyle": "QrDotStyle ('circle' | 'diamond' | 'horizontal-bars' | 'liquid' | 'plus' | 'rounded' | 'square' | 'squircle' | 'vertical-bars')", "errorLevel": "QrErrorCorrectionLevel ('H' | 'L' | 'M' | 'Q')", + "gradient": "QrGradient | undefined ('linear' | 'radial' | undefined)", + "gradientAngle": "number", "logoMargin": "number | undefined", + "logoShape": "QrLogoShape ('circle' | 'rounded' | 'square' | 'squircle')", "logoSize": "number", "logoSrc": "string | undefined", "margin": "number", "size": "number", - "squareStyle": "QrCornerSquareStyle ('circle' | 'rounded' | 'square' | 'squircle')", + "squareStyle": "QrCornerSquareStyle ('circle' | 'leaf' | 'rounded' | 'square' | 'squircle')", "static tagName": "readonly string", "value": "string | undefined", "version": "number | undefined" @@ -2911,6 +2920,7 @@ "events": {}, "slots": [], "cssParts": [ + "alignment", "background", "corner-dot", "corner-square", @@ -2920,7 +2930,9 @@ "--ig-qr-code-background", "--ig-qr-code-corner-dot-color", "--ig-qr-code-corner-square-color", - "--ig-qr-code-dark-color" + "--ig-qr-code-dark-color", + "--ig-qr-code-gradient-end", + "--ig-qr-code-gradient-start" ] }, "igc-radio": { 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/cutout.ts b/src/components/qr-code/model/cutout.ts index 5699366ce..cf1ae9555 100644 --- a/src/components/qr-code/model/cutout.ts +++ b/src/components/qr-code/model/cutout.ts @@ -13,6 +13,19 @@ export type ModuleRange = { right: number; }; +/** Calls `visit` for each module of `range` in a matrix of `size` modules. */ +export function forEachModule( + { top, left, bottom, right }: ModuleRange, + size: number, + visit: (row: number, col: number) => void +): void { + for (let row = Math.max(top, 0); row <= Math.min(bottom, size - 1); row++) { + for (let col = Math.max(left, 0); col <= Math.min(right, size - 1); col++) { + visit(row, col); + } + } +} + /** The module map value of a locator module, which a scanner needs to read the code. */ export const LOCATOR_MODULE = -2; @@ -70,27 +83,31 @@ function getCodewordBlocks(version: number, level: number): Uint8Array { /** * Whether a scanner reads a code of `version` and `level` (0 for L to 3 for H) with the modules - * of `range` hidden: no hidden module is a locator module, and no block loses more codewords - * than it corrects. A codeword with one hidden module counts as lost. + * of the `cutout` ranges hidden: no hidden module is a locator module, and no block loses more + * codewords than it corrects. A codeword with one hidden module counts as lost. */ export function canHideModules( version: number, level: number, - { top, left, bottom, right }: ModuleRange + ...cutout: ModuleRange[] ): boolean { const size = version * 4 + 17; const map = getModuleMap(version); const hidden = new Set(); - for (let row = Math.max(top, 0); row <= Math.min(bottom, size - 1); row++) { - for (let col = Math.max(left, 0); col <= Math.min(right, size - 1); col++) { + let hidesLocator = false; + + for (const range of cutout) { + forEachModule(range, size, (row, col) => { const codeword = map[row * size + col]; - if (codeword === LOCATOR_MODULE) return false; + if (codeword === LOCATOR_MODULE) hidesLocator = true; if (codeword >= 0) hidden.add(codeword); - } + }); } + if (hidesLocator) return false; + const protection = MISDECODE_PROTECTION[version - 1]?.[level] ?? 0; const correctable = (EC_BLOCKS_TABLE[version - 1][level].ecPerBlock - protection) >> 1; diff --git a/src/components/qr-code/model/encode.ts b/src/components/qr-code/model/encode.ts index e1d14be73..8d8209a16 100644 --- a/src/components/qr-code/model/encode.ts +++ b/src/components/qr-code/model/encode.ts @@ -12,98 +12,224 @@ 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. */ + countBits: readonly number[]; + /** The cost of `char` in sixths of a bit (10/3 and 11/2 are whole), 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); +/** The bits of the mode indicator and the count field of a segment in `mode`. */ +function getHeaderBits(mode: Mode, group: number): number { + return 4 + mode.countBits[group]; } -function isAlphanumeric(str: string): boolean { - for (const char of str) { - if (!ALPHANUMERIC_MAP.has(char)) { - return false; - } +function getSegmentBits({ mode, text }: Segment, group: number): number { + let cost = 0; + for (const char of text) { + cost += MODES[mode].cost(char); } - return true; + return getHeaderBits(MODES[mode], group) + Math.ceil(cost / 6); } -function detectEncodingMode(data: string): QrEncodingMode { - if (isNumeric(data)) return 'numeric'; - if (isAlphanumeric(data)) return 'alphanumeric'; - return 'byte'; +/** Returns the wider of two modes. `MODES` goes from the narrowest character set to the widest. */ +function widerMode(a: number, b: number): number { + return Math.max(a, b); } -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}`); +/** + * 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) => getHeaderBits(mode, 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; + } + } + } } -} -const MODE_INDICATORS: Record = { - numeric: 0b0001, - alphanumeric: 0b0010, - byte: 0b0100, -}; + const modes = new Int8Array(chars.length); + let mode = costs.indexOf(Math.min(...costs)); -function pushBits(bits: number[], value: number, length: number): void { - for (let i = length - 1; i >= 0; i--) { - bits.push((value >> i) & 1); + for (let i = chars.length - 1; i >= 0; i--) { + mode = steps[i * modeCount + mode]; + modes[i] = mode; + } + + const segments: Segment[] = []; + + 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: widerMode(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); + // Skip a group too small even for all-digit data. + 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 +258,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 +278,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 +292,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 +332,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/matrix.ts b/src/components/qr-code/model/matrix.ts index c488db38b..eaa99c823 100644 --- a/src/components/qr-code/model/matrix.ts +++ b/src/components/qr-code/model/matrix.ts @@ -26,6 +26,28 @@ export function getAlignmentPatternPositions(version: number): number[] { return positions; } +/** + * Returns the row and column of each alignment pattern center of a version, without the three + * that would overlap a finder pattern. + */ +export function getAlignmentPatternCenters( + version: number +): [number, number][] { + const positions = getAlignmentPatternPositions(version); + const first = positions[0]; + const last = positions.at(-1); + + return positions.flatMap((r) => + positions + .filter( + (c) => + !(r === first && (c === first || c === last)) && + !(r === last && c === first) + ) + .map((c): [number, number] => [r, c]) + ); +} + /** The format information bits of the error correction levels L, M, Q and H. */ const FORMAT_LEVEL_BITS = [0b01, 0b00, 0b11, 0b10]; @@ -252,19 +274,8 @@ export function createFunctionPatterns(version: number): { matrix[darkRow][8] = true; functionModules[darkRow][8] = true; - const alignmentPositions = getAlignmentPatternPositions(version); - for (const r of alignmentPositions) { - for (const c of alignmentPositions) { - // Skip if this position overlaps with a finder pattern - if ( - (r <= 8 && c <= 8) || - (r <= 8 && c >= size - 8) || - (r >= size - 8 && c <= 8) - ) { - continue; - } - placeAlignmentPattern(matrix, functionModules, r, c); - } + for (const [r, c] of getAlignmentPatternCenters(version)) { + placeAlignmentPattern(matrix, functionModules, r, c); } return { matrix, functionModules, locatorModules }; 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..536e38050 100644 --- a/src/components/qr-code/model/qr-model.property.spec.ts +++ b/src/components/qr-code/model/qr-model.property.spec.ts @@ -4,6 +4,10 @@ import { fc, SLOW_PROPERTY_RUNS, } from '#internals/testing/fast-check-setup.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'; @@ -11,6 +15,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 +47,62 @@ 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; + } +} + 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 +137,50 @@ 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(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(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(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); + expect(await readQrMatrix(matrix)).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..4f6193b2f 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'); @@ -633,6 +673,26 @@ describe('QR model - logo cutout', () => { .to.be.true; }); + it('counts the codewords of all the ranges together', () => { + // The ranges of rows 13 to 16 and 17 to 20 hide what rows 13 to 20 hide. + expect( + canHideModules( + 1, + 0, + { top: 13, left: 19, bottom: 16, right: 20 }, + { top: 17, left: 19, bottom: 20, right: 20 } + ) + ).to.be.true; + expect( + canHideModules( + 1, + 0, + { top: 9, left: 19, bottom: 12, right: 20 }, + { top: 13, left: 19, bottom: 20, right: 20 } + ) + ).to.be.false; + }); + it('counts a codeword with one hidden module as lost', () => { // Rows 12, 16 and 20 hold one module of codewords 2, 1 and 0. expect(canHideModules(1, 0, { top: 16, left: 20, bottom: 20, right: 20 })) diff --git a/src/components/qr-code/qr-code.spec.ts b/src/components/qr-code/qr-code.spec.ts index 0d2d9cb20..34eb4f00a 100644 --- a/src/components/qr-code/qr-code.spec.ts +++ b/src/components/qr-code/qr-code.spec.ts @@ -4,17 +4,28 @@ import { expect, fixture, html, + waitUntil, } 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 { defineComponents } from '#internals/definitions/defineComponents.js'; -import { asNumber } from '#internals/utils/math.js'; +import { expectCloseTo } from '#internals/testing/helpers.spec.js'; +import { + prepareQrDecoder, + readQr, +} from '#internals/testing/qr-decoder.spec.js'; +import { asNumber, clamp } from '#internals/utils/math.js'; import { configureTheme } from '#theming/config.js'; +import type { ModuleRange } from './model/cutout.js'; import IgcQrCodeComponent from './qr-code.js'; import { rasterizeSvg } from './renderer/export.js'; import { renderDataModules } from './renderer/helpers.js'; -import type { QrErrorCorrectionLevel } from './types.js'; +import type { QrDotStyle, QrErrorCorrectionLevel } from './types.js'; + +/** A black logo twice as wide as it is high. */ +const WIDE_LOGO = `data:image/svg+xml,${encodeURIComponent( + '' +)}`; describe('IgcQrCodeComponent', () => { before(() => { @@ -38,6 +49,22 @@ describe('IgcQrCodeComponent', () => { await expect(el).shadowDom.to.be.accessible(); }); + it('passes the a11y audit with a gradient and a shaped logo', async () => { + const logo = + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='; + const el = await fixture( + html`` + ); + + await expect(el).to.be.accessible(); + await expect(el).shadowDom.to.be.accessible(); + }); + it('renders an SVG with a element for screen readers', async () => { const el = await fixture<IgcQrCodeComponent>( html`<igc-qr-code value="https://example.com"></igc-qr-code>` @@ -147,6 +174,11 @@ describe('IgcQrCodeComponent', () => { expect(el.dotScale).to.equal(1); }); + it('gradient defaults to undefined and gradientAngle to 0', () => { + expect(el.gradient).to.be.undefined; + expect(el.gradientAngle).to.equal(0); + }); + it('value defaults to undefined', () => { expect(el.value).to.be.undefined; }); @@ -304,6 +336,168 @@ describe('IgcQrCodeComponent', () => { expect(fillOf(getPart(el, 'corner-dot'))).to.equal('rgb(0, 0, 255)'); }); + it('colors the alignment patterns with --ig-qr-code-dark-color', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code + value="https://example.com" + style="--ig-qr-code-dark-color: rgb(204, 51, 0); --ig-qr-code-corner-dot-color: rgb(0, 0, 255);" + ></igc-qr-code>` + ); + + expect(fillOf(getPart(el, 'alignment'))).to.equal('rgb(204, 51, 0)'); + }); + + describe('Gradient', () => { + // Version 2, with an alignment pattern. + const VALUE = 'https://example.com'; + + function gradientOf(el: IgcQrCodeComponent): SVGGradientElement | null { + return el.renderRoot.querySelector('linearGradient, radialGradient'); + } + + function readNumbers(element: Element, names: string[]): number[] { + return names.map((name) => asNumber(element.getAttribute(name)!)); + } + + it('renders no gradient by default', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code value=${VALUE}></igc-qr-code>` + ); + expect(gradientOf(el)).to.be.null; + }); + + it('paints the dots, the alignment patterns and the corners with the gradient', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code value=${VALUE} gradient="linear"></igc-qr-code>` + ); + const paint = `url("#${gradientOf(el)!.id}")`; + + for (const part of [ + 'dots', + 'alignment', + 'corner-square', + 'corner-dot', + ]) { + expect(fillOf(getPart(el, part)), part).to.equal(paint); + } + + el.gradient = undefined; + await elementUpdated(el); + expect(gradientOf(el)).to.be.null; + expect(fillOf(getPart(el, 'dots'))).to.equal('rgb(0, 0, 0)'); + }); + + it('paints one color for a gradient value that is not linear or radial', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code value=${VALUE}></igc-qr-code>` + ); + el.setAttribute('gradient', 'conic'); + await elementUpdated(el); + + expect(gradientOf(el)).to.be.null; + expect(fillOf(getPart(el, 'dots'))).to.equal('rgb(0, 0, 0)'); + }); + + it('treats a gradient-angle that is not a number as 0', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code></igc-qr-code>` + ); + el.setAttribute('gradient-angle', 'up'); + expect(el.gradientAngle).to.equal(0); + }); + + it('lets an explicit corner color win over the gradient', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code + value=${VALUE} + gradient="linear" + style="--ig-qr-code-corner-square-color: rgb(0, 0, 255);" + ></igc-qr-code>` + ); + + expect(fillOf(getPart(el, 'corner-square'))).to.equal('rgb(0, 0, 255)'); + expect(fillOf(getPart(el, 'corner-dot'))).to.equal( + `url("#${gradientOf(el)!.id}")` + ); + }); + + it('colors the stops with the gradient colors, or else with the dark color', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code + value=${VALUE} + gradient="radial" + style="--ig-qr-code-dark-color: rgb(204, 51, 0);" + ></igc-qr-code>` + ); + const stops = () => + Array.from( + el.renderRoot.querySelectorAll('stop'), + (stop) => getComputedStyle(stop).stopColor + ); + + expect(stops()).to.deep.equal(['rgb(204, 51, 0)', 'rgb(204, 51, 0)']); + + el.style.setProperty('--ig-qr-code-gradient-start', 'rgb(255, 0, 0)'); + el.style.setProperty('--ig-qr-code-gradient-end', 'rgb(0, 0, 255)'); + expect(stops()).to.deep.equal(['rgb(255, 0, 0)', 'rgb(0, 0, 255)']); + }); + + it('runs a linear gradient across the matrix, without the quiet zone, at gradient-angle', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code value="test" gradient="linear"></igc-qr-code>` + ); + // Version 1 with the default margin: the matrix fills the view box from `start` to `end`. + const start = (4 * 21) / 29; + const end = 21 - start; + const expectLine = (expected: number[]) => + expectCloseTo( + readNumbers(gradientOf(el)!, ['x1', 'y1', 'x2', 'y2']), + expected, + 1e-9 + ); + + expectLine([start, 10.5, end, 10.5]); + + el.gradientAngle = 90; + await elementUpdated(el); + expectLine([10.5, start, 10.5, end]); + + // At 45 degrees, the line goes from corner to corner. + el.gradientAngle = 45; + await elementUpdated(el); + expectLine([start, start, end, end]); + }); + + it('reaches the corners of the matrix with a radial gradient', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code value="test" gradient="radial"></igc-qr-code>` + ); + const [cx, cy, r] = readNumbers(gradientOf(el)!, ['cx', 'cy', 'r']); + + expect(gradientOf(el)!.getAttribute('gradientUnits')).to.equal( + 'userSpaceOnUse' + ); + expect(cx).to.equal(10.5); + expect(cy).to.equal(10.5); + expect(r).to.be.closeTo((10.5 - (4 * 21) / 29) * Math.SQRT2, 1e-9); + }); + + it('gives each instance its own gradient', async () => { + const container = await fixture<HTMLElement>(html` + <div> + <igc-qr-code value=${VALUE} gradient="linear"></igc-qr-code> + <igc-qr-code value=${VALUE} gradient="linear"></igc-qr-code> + </div> + `); + const [first, second] = Array.from( + container.querySelectorAll('igc-qr-code'), + (el) => gradientOf(el)!.id + ); + + expect(first).not.to.equal(second); + }); + }); + it('does not invert colors when the global theme switches to dark variant', async () => { configureTheme('material', 'dark'); @@ -367,6 +561,14 @@ describe('IgcQrCodeComponent', () => { ); expect(el.dotScale).to.equal(0.8); }); + + it('reflects gradient and gradient-angle to gradient and gradientAngle', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code gradient="radial" gradient-angle="45"></igc-qr-code>` + ); + expect(el.gradient).to.equal('radial'); + expect(el.gradientAngle).to.equal(45); + }); }); describe('Style variants', () => { @@ -416,6 +618,101 @@ describe('IgcQrCodeComponent', () => { }); }); + describe('Pixel snapping', () => { + // Version 2: 25 modules, and 33 with the quiet zone. + const VALUE = 'https://example.com'; + const EPSILON = 1e-6; + + /** + * Checks that each module of `svg`, a code of `el` in the document, covers the same whole + * number of pixels, and that the quiet zone has at least `margin` modules on each side. + * Returns the pixels of a module. + */ + function expectWholePixels( + el: IgcQrCodeComponent, + svg: SVGSVGElement, + pixels: number + ): number { + const { margin } = el; + const side = getSide(el); + const moduleSize = side / (side + 2 * margin); + const { a, d, e, f } = svg + .querySelector<SVGGElement>(':scope > g')! + .getCTM()!; + const module = a * moduleSize; + const start = e + margin * module; + + expect([d, f]).to.deep.equal([a, e]); + expect(module).to.be.at.least(1); + expect(module).to.be.closeTo(Math.round(module), EPSILON); + expect(start).to.be.closeTo(Math.round(start), EPSILON); + expect(start).to.be.at.least(margin * module - EPSILON); + expect(pixels - start - side * module).to.be.at.least( + margin * module - EPSILON + ); + return module; + } + + for (const size of [128, 256]) { + it(`draws each module on whole pixels at size ${size}`, async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code value=${VALUE} size=${size}></igc-qr-code>` + ); + + expect( + expectWholePixels(el, getSvg(el) as SVGSVGElement, size) + ).to.be.closeTo(Math.floor(size / 33), EPSILON); + }); + } + + it('keeps a fractional margin as the smallest quiet zone', async () => { + // 3 pixels per module would leave 1 pixel, not 1.5, on one side. + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code value=${VALUE} size="78" margin="0.5"></igc-qr-code>` + ); + + expect( + expectWholePixels(el, getSvg(el) as SVGSVGElement, 78) + ).to.be.closeTo(2, EPSILON); + }); + + it('draws each module of an export on whole pixels of the image', async () => { + // 29 modules with the quiet zone. + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code value=${VALUE} margin="2"></igc-qr-code>` + ); + const container = await fixture<HTMLDivElement>(html`<div></div>`); + + for (const scale of [2, 1.3]) { + const file = await el.toImage({ format: 'svg', scale }); + const svg = new DOMParser().parseFromString( + await file.text(), + 'image/svg+xml' + ).documentElement as unknown as SVGSVGElement; + container.replaceChildren(document.importNode(svg, true)); + + const pixels = Math.round(el.size * scale); + + expect( + expectWholePixels( + el, + container.firstElementChild as SVGSVGElement, + pixels + ) + ).to.be.closeTo(Math.floor(pixels / 29), EPSILON); + } + }); + + it('does not snap modules smaller than 1 pixel', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code value=${VALUE} size="20"></igc-qr-code>` + ); + + expect(getSvg(el)!.querySelector('g')!.hasAttribute('transform')).to.be + .false; + }); + }); + describe('Shape geometry', () => { // With no margin, one module is one SVG unit, so the module at row `r` and // column `c` fills the square from (c, r) to (c + 1, r + 1). The timing module @@ -444,6 +741,22 @@ describe('IgcQrCodeComponent', () => { .getAttribute('d')!; } + /** Whether the point at `x`, `y` lies in the fill of the path data `d`. */ + function isInPath(d: string, x: number, y: number): boolean { + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + const path = svg.appendChild( + document.createElementNS('http://www.w3.org/2000/svg', 'path') + ); + path.setAttribute('d', d); + document.body.append(svg); + + try { + return path.isPointInFill(new DOMPoint(x, y)); + } finally { + svg.remove(); + } + } + async function renderCode(): Promise<IgcQrCodeComponent> { return fixture<IgcQrCodeComponent>( html`<igc-qr-code value="test" margin="0"></igc-qr-code>` @@ -532,6 +845,226 @@ describe('IgcQrCodeComponent', () => { }); }); + describe('Alignment patterns', () => { + // Version 2 has one alignment pattern, from (16, 16) to (21, 21). Its center module + // fills the square from (18, 18) to (19, 19). + async function renderVersion2(): Promise<IgcQrCodeComponent> { + return fixture<IgcQrCodeComponent>( + html`<igc-qr-code + value="https://example.com" + margin="0" + ></igc-qr-code>` + ); + } + + it('draws a ring of the corner square style and a dot of the corner dot style', async () => { + const el = await renderVersion2(); + const ringCorner = () => isInFill(el, 'alignment', 16.05, 16.05); + const dotCorner = () => isInFill(el, 'alignment', 18.05, 18.05); + + expect(isInFill(el, 'alignment', 16.5, 18.5)).to.be.true; + expect(isInFill(el, 'alignment', 17.5, 18.5)).to.be.false; + expect(isInFill(el, 'alignment', 18.5, 18.5)).to.be.true; + expect(ringCorner()).to.be.true; + expect(dotCorner()).to.be.true; + + Object.assign(el, { squareStyle: 'rounded', cornerDotStyle: 'circle' }); + await elementUpdated(el); + expect(ringCorner()).to.be.false; + expect(dotCorner()).to.be.false; + expect(isInFill(el, 'alignment', 16.5, 18.5)).to.be.true; + expect(isInFill(el, 'alignment', 18.5, 18.5)).to.be.true; + }); + + it('leaves the alignment patterns out of the data modules at any dot scale', async () => { + const el = await renderVersion2(); + const alignment = getPath(el, 'alignment'); + + for (const [x, y] of [ + [16.5, 16.5], + [18.5, 16.5], + [18.5, 18.5], + ]) { + expect(isInFill(el, 'dots', x, y)).to.be.false; + } + + el.dotScale = 0.7; + await elementUpdated(el); + expect(getPath(el, 'alignment')).to.equal(alignment); + }); + + it('does not join a rounded module to an alignment pattern', async () => { + // The alignment pattern of version 2, and one dark module right of its ring. + const matrix = Array.from({ length: 25 }, (_, r) => + Array.from({ length: 25 }, (_, c) => { + const distance = Math.max(Math.abs(r - 18), Math.abs(c - 18)); + return (r === 18 && c === 21) || (distance <= 2 && distance !== 1); + }) + ); + const modules = renderDataModules(matrix, 1, 0, 'rounded', 1); + + expect(modules).to.have.length(1); + expect(isInPath(modules[0], 21.02, 18.02)).to.be.false; + }); + + it('draws a square or leaf corner dot as a circle in a circle corner square', async () => { + const el = await renderVersion2(); + Object.assign(el, { squareStyle: 'circle', cornerDotStyle: 'circle' }); + await elementUpdated(el); + const dot = getPath(el, 'corner-dot'); + const alignment = getPath(el, 'alignment'); + + for (const cornerDotStyle of ['square', 'leaf'] as const) { + el.cornerDotStyle = cornerDotStyle; + await elementUpdated(el); + expect(getPath(el, 'corner-dot'), cornerDotStyle).to.equal(dot); + expect(getPath(el, 'alignment'), cornerDotStyle).to.equal(alignment); + expect(el.cornerDotStyle).to.equal(cornerDotStyle); + } + + Object.assign(el, { squareStyle: 'square', cornerDotStyle: 'square' }); + await elementUpdated(el); + expect(isInFill(el, 'corner-dot', 2.05, 2.05)).to.be.true; + }); + }); + + describe('Diamond, plus, liquid, bars and leaf', () => { + // Dark modules at (10, 10), (10, 11), (10, 12) and (11, 10), away from the patterns. + const matrix = Array.from({ length: 21 }, (_, r) => + Array.from( + { length: 21 }, + (_, c) => (r === 10 && c >= 10 && c <= 12) || (r === 11 && c === 10) + ) + ); + + /** Whether the point at `x`, `y` lies in the modules of `style` at `scale`. */ + function isFilled( + style: QrDotStyle, + x: number, + y: number, + scale = 1, + cutout?: ModuleRange[] + ): boolean { + const d = renderDataModules(matrix, 1, 0, style, scale, cutout).join( + ' ' + ); + return isInPath(d, x, y); + } + + it('draws a diamond and a plus that reach the cell edges', () => { + // The module at (10, 12) has no dark neighbor on its right. + for (const style of ['diamond', 'plus'] as const) { + expect(isFilled(style, 12.5, 10.5), style).to.be.true; + expect(isFilled(style, 12.98, 10.5), style).to.be.true; + expect(isFilled(style, 12.9, 10.1), style).to.be.false; + } + + expect(isFilled('plus', 12.5, 10.15)).to.be.true; + expect(isFilled('diamond', 12.3, 10.15)).to.be.false; + }); + + it('fills the inside corner of a liquid L-join', () => { + // The inside corner of the L is at (11, 11). + expect(isFilled('liquid', 11.03, 11.03)).to.be.true; + expect(isFilled('liquid', 11.4, 11.4)).to.be.false; + expect(isFilled('rounded', 11.03, 11.03)).to.be.false; + expect(renderDataModules(matrix, 1, 0, 'liquid', 0.9)).to.deep.equal( + renderDataModules(matrix, 1, 0, 'rounded', 0.9) + ); + }); + + it('draws one bar with round ends for each run of a bar style', () => { + expect( + renderDataModules(matrix, 1, 0, 'horizontal-bars', 1) + ).to.have.length(2); + expect( + renderDataModules(matrix, 1, 0, 'vertical-bars', 1) + ).to.have.length(3); + + expect(isFilled('horizontal-bars', 11, 10.5)).to.be.true; + expect(isFilled('horizontal-bars', 10.05, 10.05)).to.be.false; + expect(isFilled('vertical-bars', 10.5, 11)).to.be.true; + + expect(isFilled('horizontal-bars', 11, 10.5, 0.7)).to.be.true; + expect(isFilled('horizontal-bars', 11, 10.1, 0.7)).to.be.false; + }); + + it('does not join a module under the logo to a module outside it', () => { + // The logo cutout holds the module at (10, 12). + const cutout = [{ top: 10, left: 12, bottom: 10, right: 12 }]; + + // The module at (10, 11) ends round toward the cutout, and the hidden module stays. + expect(isFilled('rounded', 11.98, 10.02)).to.be.true; + expect(isFilled('rounded', 11.98, 10.02, 1, cutout)).to.be.false; + expect(isFilled('rounded', 12.5, 10.5, 1, cutout)).to.be.true; + + // The bar of row 10 splits at the cutout edge. + expect( + renderDataModules(matrix, 1, 0, 'horizontal-bars', 1, cutout) + ).to.have.length(3); + + // A fillet needs three modules of one zone. + const corner = [{ top: 10, left: 10, bottom: 10, right: 10 }]; + expect(isFilled('liquid', 11.03, 11.03, 1, corner)).to.be.false; + }); + + it('rounds the leaf corners on the diagonal toward the center of the code', async () => { + const el = await renderCode(); + Object.assign(el, { squareStyle: 'leaf', cornerDotStyle: 'leaf' }); + await elementUpdated(el); + + // The top-left finder pattern fills the square from (0, 0) to (7, 7), and the + // top-right one the square from (14, 0) to (21, 7). + expect(isInFill(el, 'corner-square', 0.1, 0.1)).to.be.false; + expect(isInFill(el, 'corner-square', 6.9, 0.1)).to.be.true; + expect(isInFill(el, 'corner-square', 6.9, 6.9)).to.be.false; + expect(isInFill(el, 'corner-square', 14.1, 0.1)).to.be.true; + expect(isInFill(el, 'corner-square', 20.9, 0.1)).to.be.false; + expect(isInFill(el, 'corner-dot', 2.05, 2.05)).to.be.false; + expect(isInFill(el, 'corner-dot', 4.95, 2.05)).to.be.true; + }); + + it('gives a leaf alignment ring the shape of the top-left corner square', async () => { + // The alignment pattern of version 2 fills the square from (16, 16) to (21, 21). + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code + value="https://example.com" + margin="0" + square-style="leaf" + ></igc-qr-code>` + ); + + expect(isInFill(el, 'alignment', 16.05, 16.05)).to.be.false; + expect(isInFill(el, 'alignment', 20.95, 16.05)).to.be.true; + }); + + it('draws the corner dots of the new dot styles as square or rounded', async () => { + const el = await renderCode(); + const dot = () => getPath(el, 'corner-dot'); + + el.cornerDotStyle = 'square'; + await elementUpdated(el); + const square = dot(); + + el.cornerDotStyle = 'rounded'; + await elementUpdated(el); + const rounded = dot(); + + el.cornerDotStyle = undefined; + for (const [dotStyle, expected] of [ + ['diamond', square], + ['plus', square], + ['liquid', rounded], + ['horizontal-bars', rounded], + ['vertical-bars', rounded], + ] as const) { + el.dotStyle = dotStyle; + await elementUpdated(el); + expect(dot(), dotStyle).to.equal(expected); + } + }); + }); + describe('dotScale', () => { it('shrinks the data modules around their centers', async () => { const el = await renderCode(); @@ -635,6 +1168,10 @@ describe('IgcQrCodeComponent', () => { it('logoMargin defaults to undefined', () => { expect(el.logoMargin).to.be.undefined; }); + + it('logoShape defaults to square', () => { + expect(el.logoShape).to.equal('square'); + }); }); describe('Attribute reflection', () => { @@ -660,6 +1197,13 @@ describe('IgcQrCodeComponent', () => { ); expect(el.logoMargin).to.equal(4); }); + + it('reflects logo-shape to logoShape', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code logo-shape="circle"></igc-qr-code>` + ); + expect(el.logoShape).to.equal('circle'); + }); }); describe('URL validation', () => { @@ -970,6 +1514,24 @@ describe('IgcQrCodeComponent', () => { expect(widthWithMargin).to.be.lessThan(widthNoMargin); }); + it('keeps logoMargin in pixels when the modules snap to whole pixels', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code + value="https://example.com" + logo-src=${VALID_LOGO} + ></igc-qr-code>` + ); + await elementUpdated(el); + const left = () => + el.renderRoot.querySelector('image')!.getBoundingClientRect().left; + const start = left(); + + el.logoMargin = 2; + await elementUpdated(el); + // Firefox measures the layout in sixtieths of a pixel. + expect(left() - start).to.be.closeTo(2, 1 / 60); + }); + it('does not render an image when logoMargin consumes the entire logo box', async () => { // With logo-size="0" the box collapses to zero; no image should render. const el = await fixture<IgcQrCodeComponent>( @@ -1075,6 +1637,171 @@ describe('IgcQrCodeComponent', () => { // The cutout stays clear of the format information in row and column 8. expect(cut.x).to.be.at.least((el.margin + 9) * moduleSize - EPSILON); }); + + it('keeps one cut rectangle and no clip for a square logo', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code + value="https://example.com" + logo-size="1" + logo-src=${VALID_LOGO} + ></igc-qr-code>` + ); + + expect(el.renderRoot.querySelectorAll('mask rect')).to.have.length(2); + expect(el.renderRoot.querySelector('clipPath')).to.be.null; + expect(el.renderRoot.querySelector('image')!.hasAttribute('clip-path')) + .to.be.false; + }); + + for (const [logoShape, logo, name] of [ + ['circle', VALID_LOGO, 'circle'], + ['rounded', VALID_LOGO, 'rounded'], + ['squircle', VALID_LOGO, 'squircle'], + ['circle', WIDE_LOGO, 'wide ellipse'], + ['squircle', WIDE_LOGO, 'wide squircle'], + ] as const) { + it(`cuts the modules that a ${name} logo covers, and clips the image to it`, async () => { + // With no margin, one module is one SVG unit. + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code + value="https://example.com" + margin="0" + logo-size="1" + logo-shape=${logoShape} + logo-src=${logo} + ></igc-qr-code>` + ); + const image = el.renderRoot.querySelector('image')!; + if (logo === WIDE_LOGO) { + await waitUntil( + () => readBox(image).width > 1.9 * readBox(image).height, + 'The wide logo did not load.' + ); + } + const clip = el.renderRoot.querySelector('clipPath')!; + const shape = clip.querySelector('path')!; + const box = readBox(image); + const cuts = Array.from( + el.renderRoot.querySelectorAll('mask rect ~ rect'), + readBox + ); + const inShape = (x: number, y: number) => + shape.isPointInFill(new DOMPoint(x, y)); + const inCut = (x: number, y: number) => + cuts.some( + (cut) => + x >= cut.x && + x <= cut.x + cut.width && + y >= cut.y && + y <= cut.y + cut.height + ); + + expect(image.getAttribute('clip-path')).to.equal(`url(#${clip.id})`); + + // The cutout holds each point of the shape. + for (let i = 0; i <= 40; i++) { + for (let j = 0; j <= 40; j++) { + const x = box.x + (box.width * i) / 40; + const y = box.y + (box.height * j) / 40; + if (inShape(x, y)) { + expect(inCut(x, y), `${x}, ${y}`).to.be.true; + } + } + } + + // Each cut module overlaps the shape: the point of its cell nearest to the center of + // the logo, moved a little toward the center, is in the shape. + const cx = box.x + box.width / 2; + const cy = box.y + box.height / 2; + const nearest = (center: number, cell: number) => { + const point = clamp(center, cell, cell + 1); + return point + Math.sign(center - point) * 0.02; + }; + for (const cut of cuts) { + for (let row = cut.y; row < cut.y + cut.height; row++) { + for (let col = cut.x; col < cut.x + cut.width; col++) { + expect( + inShape(nearest(cx, col), nearest(cy, row)), + `${row}, ${col}` + ).to.be.true; + } + } + } + }); + } + + it('clips a shaped logo to the logo box less logo-margin', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code + value="https://example.com" + logo-size="1" + logo-margin="6" + logo-shape="circle" + logo-src=${VALID_LOGO} + ></igc-qr-code>` + ); + const box = readBox(el.renderRoot.querySelector('image')!); + const shape = + el.renderRoot.querySelector<SVGPathElement>('clipPath path')!; + const inShape = (x: number, y: number) => + shape.isPointInFill(new DOMPoint(x, y)); + const middle = box.y + box.height / 2; + + expect(inShape(box.x + 0.01, middle)).to.be.true; + expect(inShape(box.x - 0.01, middle)).to.be.false; + expect(inShape(box.x + box.width + 0.01, middle)).to.be.false; + }); + + it('keeps a larger logo of each other shape than of a square on a pinned version', async () => { + const widths: Record<string, number> = {}; + + for (const logoShape of [ + 'square', + 'circle', + 'rounded', + 'squircle', + ] as const) { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code + value="test" + version="1" + error-level="H" + logo-size="1" + logo-shape=${logoShape} + logo-src=${VALID_LOGO} + ></igc-qr-code>` + ); + widths[logoShape] = readBox( + el.renderRoot.querySelector('image')! + ).width; + } + + for (const logoShape of ['circle', 'rounded', 'squircle']) { + expect(widths[logoShape], logoShape).to.be.greaterThan(widths.square); + } + }); + + it('redraws the dots when the cutout changes', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code + value="https://example.com" + dot-style="rounded" + logo-size="1" + logo-src=${VALID_LOGO} + ></igc-qr-code>` + ); + const dots = () => + el.renderRoot.querySelector('[part~="dots"]')!.getAttribute('d'); + const square = dots(); + + el.logoShape = 'circle'; + await elementUpdated(el); + expect(dots()).not.to.equal(square); + + el.logoShape = 'square'; + await elementUpdated(el); + expect(dots()).to.equal(square); + }); }); }); @@ -1234,6 +1961,44 @@ describe('IgcQrCodeComponent', () => { expect(svg.querySelector('mask')).to.exist; }); + it('keeps the clip of a shaped logo', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code + value="https://example.com" + logo-shape="squircle" + logo-src=${LOGO} + ></igc-qr-code>` + ); + + const svg = await parseSvg(await el.toBlob()); + const clip = svg.querySelector('clipPath')!; + expect(svg.querySelector('image')!.getAttribute('clip-path')).to.equal( + `url(#${clip.id})` + ); + }); + + it('writes the gradient colors and paint into the export', async () => { + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code + value="https://example.com" + gradient="linear" + style="--ig-qr-code-gradient-start: rgb(255, 0, 0); --ig-qr-code-gradient-end: rgb(0, 0, 255);" + ></igc-qr-code>` + ); + + const svg = await parseSvg(await el.toBlob()); + const gradient = svg.querySelector('linearGradient')!; + expect( + Array.from(gradient.querySelectorAll('stop'), (stop) => + stop.getAttribute('stop-color') + ) + ).to.deep.equal(['rgb(255, 0, 0)', 'rgb(0, 0, 255)']); + + for (const part of svg.querySelectorAll('g path')) { + expect(part.getAttribute('fill')).to.equal(`url(#${gradient.id})`); + } + }); + it('leaves no empty host relation in the exported SVG', async () => { const container = await fixture<HTMLElement>(html` <div> @@ -1325,6 +2090,23 @@ describe('IgcQrCodeComponent', () => { expect(svg.querySelector('[mask]')).to.be.null; }); + it('keeps the gradient when the logo cannot be fetched', async () => { + stub(window, 'fetch').rejects(new TypeError('CORS')); + const el = await fixture<IgcQrCodeComponent>( + html`<igc-qr-code + value="https://example.com" + gradient="radial" + logo-shape="circle" + logo-src=${createLogoUrl()} + ></igc-qr-code>` + ); + + const svg = await parseSvg(await el.toBlob()); + expect(svg.querySelector('mask')).to.be.null; + expect(svg.querySelector('clipPath')).to.be.null; + expect(svg.querySelector('radialGradient')).to.exist; + }); + it('drops the logo when the logo request fails', async () => { const fetchStub = stub(window, 'fetch').resolves( new Response('', { status: 404 }) @@ -1690,6 +2472,13 @@ describe('IgcQrCodeComponent', () => { // Version 12 at level M, with many alignment patterns. const LONG_VALUE = `${PRODUCT_URL}?a=${PRODUCT_URL}&b=${PRODUCT_URL}&c=${PRODUCT_URL}`; const SHAPES = ['square', 'circle', 'rounded', 'squircle'] as const; + const OTHER_DOT_STYLES = [ + 'diamond', + 'plus', + 'liquid', + 'horizontal-bars', + 'vertical-bars', + ] as const; function solidLogo(color: string): string { const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"><rect width="1" height="1" fill="${color}"/></svg>`; @@ -1698,17 +2487,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<IgcQrCodeComponent>( @@ -1726,11 +2505,119 @@ describe('IgcQrCodeComponent', () => { const image = await el.toImage({ scale: Math.ceil((6 * modules) / el.size), }); - const [result] = await readBarcodes(image, { - formats: ['QRCode'], - maxNumberOfSymbols: 1, + return (await readQr(image))?.text; + } + + /** Exports the code with `pixels` pixels for each module, and returns the text read from it. */ + async function scanAt(pixels: number): Promise<string | undefined> { + await elementUpdated(el); + const modules = getSide(el) + 2 * el.margin; + const image = await el.toImage({ scale: (pixels * modules) / el.size }); + return (await readQr(image))?.text; + } + + // Sizes where the old geometry failed. A square dot draws as a circle, so it covers `circle`. + it('reads a circle corner square with each corner dot', async () => { + Object.assign(el, { dotStyle: 'circle', squareStyle: 'circle' }); + + for (const cornerDotStyle of ['square', 'rounded', 'squircle'] as const) { + for (const [value, version] of [ + ['https://example.com/', 3], + [PRODUCT_URL, 10], + ] as const) { + Object.assign(el, { value, version, cornerDotStyle }); + + for (const pixels of [7, 8, 9]) { + expect( + await scanAt(pixels), + `${cornerDotStyle}, ${version}, ${pixels}` + ).to.equal(value); + } + } + } + }); + + for (const squareStyle of [...SHAPES, 'leaf'] as const) { + it(`reads the alignment patterns of square-style="${squareStyle}"`, async () => { + Object.assign(el, { value: LONG_VALUE, squareStyle }); + + for (const dotStyle of [...SHAPES, ...OTHER_DOT_STYLES]) { + el.dotStyle = dotStyle; + + for (const pixels of [7, 8]) { + expect(await scanAt(pixels), `${dotStyle}, ${pixels}`).to.equal( + LONG_VALUE + ); + } + } + }); + } + + for (const dotStyle of OTHER_DOT_STYLES) { + it(`reads dot-style="${dotStyle}" at full size and at the smallest dot-scale`, async () => { + el.dotStyle = dotStyle; + expect(await scan()).to.equal(PRODUCT_URL); + + el.dotScale = 0; + expect(await scan()).to.equal(PRODUCT_URL); + + el.value = LONG_VALUE; + expect(await scan()).to.equal(LONG_VALUE); + }); + } + + // A leaf with fully round corners failed at these sizes. + for (const [name, pairs] of [ + [ + 'a leaf corner square with each corner dot', + [...SHAPES, 'leaf'].map((cornerDotStyle) => ({ + squareStyle: 'leaf', + cornerDotStyle, + })), + ], + // A circle ring draws a leaf dot as a circle, which the circle scans cover. + [ + 'a leaf corner dot in each corner square', + ['square', 'rounded', 'squircle'].map((squareStyle) => ({ + squareStyle, + cornerDotStyle: 'leaf', + })), + ], + ] as const) { + it(`reads ${name}`, async () => { + el.dotStyle = 'circle'; + + for (const styles of pairs) { + for (const [value, version] of [ + ['https://example.com/', 3], + [LONG_VALUE, 12], + ] as const) { + Object.assign(el, { ...styles, value, version }); + + for (const pixels of [7, 9]) { + expect( + await scanAt(pixels), + `${styles.squareStyle}, ${styles.cornerDotStyle}, ${version}, ${pixels}` + ).to.equal(value); + } + } + } + }); + } + + for (const [index, dotStyle] of OTHER_DOT_STYLES.entries()) { + // The Latin square of the basic shapes below, for the corners of each other dot style. + it(`reads dot-style="${dotStyle}" with each corner shape`, async () => { + el.dotStyle = dotStyle; + + for (const [offset, squareStyle] of SHAPES.entries()) { + const cornerDotStyle = SHAPES[(index + offset) % SHAPES.length]; + Object.assign(el, { squareStyle, cornerDotStyle }); + expect(await scan(), `${squareStyle}, ${cornerDotStyle}`).to.equal( + PRODUCT_URL + ); + } }); - return result?.text; } for (const [index, dotStyle] of SHAPES.entries()) { @@ -1785,6 +2672,94 @@ describe('IgcQrCodeComponent', () => { }); } + for (const logoShape of ['circle', 'rounded', 'squircle'] as const) { + it(`reads a ${logoShape} logo on small codes`, async () => { + el.logoShape = logoShape; + + for (const value of ['test', 'https://example.com/']) { + for (const errorLevel of ['L', 'M', 'Q', 'H'] as const) { + for (const color of ['#fff', '#000']) { + Object.assign(el, { + value, + errorLevel, + logoSrc: solidLogo(color), + logoSize: 1, + }); + expect( + await scan(), + `${value}, ${errorLevel}, ${color}` + ).to.equal(value); + } + } + } + }); + } + + it('reads a wide and a pinned shaped logo', async () => { + for (const logoShape of ['circle', 'rounded', 'squircle'] as const) { + for (const errorLevel of ['M', 'H'] as const) { + Object.assign(el, { + value: PRODUCT_URL, + version: undefined, + logoShape, + errorLevel, + logoSrc: WIDE_LOGO, + logoSize: 1, + logoMargin: 3, + }); + expect(await scan(), `${logoShape}, wide, ${errorLevel}`).to.equal( + PRODUCT_URL + ); + } + + for (const version of [1, 2, 3]) { + Object.assign(el, { + value: 'test', + version, + errorLevel: 'H', + logoSrc: solidLogo('#000'), + logoMargin: undefined, + }); + expect(await scan(), `${logoShape}, V${version}`).to.equal('test'); + } + } + }); + + it('reads the joining styles that end at the logo cutout', async () => { + Object.assign(el, { logoSrc: solidLogo('#000'), logoSize: 1 }); + + for (const dotStyle of [ + 'rounded', + 'liquid', + 'horizontal-bars', + 'vertical-bars', + ] as const) { + for (const logoShape of ['square', 'circle'] as const) { + for (const value of [PRODUCT_URL, LONG_VALUE]) { + Object.assign(el, { dotStyle, logoShape, value }); + expect(await scan(), `${dotStyle}, ${logoShape}`).to.equal(value); + } + } + } + }); + + for (const gradient of ['linear', 'radial'] as const) { + it(`reads a ${gradient} gradient between two dark colors`, async () => { + el.style.setProperty('--ig-qr-code-gradient-start', '#1a237e'); + el.style.setProperty('--ig-qr-code-gradient-end', '#880e4f'); + Object.assign(el, { gradient, dotStyle: 'circle' }); + + for (const gradientAngle of gradient === 'linear' + ? [0, 45, 135] + : [0]) { + for (const value of [PRODUCT_URL, LONG_VALUE]) { + Object.assign(el, { gradientAngle, value }); + expect(await scan(), `${gradientAngle}`).to.equal(value); + } + } + }); + } + it('reads a logo on a pinned small version', async () => { Object.assign(el, { value: 'test', logoSize: 1 }); @@ -1817,5 +2792,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/qr-code.ts b/src/components/qr-code/qr-code.ts index b6e927304..263e32f91 100644 --- a/src/components/qr-code/qr-code.ts +++ b/src/components/qr-code/qr-code.ts @@ -1,5 +1,7 @@ import { html, LitElement, nothing, type PropertyValues } from 'lit'; import { property, state } from 'lit/decorators.js'; +import { ifDefined } from 'lit/directives/if-defined.js'; +import { styleMap } from 'lit/directives/style-map.js'; import { createAbortHandle } from '#internals/abort-handler.js'; import { ariaBindings, @@ -31,13 +33,18 @@ import { MIME_TYPES, rasterizeSvg, serializeSvg, + snapSvg, } from './renderer/export.js'; +import { type CodeGrid, resolveCornerDotStyle } from './renderer/helpers.js'; import { fitLogo, type LogoLayout } from './renderer/logo.js'; +import { snapToPixels } from './renderer/snap.js'; import { DEFAULT_SIZE_RATIO, MAX_SAFE_AREA, + renderQrAlignment, renderQrDots, renderQrFinders, + renderQrGradient, renderQrMaskAndImage, SAFE_AREAS, } from './renderer/templates.js'; @@ -51,9 +58,11 @@ import type { QrCornerSquareStyle, QrDotStyle, QrErrorCorrectionLevel, + QrGradient, + QrLogoShape, } from './types.js'; -const nextMaskId = createIdGenerator('igc-qr-code-mask'); +const nextId = createIdGenerator('igc-qr-code'); /** The logo layout, and the version to request for it: unset keeps the automatic version. */ type LogoFit = { version?: number; layout: LogoLayout }; @@ -71,14 +80,17 @@ const BLOCKED_LOGO_SOURCE = /^\s*(?:javascript:|vbscript:|data:(?!image\/))/i; * @element igc-qr-code * * @cssproperty --ig-qr-code-background - The background color of the QR code. Default is `white`. - * @cssproperty --ig-qr-code-dark-color - The color of the data modules (dots), and the corner square/dot colors unless overridden below. Default is `black`. + * @cssproperty --ig-qr-code-dark-color - The color of the data modules (dots) and the alignment patterns, and the corner square/dot colors unless overridden below. Default is `black`. * @cssproperty --ig-qr-code-corner-square-color - The color of the outer finder-pattern corner squares. Defaults to `--ig-qr-code-dark-color`. * @cssproperty --ig-qr-code-corner-dot-color - The color of the inner finder-pattern corner dots. Defaults to `--ig-qr-code-dark-color`. + * @cssproperty --ig-qr-code-gradient-start - The start color of the `gradient`. Defaults to `--ig-qr-code-dark-color`. + * @cssproperty --ig-qr-code-gradient-end - The end color of the `gradient`. Defaults to `--ig-qr-code-dark-color`. * * @csspart background - The background rect of the QR code. * @csspart dots - The data modules (dots) of the QR code. * @csspart corner-square - The outer corner (finder-pattern) squares of the QR code. * @csspart corner-dot - The inner corner (finder-pattern) dots of the QR code. + * @csspart alignment - The alignment patterns of the QR code, from version 2. */ export default class IgcQrCodeComponent extends HostAriaMixin(LitElement) { public static readonly tagName = 'igc-qr-code'; @@ -91,8 +103,7 @@ export default class IgcQrCodeComponent extends HostAriaMixin(LitElement) { } private readonly _abortHandle = createAbortHandle(); - private readonly _maskId = nextMaskId(); - private readonly _maskUrl = `url(#${this._maskId})`; + private readonly _id = nextId(); private _logoReady: Promise<void> = Promise.resolve(); private _matrixCache?: { value: string; @@ -166,6 +177,10 @@ export default class IgcQrCodeComponent extends HostAriaMixin(LitElement) { /** * The size of the QR code in pixels. This determines the width and height of the generated QR code. The default value is 128 pixels. * + * Each module covers a whole number of pixels, so the edges stay sharp. The pixels that are + * left over widen the quiet zone, and the code can be smaller than `size`. An exported image + * gets whole pixels at its own size. + * * @attr size * @default 128 */ @@ -175,7 +190,7 @@ export default class IgcQrCodeComponent extends HostAriaMixin(LitElement) { /** * The margin (quiet zone) around the QR code, expressed as a number of QR code modules rather * than pixels. This is the blank border area surrounding the code, which helps ensure that it - * can be properly scanned. + * can be properly scanned. It is a minimum: spare pixels make the quiet zone wider. * * @attr margin * @default 4 @@ -223,10 +238,26 @@ export default class IgcQrCodeComponent extends HostAriaMixin(LitElement) { @property({ type: Number, attribute: 'logo-margin' }) public logoMargin?: number; + /** + * The shape of the logo: 'square', 'circle', 'rounded' or 'squircle'. The shape fills the logo + * box, so a 'circle' logo with a wide image is an ellipse. The image is clipped to the shape, + * and the cutout holds only the modules that the shape covers, in part or in full. + * + * @attr logo-shape + * @default 'square' + */ + @property({ attribute: 'logo-shape' }) + public logoShape: QrLogoShape = 'square'; + /** * The style of the data modules (dots) in the QR code. This can be 'square', 'circle', - * 'rounded', or 'squircle'. The inner dot of each finder-pattern corner uses the same style - * unless `cornerDotStyle` is set. + * 'rounded', 'squircle', 'diamond', 'plus', 'liquid', 'horizontal-bars' or 'vertical-bars'. + * 'liquid' is 'rounded' with a smooth fill in the inside corners where modules join. The bar + * styles draw each run of dark modules in a row or a column as one bar with round ends. + * + * The inner dot of each finder-pattern corner uses the same style unless `cornerDotStyle` is + * set. It draws 'diamond' and 'plus' as 'square', and 'liquid' and the bar styles as + * 'rounded'. * * @attr dot-style * @default 'square' @@ -237,8 +268,10 @@ export default class IgcQrCodeComponent extends HostAriaMixin(LitElement) { /** * The size of each data module, as a ratio of its cell in the module grid. The value is a * number from 0.7 to 1. Other values are clamped. A value below 1 leaves a gap between the - * modules, so 'rounded' modules do not join their neighbors. The finder-pattern corners keep - * their full size. A smaller value can make the code harder to scan with a camera. + * modules, so 'rounded' modules do not join their neighbors, and 'liquid' draws as 'rounded'. + * For the bar styles, it sets the thickness of the bars and shortens their ends. The + * finder-pattern corners keep their full size. A smaller value can make the code harder to + * scan with a camera. * * @attr dot-scale * @default 1 @@ -248,7 +281,9 @@ export default class IgcQrCodeComponent extends HostAriaMixin(LitElement) { /** * The style of the corner squares in the QR code. This can be 'square', 'circle', 'rounded', - * or 'squircle'. + * 'squircle' or 'leaf'. A 'leaf' has two opposite round corners on the diagonal toward the + * center of the code. The rings of the alignment patterns use the same style, and a 'leaf' + * ring there has the shape of the top-left corner square. * * @attr square-style * @default 'square' @@ -258,13 +293,41 @@ export default class IgcQrCodeComponent extends HostAriaMixin(LitElement) { /** * The style of the inner dot of each finder-pattern corner. This can be 'square', 'circle', - * 'rounded', or 'squircle'. When it is not set, the inner dot uses `dotStyle`. + * 'rounded', 'squircle' or 'leaf'. When it is not set, the inner dot uses `dotStyle`. The + * centers of the alignment patterns use the same style. + * + * In a 'circle' corner square, a 'square' or 'leaf' dot draws as 'circle', because scanners + * do not find the pattern reliably with corners in a round ring. * * @attr corner-dot-style */ @property({ attribute: 'corner-dot-style' }) public cornerDotStyle?: QrCornerDotStyle; + /** + * The gradient of the dark modules: 'linear' or 'radial'. When it is not set, or has another + * value, the modules have one color. The gradient goes from `--ig-qr-code-gradient-start` to + * `--ig-qr-code-gradient-end` over the code without its quiet zone. It also paints the corners, + * unless `--ig-qr-code-corner-square-color` or `--ig-qr-code-corner-dot-color` is set. + * + * Keep both colors much darker than the background. + * + * @attr gradient + */ + @property() + public gradient?: QrGradient; + + /** + * The angle of a 'linear' gradient in degrees, clockwise. At 0 the gradient goes from left to + * right, and at 90 from top to bottom. + * + * @attr gradient-angle + * @default 0 + */ + @property({ type: Number, attribute: 'gradient-angle' }) + @coercedProperty<number>({ transform: ({ value }) => asNumber(value, 0) }) + public gradientAngle = 0; + /** @internal */ protected override update(props: PropertyValues<this>): void { if (props.has('logoSrc')) { @@ -367,12 +430,14 @@ export default class IgcQrCodeComponent extends HostAriaMixin(LitElement) { ): LogoFit | null { const version = this.version; const aspectRatio = this._logoAspectRatio; + const shape = this.logoShape; const settings = JSON.stringify([ value, errorLevel, version, area, aspectRatio, + shape, ]); if (this._logoFitCache?.settings === settings) { @@ -387,6 +452,7 @@ export default class IgcQrCodeComponent extends HostAriaMixin(LitElement) { errorLevel, area, aspectRatio, + shape, }); fit = { version: fitted.version === smallest ? version : fitted.version, @@ -470,7 +536,10 @@ export default class IgcQrCodeComponent extends HostAriaMixin(LitElement) { return dimension; } - /** Serializes a snapshot resized to `scale`, measured from its rendered width. */ + /** + * Serializes a snapshot resized to `scale`, measured from its rendered width, with the + * modules on whole pixels of the new size. + */ private async _serializeSnapshot( scale: number ): Promise<{ blob: Blob; dimension: number }> { @@ -481,6 +550,7 @@ export default class IgcQrCodeComponent extends HostAriaMixin(LitElement) { ); svg.setAttribute('width', `${dimension}`); svg.setAttribute('height', `${dimension}`); + snapSvg(svg, dimension, this.margin); return { blob: serializeSvg(svg), dimension }; } @@ -609,20 +679,51 @@ export default class IgcQrCodeComponent extends HostAriaMixin(LitElement) { const totalModules = size + this.margin * 2; const moduleSize = size / totalModules; - const marginPx = this.margin * moduleSize; const svgSize = moduleSize * totalModules; + const grid: CodeGrid = { + size, + moduleSize, + marginPx: this.margin * moduleSize, + svgSize, + }; + const snap = snapToPixels(this.size, size, this.margin); + + const patternOptions = { + grid, + squareStyle: this.squareStyle, + dotStyle: resolveCornerDotStyle( + this.squareStyle, + this.cornerDotStyle, + this.dotStyle + ), + }; + const maskId = `${this._id}-mask`; const { mask, image, shouldApplyMask } = renderQrMaskAndImage({ src: this.logoSrc!, layout: fit?.layout, - size: this.size, + unitSize: (this.size / svgSize) * (snap?.scale ?? 1), margin: this.logoMargin, - svgSize, - moduleSize, - marginPx, - maskId: this._maskId, + grid, + maskId, + clipId: `${this._id}-clip`, + transform: snap?.transform, }); + const gradientId = `${this._id}-gradient`; + const gradientType = + this.gradient === 'linear' || this.gradient === 'radial' + ? this.gradient + : undefined; + const gradient = gradientType + ? renderQrGradient({ + id: gradientId, + gradient: gradientType, + angle: this.gradientAngle, + grid, + }) + : nothing; + return html` <svg ${ariaBindings(hostAria(this, { ownLabel: true }))} @@ -635,22 +736,23 @@ export default class IgcQrCodeComponent extends HostAriaMixin(LitElement) { <title>${this.ariaLabel ?? `QR code: ${this.value}`} - ${mask} - + ${mask} ${gradient} + ${renderQrDots({ matrix, - moduleSize, - marginPx, + grid, dotStyle: this.dotStyle, dotScale: this._getDotScale(), + cutout: shouldApplyMask ? fit?.layout.cutout : undefined, })} - ${renderQrFinders({ - size, - moduleSize, - marginPx, - dotStyle: this.cornerDotStyle || this.dotStyle, - squareStyle: this.squareStyle, - })} + ${renderQrAlignment(patternOptions)} + ${renderQrFinders(patternOptions)} ${image} diff --git a/src/components/qr-code/renderer/export.ts b/src/components/qr-code/renderer/export.ts index 3947ef1ee..0cbc989e2 100644 --- a/src/components/qr-code/renderer/export.ts +++ b/src/components/qr-code/renderer/export.ts @@ -1,4 +1,6 @@ +import { setOrRemoveAttribute } from '#internals/utils/dom.js'; import type { QrCodeExportFormat } from '../types.js'; +import { snapToPixels } from './snap.js'; type QrRasterFormat = Exclude; @@ -61,20 +63,24 @@ async function fetchImageAsDataUrl(url: string): Promise { } /** - * Copies the computed `fill` of each `part` element onto the clone and strips `part`, - * so the clone renders the same outside the shadow root. The theme sets only `fill`; - * extend this when `themes/shared/qr-code.common.scss` styles more. + * Copies the computed `fill` of each part and `stop-color` of each gradient stop onto the clone + * and strips `part`, so the clone renders the same outside the shadow root. Extend this when + * `themes/shared/qr-code.common.scss` styles more. */ function resolveStyles(source: SVGSVGElement, clone: SVGSVGElement): void { - const liveParts = source.querySelectorAll('[part]'); - const cloneParts = clone.querySelectorAll('[part]'); - - for (const [index, element] of liveParts.entries()) { - const target = cloneParts[index]; - const { fill } = getComputedStyle(element); - - if (fill) { - target.setAttribute('fill', fill); + const selector = '[part], stop'; + const liveElements = source.querySelectorAll(selector); + const cloneElements = clone.querySelectorAll(selector); + + for (const [index, element] of liveElements.entries()) { + const target = cloneElements[index]; + const { fill, stopColor } = getComputedStyle(element); + + if (element.localName === 'stop') { + target.setAttribute('stop-color', stopColor); + } else if (fill) { + // SVG 1.1 readers take `url(#id)` without quotes. + target.setAttribute('fill', fill.replace(/^url\("(.*)"\)$/, 'url($1)')); } target.removeAttribute('part'); } @@ -99,7 +105,9 @@ async function inlineLogo(clone: SVGSVGElement): Promise { } else { image.remove(); clone.querySelector('[mask]')?.removeAttribute('mask'); - clone.querySelector('defs')?.remove(); + for (const element of clone.querySelectorAll('mask, clipPath')) { + element.remove(); + } } } @@ -134,6 +142,23 @@ export async function createSvgSnapshot( return clone; } +/** + * Puts the modules of a snapshot on whole pixels of an image of `pixels`: rewrites the transform + * of the code group and of the logo, which the component renders for its own size. + */ +export function snapSvg( + svg: SVGSVGElement, + pixels: number, + margin: number +): void { + const side = Math.round(svg.viewBox.baseVal.width); + const transform = snapToPixels(pixels, side, margin)?.transform; + + for (const element of svg.querySelectorAll(':scope > g, :scope > image')) { + setOrRemoveAttribute(element, 'transform', transform); + } +} + /** Serializes an SVG element into an `image/svg+xml` blob. */ export function serializeSvg(svg: SVGSVGElement): Blob { const markup = new XMLSerializer().serializeToString(svg); diff --git a/src/components/qr-code/renderer/helpers.ts b/src/components/qr-code/renderer/helpers.ts index ae45b271d..2f107b283 100644 --- a/src/components/qr-code/renderer/helpers.ts +++ b/src/components/qr-code/renderer/helpers.ts @@ -1,63 +1,128 @@ +import { forEachModule, type ModuleRange } from '../model/cutout.js'; +import { getAlignmentPatternCenters } from '../model/matrix.js'; import type { QrCornerDotStyle, QrCornerSquareStyle, QrDotStyle, } from '../types.js'; -function squarePath(x: number, y: number, s: number): string { - return `M${x},${y}h${s}v${s}h${-s}Z`; +/** A box in SVG units. */ +export type Box = { x: number; y: number; width: number; height: number }; + +/** The modules of a code in SVG units: the side of a module, and the quiet zone before the first. */ +export type ModuleGrid = { moduleSize: number; marginPx: number }; + +/** A code of `size` modules on a view box with the side `svgSize`. */ +export type CodeGrid = ModuleGrid & { size: number; svgSize: number }; + +/** Converts a module index to an SVG coordinate. */ +export function moduleToPx( + index: number, + { moduleSize, marginPx }: ModuleGrid +): number { + return index * moduleSize + marginPx; } -function circlePath(cx: number, cy: number, r: number, sweep = 0): string { +//#region Shapes + +function squarePath(x: number, y: number, side: number): string { + return `M${x},${y}h${side}v${side}h${-side}Z`; +} + +function ellipsePath( + cx: number, + cy: number, + rx: number, + ry: number, + sweep = 0 +): string { return ( - `M${cx - r},${cy}` + - `a${r},${r} 0 1,${sweep} ${r * 2},0` + - `a${r},${r} 0 1,${sweep} ${-r * 2},0z` + `M${cx - rx},${cy}` + + `a${rx},${ry} 0 1,${sweep} ${rx * 2},0` + + `a${rx},${ry} 0 1,${sweep} ${-rx * 2},0z` ); } +function circlePath(cx: number, cy: number, r: number, sweep = 0): string { + return ellipsePath(cx, cy, r, r, sweep); +} + +/** Returns the path of an ellipse that fills `box`. */ +export function ellipseBoxPath({ x, y, width, height }: Box): string { + return ellipsePath(x + width / 2, y + height / 2, width / 2, height / 2); +} + /** * The distance of the cubic control points from the axis, as a ratio of the half side, that puts * the curve on the superellipse |x|⁴ + |y|⁴ = 1 at 45°: (2^-¼ - ½) / ⅜. */ const SQUIRCLE_KAPPA = 0.909_057; -/** The relative cubics of the last squircle side, which all the data modules share. */ -let squircleCurves = { side: Number.NaN, path: '' }; - -/** Returns the path of a squircle that fills the square of side `s` at `x`, `y`. */ -function squirclePath(x: number, y: number, s: number): string { - if (squircleCurves.side !== s) { - const round = (value: number) => Number(value.toFixed(4)); - const h = round(s / 2); - const d = round((s / 2) * (1 - SQUIRCLE_KAPPA)); - const k = round(h - d); - // One cubic for each quadrant, clockwise from the middle of the right side. - squircleCurves = { - side: s, - path: - `c0,${k} ${-d},${h} ${-h},${h}` + - `s${-h},${-d} ${-h},${-h}` + - `s${d},${-h} ${h},${-h}` + - `s${h},${d} ${h},${h}z`, - }; - } +/** The corner radius of a `rounded` module and of a `liquid` fillet, per module side. */ +const ROUNDED_RADIUS = 0.45; - return `M${x + s},${y + s / 2}${squircleCurves.path}`; +/** Returns `build`, memoized for the last side: the relative path that modules of one size share. */ +function cachedBySide( + build: (side: number) => string +): (side: number) => string { + let lastSide = Number.NaN; + let path = ''; + return (side) => { + if (side !== lastSide) { + lastSide = side; + path = build(side); + } + return path; + }; } -function roundedRect( - x: number, - y: number, - width: number, - height: number, - radius: number -): string { - const cr = Math.min(radius, width / 2, height / 2); - return roundedRectPerCorner(x, y, width, height, cr, cr, cr, cr); +/** + * Returns the relative path of a squircle of `width` by `height`: one cubic for each quadrant, + * clockwise from the middle of the right side. + */ +function squircleCurves(width: number, height: number): string { + const round = (value: number) => Number(value.toFixed(4)); + const w = round(width / 2); + const h = round(height / 2); + const dx = round(w * (1 - SQUIRCLE_KAPPA)); + const dy = round(h * (1 - SQUIRCLE_KAPPA)); + return ( + `c0,${round(h - dy)} ${-dx},${h} ${-w},${h}` + + `s${-w},${-dy} ${-w},${-h}` + + `s${dx},${-h} ${w},${-h}` + + `s${w},${dy} ${w},${h}z` + ); +} + +const squircleTail = cachedBySide((side) => squircleCurves(side, side)); + +/** Returns the path of a squircle that fills `box`. */ +export function squircleBoxPath({ x, y, width, height }: Box): string { + const curves = + width === height ? squircleTail(width) : squircleCurves(width, height); + return `M${x + width},${y + height / 2}${curves}`; } -function roundedRectPerCorner( +function squirclePath(x: number, y: number, side: number): string { + return squircleBoxPath({ x, y, width: side, height: side }); +} + +/** Draws a corner of radius `r` to `dx`, `dy`; `horizontal` when the edge before it is. */ +type CornerCommand = ( + r: number, + dx: number, + dy: number, + horizontal: boolean +) => string; + +const quadCorner: CornerCommand = (_r, dx, dy, horizontal) => + horizontal ? `q${dx},0 ${dx},${dy}` : `q0,${dy} ${dx},${dy}`; + +const arcCorner: CornerCommand = (r, dx, dy) => + r ? `a${r},${r} 0 0 1 ${dx},${dy}` : ''; + +/** Returns the path of a rectangle with a radius for each corner, drawn with `corner`. */ +function rectPerCorner( x: number, y: number, width: number, @@ -65,182 +130,558 @@ function roundedRectPerCorner( rTL: number, rTR: number, rBR: number, - rBL: number + rBL: number, + corner: CornerCommand ): string { return ( `M${x + rTL},${y}` + - `h${width - rTL - rTR}` + - `q${rTR},0 ${rTR},${rTR}` + - `v${height - rTR - rBR}` + - `q0,${rBR} ${-rBR},${rBR}` + - `h${-(width - rBR - rBL)}` + - `q${-rBL},0 ${-rBL},${-rBL}` + - `v${-(height - rBL - rTL)}` + - `q0,${-rTL} ${rTL},${-rTL}z` + `h${width - rTL - rTR}${corner(rTR, rTR, rTR, true)}` + + `v${height - rTR - rBR}${corner(rBR, -rBR, rBR, false)}` + + `h${-(width - rBR - rBL)}${corner(rBL, -rBL, -rBL, true)}` + + `v${-(height - rBL - rTL)}${corner(rTL, rTL, -rTL, false)}z` + ); +} + +function roundedRect( + x: number, + y: number, + width: number, + height: number, + radius: number +): string { + const r = Math.min(radius, width / 2, height / 2); + return rectPerCorner(x, y, width, height, r, r, r, r, quadCorner); +} + +/** Returns the path of `box` with circular corners of `radius`. */ +export function arcBoxPath( + { x, y, width, height }: Box, + radius: number +): string { + return rectPerCorner( + x, + y, + width, + height, + radius, + radius, + radius, + radius, + arcCorner ); } +const diamondTail = cachedBySide((side) => { + const half = side / 2; + return `l${half},${half}l${-half},${half}l${-half},${-half}z`; +}); + +function diamondPath(x: number, y: number, side: number): string { + return `M${x + side / 2},${y}${diamondTail(side)}`; +} + +const plusTail = cachedBySide((side) => { + const arm = side / 4; + return `h${2 * arm}v${arm}h${arm}v${2 * arm}h${-arm}v${arm}h${-2 * arm}v${-arm}h${-arm}v${-2 * arm}h${arm}z`; +}); + +/** Returns the path of a cross with arms half as wide as the square of `side` at `x`, `y`. */ +function plusPath(x: number, y: number, side: number): string { + return `M${x + side / 4},${y}${plusTail(side)}`; +} + /** - * Returns the SVG path of the data module at row `r` and column `c`, in a cell of side `s` - * at `x`, `y`. The module is `scale` times the cell, centered in it. A `'rounded'` module - * keeps a square corner toward each dark neighbor that it touches. + * Returns a square whose top-left and bottom-right corners, or the other two on the + * `antiDiagonal`, are round at a quarter of the side. A larger radius fails to decode. */ -function dotPath( - data: boolean[][], - r: number, - c: number, +function leafPath( x: number, y: number, - s: number, - style: QrDotStyle, - scale: number + side: number, + antiDiagonal: boolean ): string { - const size = s * scale; - const inset = (s - size) / 2; + const radius = side / 4; + const [topLeft, topRight] = antiDiagonal ? [0, radius] : [radius, 0]; + return rectPerCorner( + x, + y, + side, + side, + topLeft, + topRight, + topLeft, + topRight, + arcCorner + ); +} - switch (style) { - case 'square': - return squarePath(x + inset, y + inset, size); - case 'circle': - return circlePath(x + s / 2, y + s / 2, size / 2); - case 'squircle': - return squirclePath(x + inset, y + inset, size); - case 'rounded': { - const R = size * 0.45; - // A scaled module touches no neighbor. - if (scale < 1) { - return roundedRect(x + inset, y + inset, size, size, R); - } - // Out of the matrix, the reads give `undefined`, a light neighbor. - const top = data[r - 1]?.[c]; - const right = data[r][c + 1]; - const bottom = data[r + 1]?.[c]; - const left = data[r][c - 1]; - return roundedRectPerCorner( - x, - y, - s, - s, - top || left ? 0 : R, - top || right ? 0 : R, - bottom || right ? 0 : R, - bottom || left ? 0 : R - ); - } - } +/** Returns the path of a pill: two half circles on the short sides. */ +function pillPath(x: number, y: number, width: number, height: number): string { + const radius = Math.min(width, height) / 2; + const arc = (dx: number, dy: number) => + `a${radius},${radius} 0 0 1 ${dx},${dy}`; + return width >= height + ? `M${x + radius},${y}h${width - 2 * radius}${arc(0, 2 * radius)}h${2 * radius - width}${arc(0, -2 * radius)}z` + : `M${x},${y + radius}${arc(2 * radius, 0)}v${height - 2 * radius}${arc(-2 * radius, 0)}z`; } -/** Returns an SVG path string for the inner dot of a finder-pattern corner. */ -export function cornerDotPath( +//#endregion + +//#region Finder and alignment patterns + +function finderCorners(size: number): [number, number][] { + return [ + [0, 0], // Top-left + [0, size - 7], // Top-right + [size - 7, 0], // Bottom-left + ]; +} + +function alignmentCenters(size: number): [number, number][] { + return getAlignmentPatternCenters((size - 17) / 4); +} + +/** Returns the SVG path of the center dot of a finder or an alignment pattern. */ +function cornerDotPath( x: number, y: number, - size: number, - style: QrCornerDotStyle + side: number, + style: QrCornerDotStyle, + antiDiagonal: boolean ): string { switch (style) { case 'circle': - return circlePath(x + size / 2, y + size / 2, size / 2); - case 'rounded': { - return roundedRect(x, y, size, size, size * 0.3); - } + return circlePath(x + side / 2, y + side / 2, side / 2); + case 'rounded': + return roundedRect(x, y, side, side, side * 0.3); case 'squircle': - return squirclePath(x, y, size); + return squirclePath(x, y, side); + case 'leaf': + return leafPath(x, y, side, antiDiagonal); default: - return squarePath(x, y, size); + return squarePath(x, y, side); } } -/** Returns the SVG path (a ring with a cutout) of the outer square of a finder corner. */ -export function cornerSquarePath( +/** Returns the SVG path of a ring of `side` and of width `ring`. */ +function cornerSquarePath( x: number, y: number, - size: number, - style: QrCornerSquareStyle + side: number, + ring: number, + style: QrCornerSquareStyle, + antiDiagonal: boolean ): string { - const moduleSize = size / 7; - const inner = size - 2 * moduleSize; - const innerOffset = moduleSize; + const inner = side - 2 * ring; + const hole = (shape: (x: number, y: number, side: number) => string) => + shape(x + ring, y + ring, inner); switch (style) { - case 'square': { - const outer = squarePath(x, y, size); - const cut = squarePath(x + innerOffset, y + innerOffset, inner); - return `${outer} ${cut}`; - } - case 'rounded': { - const outer = roundedRect(x, y, size, size, size * 0.15); - const cut = squarePath(x + innerOffset, y + innerOffset, inner); - return `${outer} ${cut}`; - } - case 'squircle': { - const outer = squirclePath(x, y, size); - const cut = squirclePath(x + innerOffset, y + innerOffset, inner); - return `${outer} ${cut}`; + case 'leaf': { + const leaf = (left: number, top: number, leafSide: number) => + leafPath(left, top, leafSide, antiDiagonal); + return `${leaf(x, y, side)} ${hole(leaf)}`; } + case 'square': + return `${squarePath(x, y, side)} ${hole(squarePath)}`; + case 'rounded': + return `${roundedRect(x, y, side, side, side * 0.15)} ${hole(squarePath)}`; + case 'squircle': + return `${squirclePath(x, y, side)} ${hole(squirclePath)}`; default: { - const cx = x + size / 2; - const cy = y + size / 2; - return circlePath(cx, cy, size / 2) + circlePath(cx, cy, inner / 2, 1); + const cx = x + side / 2; + const cy = y + side / 2; + return circlePath(cx, cy, side / 2) + circlePath(cx, cy, inner / 2, 1); } } } -/** Converts a module grid index to a pixel coordinate, accounting for margin. */ -export function moduleToPx( - moduleIndex: number, +/** + * Returns the ring and the center dot of a finder pattern (7 modules) or an alignment pattern + * (5 modules) whose top-left module is at `x`, `y`. + */ +export function patternPaths( + x: number, + y: number, + modules: number, moduleSize: number, - marginPx: number -): number { - return moduleIndex * moduleSize + marginPx; -} - -function finderCorners(size: number): [number, number][] { + squareStyle: QrCornerSquareStyle, + dotStyle: QrCornerDotStyle, + antiDiagonal = false +): [ring: string, dot: string] { + const side = modules * moduleSize; + const inset = 2 * moduleSize; return [ - [0, 0], // Top-left - [0, size - 7], // Top-right - [size - 7, 0], // Bottom-left + cornerSquarePath(x, y, side, moduleSize, squareStyle, antiDiagonal), + cornerDotPath( + x + inset, + y + inset, + side - 2 * inset, + dotStyle, + antiDiagonal + ), ]; } /** - * Returns one SVG path for each dark data module outside the finder patterns, at `dotScale` - * times the module size. + * Returns the top-left SVG coordinates of the three finder patterns. The `leaf` of the top-right + * and the bottom-left ones is round on the anti-diagonal, so that each leaf points at the center + * of the code. */ -export function renderDataModules( - data: boolean[][], - moduleSize: number, - marginPx: number, - dotStyle: QrDotStyle, - dotScale: number -): string[] { +export function getFinderPatterns( + grid: CodeGrid +): { x: number; y: number; antiDiagonal: boolean }[] { + return finderCorners(grid.size).map(([r, c], index) => ({ + x: moduleToPx(c, grid), + y: moduleToPx(r, grid), + antiDiagonal: index > 0, + })); +} + +/** + * Returns the SVG path of the alignment patterns: a ring of `squareStyle` and a center dot of + * `dotStyle` for each. Fill it with the `evenodd` rule. + */ +export function alignmentPath( + grid: CodeGrid, + squareStyle: QrCornerSquareStyle, + dotStyle: QrCornerDotStyle +): string { + return alignmentCenters(grid.size) + .flatMap(([r, c]) => + patternPaths( + moduleToPx(c - 2, grid), + moduleToPx(r - 2, grid), + 5, + grid.moduleSize, + squareStyle, + dotStyle + ) + ) + .join(' '); +} + +//#endregion + +//#region Data modules + +const OPEN_ZONE = 1; +const CUTOUT_ZONE = 2; + +/** + * The cells of a matrix: whether each one is dark, and its zone, `CUTOUT_ZONE` under the logo or + * else `OPEN_ZONE`. A cell of a finder pattern, its separator or an alignment pattern has zone 0, + * because the data modules do not draw it. + */ +type ModuleCells = { dark: boolean[][]; zones: number[][] }; + +function getModuleCells(data: boolean[][], cutout: ModuleRange[]): ModuleCells { const size = data.length; - const far = size - 8; + const zones = data.map((row) => row.map(() => OPEN_ZONE)); + const mark = (range: ModuleRange, zone: number) => + forEachModule(range, size, (r, c) => { + zones[r][c] = zone; + }); + const square = (top: number, left: number, side: number): ModuleRange => ({ + top, + left, + bottom: top + side - 1, + right: left + side - 1, + }); + + for (const range of cutout) mark(range, CUTOUT_ZONE); + for (const [row, col] of finderCorners(size)) { + mark(square(row - 1, col - 1, 9), 0); + } + for (const [row, col] of alignmentCenters(size)) { + mark(square(row - 2, col - 2, 5), 0); + } + + return { dark: data, zones }; +} + +/** Whether the cell at `r`, `c` is a dark data module of `zone`. */ +function isModuleOf( + { dark, zones }: ModuleCells, + r: number, + c: number, + zone: number +): boolean { + return zone > 0 && dark[r]?.[c] === true && zones[r][c] === zone; +} + +/** Whether the cells at `r`, `c` and `r2`, `c2` are dark data modules of one zone. */ +function joins( + cells: ModuleCells, + r: number, + c: number, + r2: number, + c2: number +): boolean { + const zone = cells.zones[r][c]; + return isModuleOf(cells, r, c, zone) && isModuleOf(cells, r2, c2, zone); +} + +/** Draws a module in the square of `side` at `x`, `y`, for the module at row `r` and column `c`. */ +type ModuleShape = ( + x: number, + y: number, + side: number, + r: number, + c: number +) => string; + +/** Returns `shape` for each dark data module, `scale` times its cell and centered in it. */ +function modulePaths( + cells: ModuleCells, + grid: ModuleGrid, + scale: number, + shape: ModuleShape +): string[] { + const side = grid.moduleSize * scale; + const inset = (grid.moduleSize - side) / 2; const paths: string[] = []; - for (let r = 0; r < size; r++) { - for (let c = 0; c < size; c++) { - // The finder patterns and their separators. - if ((r <= 7 && (c <= 7 || c >= far)) || (r >= far && c <= 7)) continue; - if (!data[r][c]) continue; + for (const [r, row] of cells.dark.entries()) { + for (const [c, dark] of row.entries()) { + if (dark && cells.zones[r][c] > 0) { + const x = moduleToPx(c, grid) + inset; + const y = moduleToPx(r, grid) + inset; + paths.push(shape(x, y, side, r, c)); + } + } + } + + return paths; +} - const x = moduleToPx(c, moduleSize, marginPx); - const y = moduleToPx(r, moduleSize, marginPx); +/** Returns `rounded` modules, with a square corner toward each neighbor that they join. */ +function roundedPaths( + cells: ModuleCells, + grid: ModuleGrid, + scale: number, + joined: boolean +): string[] { + return modulePaths(cells, grid, scale, (x, y, side, r, c) => { + const radius = side * ROUNDED_RADIUS; + const top = joined && joins(cells, r, c, r - 1, c); + const right = joined && joins(cells, r, c, r, c + 1); + const bottom = joined && joins(cells, r, c, r + 1, c); + const left = joined && joins(cells, r, c, r, c - 1); + return rectPerCorner( + x, + y, + side, + side, + top || left ? 0 : radius, + top || right ? 0 : radius, + bottom || right ? 0 : radius, + bottom || left ? 0 : radius, + quadCorner + ); + }); +} - paths.push(dotPath(data, r, c, x, y, moduleSize, dotStyle, dotScale)); +/** + * Returns the concave `liquid` fillets: one in each corner of a light cell whose two side + * neighbors and diagonal neighbor at that corner are dark and in its zone. + */ +function filletPaths(cells: ModuleCells, grid: ModuleGrid): string[] { + const radius = grid.moduleSize * ROUNDED_RADIUS; + // The directions of the neighbors at each corner, and the fillet from the corner point. + const corners = [ + [-1, -1], + [-1, 1], + [1, 1], + [1, -1], + ].map(([dr, dc]) => ({ + dr, + dc, + fillet: `h${-dc * radius}a${radius},${radius} 0 0 ${dr === dc ? 0 : 1} ${dc * radius},${-dr * radius}z`, + })); + const paths: string[] = []; + + for (const [r, row] of cells.dark.entries()) { + for (const [c, dark] of row.entries()) { + const zone = cells.zones[r][c]; + if (dark || zone === 0) continue; + + for (const { dr, dc, fillet } of corners) { + if ( + isModuleOf(cells, r + dr, c, zone) && + isModuleOf(cells, r, c + dc, zone) && + isModuleOf(cells, r + dr, c + dc, zone) + ) { + const x = moduleToPx(c + (dc > 0 ? 1 : 0), grid); + const y = moduleToPx(r + (dr > 0 ? 1 : 0), grid); + paths.push(`M${x},${y}${fillet}`); + } + } } } return paths; } -/** Returns the top-left pixel coordinates of the three finder-pattern corners. */ -export function getFinderPatterns( - size: number, +/** + * Returns one pill for each run of joined modules in a row, or in a column when `vertical` is + * set. `scale` sets the thickness and insets the ends. + */ +function barPaths( + cells: ModuleCells, + grid: ModuleGrid, + scale: number, + vertical: boolean +): string[] { + const size = cells.dark.length; + const thickness = grid.moduleSize * scale; + const inset = (grid.moduleSize - thickness) / 2; + const row = (line: number, i: number) => (vertical ? i : line); + const col = (line: number, i: number) => (vertical ? line : i); + const joinsNext = (line: number, i: number) => + joins( + cells, + row(line, i), + col(line, i), + row(line, i + 1), + col(line, i + 1) + ); + const paths: string[] = []; + + for (let line = 0; line < size; line++) { + for (let start = 0; start < size; start++) { + const r = row(line, start); + const c = col(line, start); + if (!isModuleOf(cells, r, c, cells.zones[r][c])) continue; + + let end = start; + while (end + 1 < size && joinsNext(line, end)) end++; + + const across = moduleToPx(line, grid) + inset; + const along = moduleToPx(start, grid) + inset; + const length = (end - start + 1) * grid.moduleSize - 2 * inset; + + paths.push( + vertical + ? pillPath(across, along, thickness, length) + : pillPath(along, across, length, thickness) + ); + start = end; + } + } + + return paths; +} + +type DotStyleGeometry = { + /** The style of the corner dots when `cornerDotStyle` is not set. */ + cornerDot: QrCornerDotStyle; + /** Whether the modules join their neighbors at `scale`. */ + joins: (scale: number) => boolean; + /** Returns the paths of the dark data modules; `joined` is the result of `joins`. */ + paths: ( + cells: ModuleCells, + grid: ModuleGrid, + scale: number, + joined: boolean + ) => string[]; +}; + +const shaped = + (shape: ModuleShape): DotStyleGeometry['paths'] => + (cells, grid, scale) => + modulePaths(cells, grid, scale, shape); + +const never = () => false; +const atFullSize = (scale: number) => scale === 1; + +/** + * The geometry of each dot style. A `diamond` or `plus` finder center fails to decode, so their + * corner dot is a square. A joining style has no single-shape form, so its corner dot is rounded. + */ +const DOT_STYLES: Record = { + square: { cornerDot: 'square', joins: never, paths: shaped(squarePath) }, + circle: { + cornerDot: 'circle', + joins: never, + paths: shaped((x, y, side) => + circlePath(x + side / 2, y + side / 2, side / 2) + ), + }, + squircle: { + cornerDot: 'squircle', + joins: never, + paths: shaped(squirclePath), + }, + diamond: { cornerDot: 'square', joins: never, paths: shaped(diamondPath) }, + plus: { cornerDot: 'square', joins: never, paths: shaped(plusPath) }, + rounded: { cornerDot: 'rounded', joins: atFullSize, paths: roundedPaths }, + liquid: { + cornerDot: 'rounded', + joins: atFullSize, + paths: (cells, grid, scale, joined) => [ + ...roundedPaths(cells, grid, scale, joined), + ...(joined ? filletPaths(cells, grid) : []), + ], + }, + 'horizontal-bars': { + cornerDot: 'rounded', + joins: () => true, + paths: (cells, grid, scale) => barPaths(cells, grid, scale, false), + }, + 'vertical-bars': { + cornerDot: 'rounded', + joins: () => true, + paths: (cells, grid, scale) => barPaths(cells, grid, scale, true), + }, +}; + +function dotStyleOf(dotStyle: QrDotStyle): DotStyleGeometry { + return DOT_STYLES[dotStyle] ?? DOT_STYLES.square; +} + +/** Whether the modules of `dotStyle` join their neighbors, so that the logo cutout changes them. */ +export function joinsModules(dotStyle: QrDotStyle, dotScale: number): boolean { + return dotStyleOf(dotStyle).joins(dotScale); +} + +/** + * Returns the SVG paths of the dark data modules outside the finder and alignment patterns, at + * `dotScale` times the module size. The modules under the logo `cutout` stay in the paths, for + * an export that drops the logo. + */ +export function renderDataModules( + data: boolean[][], moduleSize: number, - marginPx: number -) { - return finderCorners(size).map(([r, c]) => ({ - x: moduleToPx(c, moduleSize, marginPx), - y: moduleToPx(r, moduleSize, marginPx), - })); + marginPx: number, + dotStyle: QrDotStyle, + dotScale: number, + cutout: ModuleRange[] = [] +): string[] { + const style = dotStyleOf(dotStyle); + return style.paths( + getModuleCells(data, cutout), + { moduleSize, marginPx }, + dotScale, + style.joins(dotScale) + ); } + +/** + * Returns the style that the corner dots draw: `cornerDotStyle`, or else the one of `dotStyle`. + * A `circle` ring draws a `square` or `leaf` dot as a circle: zxing checks the pattern on the + * diagonals too, and a dot with corners there leaves a gap. + */ +export function resolveCornerDotStyle( + squareStyle: QrCornerSquareStyle, + cornerDotStyle: QrCornerDotStyle | undefined, + dotStyle: QrDotStyle +): QrCornerDotStyle { + const style = cornerDotStyle || dotStyleOf(dotStyle).cornerDot; + + return squareStyle === 'circle' && (style === 'square' || style === 'leaf') + ? 'circle' + : style; +} + +//#endregion diff --git a/src/components/qr-code/renderer/logo.ts b/src/components/qr-code/renderer/logo.ts index 0351a9ee7..a5d7394b0 100644 --- a/src/components/qr-code/renderer/logo.ts +++ b/src/components/qr-code/renderer/logo.ts @@ -1,16 +1,21 @@ +import { clamp } from '#internals/utils/math.js'; import { canHideModules, type ModuleRange } from '../model/cutout.js'; import { EC_LEVEL_INDEX } from '../model/encode.js'; -import type { QrErrorCorrectionLevel } from '../types.js'; +import type { QrErrorCorrectionLevel, QrLogoShape } from '../types.js'; +import { + arcBoxPath, + type Box, + ellipseBoxPath, + squircleBoxPath, +} from './helpers.js'; /** - * A logo box centered on the code, and the cutout under it: each module that the box covers, in - * part or in full. The values are in modules from the top-left corner of the matrix. + * A logo box centered on the code, in modules from the top-left corner of the matrix, its shape, + * and the cutout: the modules that the shape covers, in part or in full. */ -export type LogoLayout = ModuleRange & { - x: number; - y: number; - width: number; - height: number; +export type LogoLayout = Box & { + shape: QrLogoShape; + cutout: ModuleRange[]; }; /** The logo settings of a code: `area` is a share of the code without its quiet zone. */ @@ -18,37 +23,143 @@ export type LogoSettings = { errorLevel: QrErrorCorrectionLevel; area: number; aspectRatio: number; + shape: QrLogoShape; }; +function cornerRadius(width: number, height: number): number { + return Math.min(width, height) / 4; +} + +/** Returns `box` less `inset` on each side. */ +export function insetBox({ x, y, width, height }: Box, inset: number): Box { + return { + x: x + inset, + y: y + inset, + width: width - 2 * inset, + height: height - 2 * inset, + }; +} + +type LogoShapeGeometry = { + /** + * Whether a point at `dx`, `dy` from the center of a box with the half sides `halfWidth`, + * `halfHeight` is in the shape. + */ + covers: ( + dx: number, + dy: number, + halfWidth: number, + halfHeight: number + ) => boolean; + /** Returns the clip path of the shape in `inner`: its `box` less `inset` on each side. */ + clip?: (inner: Box, inset: number, box: Box) => string; +}; + +/** Each cell of the box range overlaps a `square`. */ +const LOGO_SHAPES: Record = { + square: { covers: () => true }, + circle: { + covers: (dx, dy, halfWidth, halfHeight) => + (dx / halfWidth) ** 2 + (dy / halfHeight) ** 2 < 1, + clip: ellipseBoxPath, + }, + squircle: { + covers: (dx, dy, halfWidth, halfHeight) => + (dx / halfWidth) ** 4 + (dy / halfHeight) ** 4 < 1, + clip: squircleBoxPath, + }, + rounded: { + covers: (dx, dy, halfWidth, halfHeight) => { + const r = cornerRadius(2 * halfWidth, 2 * halfHeight); + const cx = Math.max(dx - halfWidth + r, 0); + const cy = Math.max(dy - halfHeight + r, 0); + return dx < halfWidth && dy < halfHeight && cx * cx + cy * cy < r * r; + }, + // The curve keeps its center, so the clip is the exact inset of the shape. + clip: (inner, inset, box) => + arcBoxPath( + inner, + Math.max(cornerRadius(box.width, box.height) - inset, 0) + ), + }, +}; + +function geometryOf(shape: QrLogoShape): LogoShapeGeometry { + return LOGO_SHAPES[shape] ?? LOGO_SHAPES.square; +} + +/** + * Returns the ranges of the modules whose cells overlap `shape` in `box`, one for each run of + * rows with the same columns. The point of a cell nearest to the center decides. + */ +function getCutout( + shape: QrLogoShape, + { x, y, width, height }: Box +): ModuleRange[] { + const { covers } = geometryOf(shape); + const halfWidth = width / 2; + const halfHeight = height / 2; + const distance = (center: number, cell: number) => + Math.abs(clamp(center, cell, cell + 1) - center); + const ranges: ModuleRange[] = []; + + for (let row = Math.floor(y); row < y + height; row++) { + const dy = distance(y + halfHeight, row); + const overlaps = (col: number) => + covers(distance(x + halfWidth, col), dy, halfWidth, halfHeight); + let left = Math.floor(x); + let right = Math.ceil(x + width) - 1; + + while (left <= right && !overlaps(left)) left++; + while (right > left && !overlaps(right)) right--; + if (left > right) continue; + + const last = ranges.at(-1); + if ( + last?.bottom === row - 1 && + last.left === left && + last.right === right + ) { + last.bottom = row; + } else { + ranges.push({ top: row, left, bottom: row, right }); + } + } + + return ranges; +} + +/** + * Returns the clip path of a logo `shape` in `box`, less `inset` on each side, or `undefined` + * for a `square`, which needs no clip. + */ +export function logoClipPath( + shape: QrLogoShape, + box: Box, + inset: number +): string | undefined { + return geometryOf(shape).clip?.(insetBox(box, inset), inset, box); +} + function getLogoLayout( version: number, - { aspectRatio }: LogoSettings, + { aspectRatio, shape }: LogoSettings, area: number ): LogoLayout { const size = version * 4 + 17; const scaled = area * size * size; const width = Math.sqrt(scaled * aspectRatio); const height = Math.sqrt(scaled / aspectRatio); - const x = (size - width) / 2; - const y = (size - height) / 2; + const box = { x: (size - width) / 2, y: (size - height) / 2, width, height }; - return { - x, - y, - width, - height, - top: Math.floor(y), - left: Math.floor(x), - bottom: Math.ceil(y + height) - 1, - right: Math.ceil(x + width) - 1, - }; + return { ...box, shape, cutout: getCutout(shape, box) }; } function fits(version: number, settings: LogoSettings, area: number): boolean { return canHideModules( version, EC_LEVEL_INDEX[settings.errorLevel], - getLogoLayout(version, settings, area) + ...getLogoLayout(version, settings, area).cutout ); } diff --git a/src/components/qr-code/renderer/snap.ts b/src/components/qr-code/renderer/snap.ts new file mode 100644 index 000000000..518539ce0 --- /dev/null +++ b/src/components/qr-code/renderer/snap.ts @@ -0,0 +1,28 @@ +/** + * Returns the transform that puts each module of a code of `side` modules on whole pixels of an + * image of `pixels`, with the spare pixels in the quiet zone. Below 1 pixel per module, it returns + * `undefined`. + */ +export function snapToPixels( + pixels: number, + side: number, + margin: number +): { transform: string; scale: number } | undefined { + const modules = side + 2 * margin; + let modulePixels = Math.floor(pixels / modules); + + // A fractional margin needs whole pixels on both sides. + if (2 * Math.ceil(margin * modulePixels) + modulePixels * side > pixels) { + modulePixels--; + } + + if (!Number.isFinite(modulePixels) || modulePixels < 1) { + return undefined; + } + + const start = Math.floor((pixels - modulePixels * side) / 2); + const scale = (modulePixels * modules) / pixels; + const offset = (side * (start - modulePixels * margin)) / pixels; + + return { transform: `translate(${offset} ${offset}) scale(${scale})`, scale }; +} diff --git a/src/components/qr-code/renderer/templates.ts b/src/components/qr-code/renderer/templates.ts index 9a370fff2..4bc33d86a 100644 --- a/src/components/qr-code/renderer/templates.ts +++ b/src/components/qr-code/renderer/templates.ts @@ -1,17 +1,23 @@ import { nothing, svg, type TemplateResult } from 'lit'; +import { ifDefined } from 'lit/directives/if-defined.js'; +import { bindIf } from '#internals/utils/lit.js'; +import type { ModuleRange } from '../model/cutout.js'; import type { QrCornerDotStyle, QrCornerSquareStyle, QrDotStyle, + QrGradient, } from '../types.js'; import { - cornerDotPath, - cornerSquarePath, + alignmentPath, + type CodeGrid, getFinderPatterns, + joinsModules, moduleToPx, + patternPaths, renderDataModules, } from './helpers.js'; -import type { LogoLayout } from './logo.js'; +import { insetBox, type LogoLayout, logoClipPath } from './logo.js'; //#region Logo areas @@ -33,10 +39,10 @@ const DEFAULT_SIZE_RATIO = 0.4; type RenderQrDotsProperties = { matrix: boolean[][]; - moduleSize: number; - marginPx: number; + grid: CodeGrid; dotStyle: QrDotStyle; dotScale: number; + cutout?: ModuleRange[]; }; /** The last path of each matrix, keyed by geometry; an unchanged render reuses it. */ @@ -45,12 +51,14 @@ const paths = new WeakMap(); /** Renders the data modules as a single SVG path. */ export function renderQrDots({ matrix, - moduleSize, - marginPx, + grid: { moduleSize, marginPx }, dotStyle, dotScale, + cutout, }: RenderQrDotsProperties): TemplateResult { - const key = `${moduleSize}:${marginPx}:${dotStyle}:${dotScale}`; + // Only a joining style reads the cutout, so the others keep their cached path. + const joinedCutout = joinsModules(dotStyle, dotScale) ? cutout : undefined; + const key = `${moduleSize}:${marginPx}:${dotStyle}:${dotScale}:${JSON.stringify(joinedCutout)}`; let cached = paths.get(matrix); if (cached?.key !== key) { @@ -59,7 +67,8 @@ export function renderQrDots({ moduleSize, marginPx, dotStyle, - dotScale + dotScale, + joinedCutout ); cached = { key, path: modules.join(' ') }; paths.set(matrix, cached); @@ -68,29 +77,27 @@ export function renderQrDots({ return svg``; } -type RenderFindersProperties = { - size: number; - moduleSize: number; - marginPx: number; +export type RenderPatternsProperties = { + grid: CodeGrid; dotStyle: QrCornerDotStyle; squareStyle: QrCornerSquareStyle; }; /** Renders the three finder-pattern corners. */ export function renderQrFinders({ - size, - moduleSize, - marginPx, + grid, dotStyle, squareStyle, -}: RenderFindersProperties): TemplateResult[] { - return getFinderPatterns(size, moduleSize, marginPx).map(({ x, y }) => { - const squarePath = cornerSquarePath(x, y, 7 * moduleSize, squareStyle); - const dotPath = cornerDotPath( - x + 2 * moduleSize, - y + 2 * moduleSize, - 3 * moduleSize, - dotStyle +}: RenderPatternsProperties): TemplateResult[] { + return getFinderPatterns(grid).map(({ x, y, antiDiagonal }) => { + const [squarePath, dotPath] = patternPaths( + x, + y, + 7, + grid.moduleSize, + squareStyle, + dotStyle, + antiDiagonal ); return svg` @@ -102,72 +109,126 @@ export function renderQrFinders({ }); } +/** Renders the alignment patterns as a single SVG path, or nothing for version 1. */ +export function renderQrAlignment({ + grid, + dotStyle, + squareStyle, +}: RenderPatternsProperties): TemplateResult | typeof nothing { + const path = alignmentPath(grid, squareStyle, dotStyle); + + return path + ? svg`` + : nothing; +} + +type QrMaskAndImage = { + mask: TemplateResult | typeof nothing; + image: TemplateResult | typeof nothing; + shouldApplyMask: boolean; +}; + +const NO_LOGO: QrMaskAndImage = { + mask: nothing, + image: nothing, + shouldApplyMask: false, +}; + type RenderQrMaskAndImageProperties = { src: string; layout?: LogoLayout; - size: number; + /** The CSS pixels of one SVG unit, which convert `margin` to units. */ + unitSize: number; margin?: number; - svgSize: number; - moduleSize: number; - marginPx: number; + grid: CodeGrid; maskId: string; + clipId: string; + transform?: string; }; /** - * Renders the logo image and its mask: a white rectangle with a black cutout of the modules of - * `layout`. The image fills the logo box, less `margin` on each side. + * Renders the logo image and its mask: a white rectangle with a black rectangle for each range + * of the cutout of `layout`. The image fills the logo box, less `margin` pixels on each side, + * takes the `transform` of the masked group, and is clipped to the logo shape. */ export function renderQrMaskAndImage({ src, layout, - size, + unitSize, margin, - svgSize, - moduleSize, - marginPx, + grid, maskId, -}: RenderQrMaskAndImageProperties) { - if (!layout) { - return { mask: nothing, image: nothing, shouldApplyMask: false }; - } - - const toSvg = (modules: number) => moduleToPx(modules, moduleSize, marginPx); - const boxMargin = (margin ?? 0) * (svgSize / size); - - const cutX = toSvg(layout.left); - const cutY = toSvg(layout.top); - const cutRight = toSvg(layout.right + 1); - const cutBottom = toSvg(layout.bottom + 1); - - const x = toSvg(layout.x) + boxMargin; - const y = toSvg(layout.y) + boxMargin; - const width = Math.max(0, layout.width * moduleSize - boxMargin * 2); - const height = Math.max(0, layout.height * moduleSize - boxMargin * 2); + clipId, + transform, +}: RenderQrMaskAndImageProperties): QrMaskAndImage { + if (!layout) return NO_LOGO; + + const toSvg = (modules: number) => moduleToPx(modules, grid); + const boxMargin = (margin ?? 0) / unitSize; + const box = { + x: toSvg(layout.x), + y: toSvg(layout.y), + width: layout.width * grid.moduleSize, + height: layout.height * grid.moduleSize, + }; + const { x, y, width, height } = insetBox(box, boxMargin); + + if (width <= 0 || height <= 0) return NO_LOGO; + + const cuts = layout.cutout.map(({ top, left, bottom, right }) => { + const cutX = toSvg(left); + const cutY = toSvg(top); + return svg``; + }); - const shouldApplyMask = width > 0 && height > 0; + const clip = logoClipPath(layout.shape, box, boxMargin); - const mask = shouldApplyMask - ? svg` + const mask = svg` - - + + ${cuts} + ${clip ? svg`` : nothing} - ` - : nothing; + `; - const image = shouldApplyMask - ? svg`` - : nothing; + const image = svg``; + + return { mask, image, shouldApplyMask: true }; +} + +type RenderQrGradientProperties = { + id: string; + gradient: QrGradient; + angle: number; + grid: CodeGrid; +}; + +/** + * Renders the gradient of the dark modules over the matrix, without the quiet zone. A linear one + * at `angle` and a radial one reach the corners of the matrix. The CSS sets the stop colors. + */ +export function renderQrGradient({ + id, + gradient, + angle, + grid: { svgSize, marginPx }, +}: RenderQrGradientProperties): TemplateResult { + const center = svgSize / 2; + const half = center - marginPx; + const stops = svg``; + + if (gradient === 'radial') { + return svg`${stops}`; + } + + const radians = (angle * Math.PI) / 180; + const dx = Math.cos(radians); + const dy = Math.sin(radians); + const reach = half * (Math.abs(dx) + Math.abs(dy)); - return { mask, image, shouldApplyMask }; + return svg`${stops}`; } //#endregion diff --git a/src/components/qr-code/spec.md b/src/components/qr-code/spec.md index 3cbc3eb4e..77d4d4613 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) @@ -36,10 +37,12 @@ - [Theming](#theming) - [Attribute reflection](#attribute-reflection) - [Style variants](#style-variants) + - [Pixel snapping](#pixel-snapping) - [Shape geometry](#shape-geometry) - [Logo](#logo) - [Export](#export) - [Clipboard](#clipboard) + - [QR model properties](#qr-model-properties) - [Host ARIA](#host-aria) - [Scanning](#scanning) - [Not covered by the suite](#not-covered-by-the-suite) @@ -60,11 +63,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; no ECI header; payload helpers; export holds only the code; whole-pixel modules; alignment patterns; new dot styles and `leaf`; gradient; `logo-shape` | ## 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, @@ -74,31 +78,39 @@ 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. -- **Visual customization** of the data modules, the outer corner squares and the inner corner dots as `square`, - `circle`, `rounded` or `squircle`, and a scale for the data modules that leaves a gap between them. + escalation from `M` to the smallest level that keeps the code scannable at the requested logo size. The logo can be + a square, a circle, a rounded square or a squircle. +- **Visual customization** of the data modules, the outer corner squares and the inner corner dots. The data modules + have nine styles, among them joined `liquid` modules and bars. A scale for the data modules leaves a gap between + them. The alignment patterns take the shapes of the corners. +- **Sharp edges**: each module covers a whole number of pixels, on the screen and in an export. - **Themeable colors** through CSS custom properties, with parts for the background, the dots and each corner - element. + element, and an optional linear or radial gradient. - **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 - 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. +- `size` and `margin` must control the rendered pixels and the quiet zone without touching the encoded data. Each + module that covers at least one pixel must cover a whole number of pixels, and the quiet zone must keep at least + `margin` modules. - A valid `logo-src` must be centered over the code with the whole modules beneath it masked out. - Unsafe logo values must be rejected, and the component must recover when a failed logo is replaced. - `dot-style`, `square-style` and `corner-dot-style` must control their shapes independently, and the inner corner dots must follow `dot-style` while `corner-dot-style` is not set. -- `dot-scale` must shrink the data modules and leave the finder patterns at full size. +- `dot-scale` must shrink the data modules and leave the finder and alignment patterns at full size. - The colors must be customizable and must not invert with the light and dark theme variants. - `copyToClipboard()` must start the clipboard write inside the user action that calls it. - The element must be integrated and themeable with the theming mechanism of the library. @@ -130,6 +142,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 @@ -158,6 +171,15 @@ This renders a 128×128 pixel code with a 4-module margin, `M` error correction ``` +Each module covers `floor(size / (modules + 2 * margin))` whole pixels, so its edges stay sharp. The pixels that are +left over go to the quiet zone, so `margin` is a minimum and the code can be smaller than its box. A fractional +`margin` can make each module 1 pixel smaller, so that the quiet zone keeps its minimum. A module smaller than 1 pixel +is not snapped. + +For example, a version 2 code has 25 modules, and 33 with the default margin. At the default size of 128 pixels, each +module covers 3 pixels and the code covers 75 pixels. The quiet zone covers 26 pixels on the left and top, and 27 +pixels on the right and bottom. + #### Pinning a specific version ```html @@ -188,6 +210,24 @@ collapses to zero renders no image and throws nothing. The cutout under the logo holds whole modules: each module that the logo box covers, in part or in full. No module is cut in part, and the logo keeps the size of its box. +```html + +``` + +`logo-shape` takes `square` (the default), `circle`, `rounded` or `squircle`. The shape fills the logo box, so a +`circle` logo with a wide image is an ellipse, and a `rounded` logo has corners with a radius of a quarter of its +shorter side. `logo-size` stays the area of the box. The image is clipped to the shape drawn in the logo box less +`logo-margin` on each side, and the cutout holds only the modules that the shape covers, in part or in full. A shape +other than `square` hides fewer modules, so a pinned version can keep a larger logo. + +The `rounded`, `liquid` and bar styles do not join a module under the logo to a module outside it, so the visible +modules end round at the edge of the cutout. The hidden modules stay in the code under the mask: an export whose logo +cannot be fetched drops the mask and shows them. + The code must stay readable under the logo. The cutout must not hide a finder pattern, its separator, or the format or version information, and no error correction block can lose more codewords than it corrects. A codeword with one hidden module counts as lost, whatever the logo shows. When `version` is not set, the component selects the smallest @@ -204,8 +244,28 @@ image that fails to load leaves the code without a logo until a valid source is ``` `dot-style`, `square-style` and `corner-dot-style` take `square`, `circle`, `rounded` or `squircle`. A `squircle` is -a superellipse: a square with soft corners, rounder than `rounded` and squarer than `circle`. The inner corner dots -use `dot-style` until `corner-dot-style` is set. +a superellipse: a square with soft corners, rounder than `rounded` and squarer than `circle`. + +`dot-style` also takes these styles: + +- `diamond`: a square turned 45°, with its points at the cell edges. +- `plus`: a cross with arms to the cell edges, so neighbors join along the arms. +- `liquid`: `rounded`, with a smooth fill in the inside corner of each L-join. +- `horizontal-bars` and `vertical-bars`: each run of dark modules in a row or a column is one bar with round ends. + +`square-style` and `corner-dot-style` also take `leaf`: a square with two opposite round corners, on the diagonal +toward the center of the code. The radius is a quarter of the side. A leaf with fully round corners fails to decode. + +The inner corner dots use `dot-style` until `corner-dot-style` is set. A corner dot is one shape, so it draws +`diamond` and `plus` as `square`, and `liquid` and the bar styles as `rounded`. + +From version 2, the code has alignment patterns. Each one is a ring of `square-style` around a center dot of the +corner dot style, so it matches the finder patterns. A `leaf` alignment ring has the shape of the top-left corner +square. A joining style does not join a data module to an alignment pattern. + +A `circle` corner square draws a `square` or `leaf` corner dot as a `circle`, in the finder and the alignment +patterns. A scanner such as zxing-cpp also checks the finder pattern on its diagonals, and a dot with corners in a +round ring leaves a gap there. `cornerDotStyle` keeps the value that the application set. ```html ``` -The colors do not follow the light and dark variants of the global theme; a code that inverted itself would stop -scanning reliably. +The alignment patterns take `--ig-qr-code-dark-color`. The colors do not follow the light and dark variants of the +global theme; a code that inverted itself would stop scanning reliably. + +```html + +``` + +`gradient` paints the data modules, the alignment patterns and the corners with a `linear` or a `radial` gradient, +from `--ig-qr-code-gradient-start` to `--ig-qr-code-gradient-end`. Another value gives one color. Both colors fall back to +`--ig-qr-code-dark-color`. The gradient spans the matrix, not the quiet zone. A linear gradient goes from left to +right at a `gradient-angle` of `0`, turns clockwise in degrees, and reaches the corners of the matrix. A radial +gradient goes from the center to the corners. An explicit `--ig-qr-code-corner-square-color` or +`--ig-qr-code-corner-dot-color` wins over the gradient for its part. Each instance has its own gradient, so the +codes on a page do not share one. An export writes the colors of the stops. + +The component gives no warning for low contrast. Keep the dark color, and both colors of a gradient, much darker than +the background, and do not invert the code. Test the colors with the phones and the apps of your users. #### Exporting @@ -248,8 +329,8 @@ 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` -set right after the call applies to the image. +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. Its modules cover whole pixels of the image size, `size * scale`. ```ts const file = await qrCode.toImage({ format: 'png', scale: 2, download: true }); @@ -284,6 +365,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 @@ -310,20 +397,25 @@ 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. | +| `size` | `size` | no | `number` | `128` | The rendered width and height in pixels; modules cover whole pixels. | +| `margin` | `margin` | no | `number` | `4` | The smallest quiet-zone margin, in modules. | +| `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. | +| `squareStyle` | `square-style` | no | `QrCornerSquareStyle` | `square`| The shape of the outer corner squares and of the alignment rings. | +| `cornerDotStyle` | `corner-dot-style` | no | `QrCornerDotStyle \| undefined` | Not set | The shape of the inner corner dots and of the alignment centers; follows `dotStyle` when unset. | +| `logoShape` | `logo-shape` | no | `QrLogoShape` | `square`| The shape of the logo: 'square', 'circle', 'rounded' or 'squircle'. | +| `gradient` | `gradient` | no | `QrGradient \| undefined` | Not set | The gradient of the dark modules: 'linear' or 'radial'. | +| `gradientAngle` | `gradient-angle` | no | `number` | `0` | The angle of a 'linear' gradient in degrees, clockwise. | -`QrDotStyle`, `QrCornerSquareStyle` and `QrCornerDotStyle` are `"square" | "circle" | "rounded" | "squircle"`. +`QrDotStyle` is `"square" | "circle" | "rounded" | "squircle" | "diamond" | "plus" | "liquid" | "horizontal-bars" | +"vertical-bars"`. `QrCornerSquareStyle` and `QrCornerDotStyle` are `"square" | "circle" | "rounded" | "squircle" | +"leaf"`. `QrLogoShape` is `"square" | "circle" | "rounded" | "squircle"`, and `QrGradient` is `"linear" | "radial"`. ### Methods @@ -365,15 +457,18 @@ None. The SVG is rendered entirely from the properties of the component. | `dots` | The data modules of the code. | | `corner-square` | The outer finder-pattern corner squares. | | `corner-dot` | The inner finder-pattern corner dots. | +| `alignment` | The alignment patterns, from version 2. | ### CSS custom properties | Property | Default | Description | | ---------------------------------- | ------- | ---------------------------------------------------------------------------------- | | `--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-dark-color` | `black` | The color of the data modules and the alignment patterns, and of the corners unless they are overridden. | +| `--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`. | +| `--ig-qr-code-gradient-start` | Not set | The start color of the `gradient`. Defaults to `--ig-qr-code-dark-color`. | +| `--ig-qr-code-gradient-end` | Not set | The end color of the `gradient`. Defaults to `--ig-qr-code-dark-color`. | ## Test scenarios @@ -384,14 +479,16 @@ None. The SVG is rendered entirely from the properties of the component. ### Accessibility tests -1. The component passes the accessibility audit when a value is set. +1. The component passes the accessibility audit when a value is set, and with a gradient and a shaped logo also in + the light DOM. 2. The SVG carries a `` for screen readers, which uses the `aria-label` when one is provided, follows a change of `ariaLabel` alone, and returns to the default when the attribute is removed. ### Default property values -3. `size`, `margin`, `errorLevel`, `dotStyle`, `squareStyle`, `cornerDotStyle`, `dotScale` and `value` have their - documented defaults, and so do `logoSrc`, `logoSize` and `logoMargin`. +3. `size`, `margin`, `errorLevel`, `dotStyle`, `squareStyle`, `cornerDotStyle`, `dotScale`, `gradient`, + `gradientAngle` and `value` have their documented defaults, and so do `logoSrc`, `logoSize`, `logoMargin` and + `logoShape`. ### Rendering @@ -401,102 +498,156 @@ None. The SVG is rendered entirely from the properties of the component. ### Theming -7. The `background`, `dots`, `corner-square` and `corner-dot` parts are exposed. +7. The `background`, `dots`, `corner-square`, `corner-dot` and `alignment` parts are exposed. 8. The default colors are the schema ones, and the documented custom properties override them. 9. `--ig-qr-code-dark-color` cascades to the corner square and the corner dot, and an explicit corner override - wins over the cascade. + wins over the cascade. The alignment patterns take `--ig-qr-code-dark-color`. 10. The colors do not invert when the global theme switches to its dark variant. +11. `gradient` paints the dots, the alignment patterns and the corners with the gradient of the instance, and each + instance has its own. An explicit corner color wins for its part. The stops take the gradient colors, or else + the dark color, and a cleared `gradient` or a value other than `linear` and `radial` gives one color. +12. A linear gradient spans the matrix without the quiet zone, along `gradient-angle`, and a radial gradient reaches + the corners of the matrix from its center. A `gradient-angle` that is not a number is 0. ### Attribute reflection -11. The `dot-style`, `square-style`, `corner-dot-style`, `dot-scale`, `error-level`, `version`, `logo-src`, - `logo-size` and `logo-margin` attributes initialize their properties. +13. The `dot-style`, `square-style`, `corner-dot-style`, `dot-scale`, `gradient`, `gradient-angle`, `error-level`, + `version`, `logo-src`, `logo-size`, `logo-margin` and `logo-shape` attributes initialize their properties. ### Style variants -12. Each `dot-style` renders its data path, and each `square-style` renders its corner groups. +14. Each `dot-style` renders its data path, and each `square-style` renders its corner groups. + +### Pixel snapping + +15. At the sizes 128 and 256, each module covers the same whole number of pixels, and the code starts on a whole + pixel. The quiet zone keeps at least `margin` modules on each side, also for a fractional `margin`. +16. An SVG export at the scales 2 and 1.3 puts the modules on whole pixels of the image size, and a module smaller + than 1 pixel is not snapped. ### Shape geometry -13. A `squircle` data module rounds its corners less than a circle, a `squircle` corner square is a ring, and a +17. A `squircle` data module rounds its corners less than a circle, a `squircle` corner square is a ring, and a `squircle` corner dot rounds its corners. -14. The inner corner dots follow `dotStyle` until `cornerDotStyle` is set and again after it is unset, and the data +18. The inner corner dots follow `dotStyle` until `cornerDotStyle` is set and again after it is unset, and the data modules do not change with `cornerDotStyle`. -15. `dotScale` shrinks the data modules around their centers, is clamped from 0.7 to 1 with 1 for a value that is not +19. An alignment pattern is a ring of `squareStyle` around a center dot of the corner dot style. It is not part of the + data path, keeps its size at any `dotScale`, and a `rounded` module does not join it. +20. A `circle` corner square draws a `square` or `leaf` corner dot as a circle, in the finder and the alignment + patterns, and `cornerDotStyle` keeps its value. +21. A `diamond` module has its points at the cell edges, and a `plus` module has its arms to the cell edges. +22. A `liquid` L-join has a fill in its inside corner, and below a `dotScale` of 1, `liquid` draws as `rounded`. +23. A bar style draws one bar with round ends for each run of dark modules in a row or a column, and `dotScale` sets + its thickness. +24. A `leaf` corner square and corner dot round the corners on the diagonal toward the center of the code, and a + `leaf` alignment ring has the shape of the top-left one. +25. Without `cornerDotStyle`, the corner dots draw `diamond` and `plus` as `square`, and `liquid` and the bar styles + as `rounded`. +26. A joining style does not join a module under the logo cutout to a module outside it: a `rounded` module ends + round at the cutout and the hidden module stays, a bar splits at the cutout edge, and a `liquid` fillet needs + three modules of one zone. +27. `dotScale` shrinks the data modules around their centers, is clamped from 0.7 to 1 with 1 for a value that is not a number, and leaves the finder patterns at full size. A scaled `rounded` module rounds the corners toward its dark neighbors. ### Logo -16. No `<image>` or `<mask>` is rendered without a logo; a valid one renders both, with the image outside the +28. No `<image>` or `<mask>` is rendered without a logo; a valid one renders both, with the image outside the masked group and the mask applied to the group holding the dots and the finders. -17. The mask id is stable across re-renders, and clearing the logo or replacing it with an unsafe URL removes the +29. The mask id is stable across re-renders, and clearing the logo or replacing it with an unsafe URL removes the image and the mask. -18. Unsafe schemes and non-image `data:` URIs are blocked, while `data:image/` and `https://` URLs are accepted. -19. A logo that fails to load leaves the code without one, and the component recovers once a valid source is set. -20. A higher error correction level produces a larger code, and the logo area is capped to the safe area of the +30. Unsafe schemes and non-image `data:` URIs are blocked, while `data:image/` and `https://` URLs are accepted. +31. A logo that fails to load leaves the code without one, and the component recovers once a valid source is set. +32. A higher error correction level produces a larger code, and the logo area is capped to the safe area of the resolved level. Without `error-level`, a large logo escalates the level while `errorLevel` reads `M`, a small logo keeps `M`, an explicit `M` caps the logo, and removing the attribute restores the escalation. -21. `logoMargin` reduces the visible logo, and a margin that consumes the whole logo box renders no image. -22. The cutout starts and ends on module boundaries and is centered, and the logo lies inside it, with and without +33. `logoMargin` reduces the visible logo, stays in pixels when the modules snap to whole pixels, and a margin that + consumes the whole logo box renders no image. +34. The cutout starts and ends on module boundaries and is centered, and the logo lies inside it, with and without `logoMargin`. -23. A logo that would hide more codewords than the level corrects raises the version, and removing the logo restores +35. A logo that would hide more codewords than the level corrects raises the version, and removing the logo restores it. A pinned version keeps its size, and the logo gets smaller. +36. A `square` logo has one cut rectangle and no clip. The cutout of a `circle`, `rounded` or `squircle` logo, and of + a wide `circle` or `squircle` logo, holds each point of the shape and only the modules that the shape covers. The + image is clipped to the shape drawn in the logo box less `logoMargin`. +37. On a pinned version, a `circle`, `rounded` or `squircle` logo stays larger than a `square` logo. +38. A change of the cutout redraws the data modules. ### Export -24. `toBlob()` returns an SVG blob, resolves the theme colors to `fill` attributes and strips the parts. -25. A data URI logo is kept as it is, a fetched one is inlined as a data URI, a logo assigned right before the +39. `toBlob()` returns an SVG blob, resolves the theme colors to `fill` attributes and strips the parts. +40. A data URI logo is kept as it is, a fetched one is inlined as a data URI, a logo assigned right before the export is awaited, and one that cannot be fetched is dropped together with its mask. The logo is written as both `href` and `xlink:href`, and a code without a logo has no `xlink:href`. -26. `toImage()` exports a PNG at the component size by default, scales the raster output, and exports an opaque +41. A shaped logo keeps its clip. The export writes the colors of the gradient stops and the gradient as the `fill` + of the parts, and keeps the gradient when the logo cannot be fetched. +42. `toImage()` exports a PNG at the component size by default, scales the raster output, and exports an opaque JPEG, a WebP and an SVG with scaled dimensions. A `size` set right after the call applies to the image. -27. An existing matching extension in the file name is kept, and the download dialog opens only when requested. -28. Both methods reject without a value, and `toImage()` rejects invalid options, also a `size` set right after the +43. An existing matching extension in the file name is kept, and the download dialog opens only when requested. +44. Both methods reject without a value, and `toImage()` rejects invalid options, also a `size` set right after the call that makes the image larger than the maximum canvas size. A value that does not fit the pinned version renders nothing, warns once and makes the export reject with the encoder error. A version that is not an integer from 1 to 40 falls back to the automatic version. ### Clipboard -29. `copyToClipboard()` copies a PNG image at the component size by default, and a `size` set right after the call +45. `copyToClipboard()` copies a PNG image at the component size by default, and a `size` set right after the call applies to the copy. -30. An `svg` copy holds an SVG image, with the theme colors resolved and the parts stripped, and a PNG image, both +46. An `svg` copy holds an SVG image, with the theme colors resolved and the parts stripped, and a PNG image, both multiplied by `scale`. A clipboard that does not take SVG gets only the PNG. -31. The clipboard write starts before the first `await` of the method, for a PNG copy and an SVG copy. -32. The method rejects when the clipboard refuses the write and without the Clipboard API. It also rejects on invalid +47. The clipboard write starts before the first `await` of the method, for a PNG copy and an SVG copy. +48. The method rejects when the clipboard refuses the write and without the Clipboard API. It also rejects on invalid options and without a value, and then it writes nothing. A refused write that skips a failed export leaves no unhandled rejection. ### QR model properties -33. Each version and error correction level holds as many codewords as the symbol has room for, checked against the +49. 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. -35. The matrix is square, with the side length of its version, and data over the capacity of a version throws the +50. 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. +51. 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. ### Host ARIA -36. The host `aria-labelledby` and `aria-describedby` reach the SVG, and the exported SVG has neither attribute. +52. The host `aria-labelledby` and `aria-describedby` reach the SVG, and the exported SVG has neither attribute. ### Scanning A decoder (zxing-cpp, from the `zxing-wasm` package) reads the PNG that `toImage()` exports, with at least 6 pixels for each module. -37. Each `dot-style` decodes with each `square-style` and each `corner-dot-style`, in a Latin square of the three - shapes. -38. Each `dot-style` decodes at the smallest `dotScale`, also in a version 12 code. -39. A code with a white or a black logo, at the default and the largest `logoSize`, decodes at each error correction +53. Each basic `dot-style` (`square`, `circle`, `rounded` and `squircle`) decodes with each basic `square-style` and + `corner-dot-style`, in a Latin square of the three shapes. Each other `dot-style` decodes with the same pairs of + corner shapes. +54. Each `dot-style` decodes at the smallest `dotScale`, also in a version 12 code. +55. A code with a white or a black logo, at the default and the largest `logoSize`, decodes at each error correction 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 +56. 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. +57. Values that mix numeric, alphanumeric and byte segments decode, with and without a logo. +58. A `circle` corner square with circle modules decodes with each `corner-dot-style`, at versions 3 and 10 and at 7, + 8 and 9 pixels for each module. Before the alignment rings and the rule for the corner dot, some of these failed. +59. The alignment patterns of each `square-style` decode with each `dot-style` in a version 12 code, at 7 and 8 + pixels for each module. +60. Each new `dot-style` decodes at a `dotScale` of 1, and at the smallest `dotScale` also in a version 12 code. +61. A `leaf` corner square decodes with each `corner-dot-style`, at versions 3 and 12 and at 7 and 9 pixels for each + module. +62. A `leaf` corner dot decodes in a `square`, `rounded` and `squircle` corner square, at versions 3 and 12 and at 7 + and 9 pixels for each module. +63. A white or black `circle`, `rounded` and `squircle` logo of the largest `logoSize` decodes on codes of versions 1 + to 3 at each error correction level. A wide shaped logo decodes at levels `M` and `H`, and a shaped logo on a + pinned version 1, 2 or 3 at level `H`. +64. The `rounded`, `liquid` and bar styles decode with a `square` and a `circle` logo of the largest `logoSize`, also + in a version 12 code. +65. A linear gradient at 0, 45 and 135 degrees and a radial gradient between two dark colors decode, also in a + version 12 code. ### Not covered by the suite -- `margin` is not asserted on its own. +- `margin` is asserted only as the smallest quiet zone, in the pixel snapping specs. - The scanning specs use one decoder on clean images. A phone camera adds blur, noise and perspective, and other decoders can be stricter or more lenient. - A real clipboard write: the suite stubs the Clipboard API, because headless Chromium denies a clipboard write @@ -504,18 +655,28 @@ 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 - sizes, with or without a logo. The same codes fail in earlier releases. +- A `diamond` or `plus` finder center and a `leaf` with fully round corners fail to decode in zxing-cpp at some sizes, + so the corner dots do not take `diamond` or `plus`, and a `leaf` rounds a quarter of its side. +- The modules cover whole CSS pixels. At a device pixel ratio of 1, 2 or 3 the edges are sharp, and at 1.25 or 1.5 + they can blur, because a CSS pixel is not a whole number of device pixels. An export is always exact. - 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()` rejects. - The colors deliberately do not follow the light and dark theme variants. +- The gradient colors are CSS custom properties of the component only. The igniteui-theming schema has no gradient + colors, and with `gradient` set, the corner colors of a Sass `qr-code-theme()` do not apply. To keep a corner + color, set `--ig-qr-code-corner-square-color` or `--ig-qr-code-corner-dot-color`. +- The component does not check the contrast of the colors. The application owns a gradient or a color that a camera + cannot tell from the background. - `toImage()` and `copyToClipboard()` are bounded by the maximum canvas size of the browser, so a very large size and scale combination is rejected. - `copyToClipboard()` needs a secure context, a focused document and a user action. The application must call it @@ -540,5 +701,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/components/qr-code/themes/shared/qr-code.common.scss b/src/components/qr-code/themes/shared/qr-code.common.scss index 223339f4a..b5b84a7f3 100644 --- a/src/components/qr-code/themes/shared/qr-code.common.scss +++ b/src/components/qr-code/themes/shared/qr-code.common.scss @@ -3,18 +3,28 @@ $theme: $base; -[part='background'] { +[part~='background'] { fill: var-get($theme, 'background'); } -[part='dots'] { - fill: var-get($theme, 'dark-color'); +// The template sets `--_paint` to the gradient of the instance. +[part~='dots'], +[part~='alignment'] { + fill: var(--_paint, #{var-get($theme, 'dark-color')}); } -[part='corner-square'] { - fill: var-get($theme, 'corner-square-color'); +[part~='corner-square'] { + fill: var(--ig-qr-code-corner-square-color, var(--_paint, #{var-get($theme, 'corner-square-color')})); } -[part='corner-dot'] { - fill: var-get($theme, 'corner-dot-color'); +[part~='corner-dot'] { + fill: var(--ig-qr-code-corner-dot-color, var(--_paint, #{var-get($theme, 'corner-dot-color')})); +} + +stop:first-child { + stop-color: var(--ig-qr-code-gradient-start, #{var-get($theme, 'dark-color')}); +} + +stop:last-child { + stop-color: var(--ig-qr-code-gradient-end, #{var-get($theme, 'dark-color')}); } diff --git a/src/components/qr-code/types.ts b/src/components/qr-code/types.ts index 05d51c736..1c65d5aec 100644 --- a/src/components/qr-code/types.ts +++ b/src/components/qr-code/types.ts @@ -1,11 +1,36 @@ /** Shape of individual data modules in the QR code body. */ -export type QrDotStyle = 'square' | 'circle' | 'rounded' | 'squircle'; +export type QrDotStyle = + | 'square' + | 'circle' + | 'rounded' + | 'squircle' + | 'diamond' + | 'plus' + | 'liquid' + | 'horizontal-bars' + | 'vertical-bars'; /** Shape of the inner dot inside each finder-pattern corner. */ -export type QrCornerDotStyle = 'square' | 'circle' | 'rounded' | 'squircle'; +export type QrCornerDotStyle = + | 'square' + | 'circle' + | 'rounded' + | 'squircle' + | 'leaf'; /** Shape of the outer square of each finder-pattern corner. */ -export type QrCornerSquareStyle = 'square' | 'circle' | 'rounded' | 'squircle'; +export type QrCornerSquareStyle = + | 'square' + | 'circle' + | 'rounded' + | 'squircle' + | 'leaf'; + +/** Paint of the dark modules: a gradient between two colors. Unset means a solid color. */ +export type QrGradient = 'linear' | 'radial'; + +/** Shape of the logo, which fills the logo box. */ +export type QrLogoShape = 'square' | 'circle' | 'rounded' | 'squircle'; /** * QR error correction level. Higher levels recover more data but reduce capacity. @@ -14,7 +39,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/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<string, string>` | 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..9411e7239 --- /dev/null +++ b/src/extras/qr-payloads/qr-payloads.ts @@ -0,0 +1,330 @@ +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:<type>;S:<ssid>;P:<password>;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: <value>`, 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/index.ts b/src/index.ts index 9d579f4bc..202758610 100644 --- a/src/index.ts +++ b/src/index.ts @@ -240,9 +240,12 @@ export type { QrCodeCopyOptions, QrCodeExportFormat, QrCodeExportOptions, + QrCornerDotStyle, QrCornerSquareStyle, QrDotStyle, QrErrorCorrectionLevel, + QrGradient, + QrLogoShape, } from './components/qr-code/types.js'; // Internal exports for other packages diff --git a/src/internals/testing/qr-decoder.spec.ts b/src/internals/testing/qr-decoder.spec.ts new file mode 100644 index 000000000..d4bd1f3be --- /dev/null +++ b/src/internals/testing/qr-decoder.spec.ts @@ -0,0 +1,54 @@ +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 { + prepareZXingModule({ + overrides: { + locateFile: (path: string, prefix: string) => + path.endsWith('.wasm') + ? '/node_modules/zxing-wasm/dist/reader/zxing_reader.wasm' + : prefix + path, + }, + }); +} + +/** Returns the first QR code that the decoder reads from `image`. */ +export async function readQr( + image: Blob | ImageData +): Promise<ReadResult | undefined> { + 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<Uint8Array | undefined> { + 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..cda8ce7c8 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'; @@ -57,14 +64,14 @@ const metadata: Meta<IgcQrCodeComponent> = { size: { type: 'number', description: - 'The size of the QR code in pixels. This determines the width and height of the generated QR code. The default value is 128 pixels.', + 'The size of the QR code in pixels. This determines the width and height of the generated QR code. The default value is 128 pixels.\n\nEach module covers a whole number of pixels, so the edges stay sharp. The pixels that are\nleft over widen the quiet zone, and the code can be smaller than `size`. An exported image\ngets whole pixels at its own size.', control: 'number', table: { defaultValue: { summary: '128' } }, }, margin: { type: 'number', description: - 'The margin (quiet zone) around the QR code, expressed as a number of QR code modules rather\nthan pixels. This is the blank border area surrounding the code, which helps ensure that it\ncan be properly scanned.', + 'The margin (quiet zone) around the QR code, expressed as a number of QR code modules rather\nthan pixels. This is the blank border area surrounding the code, which helps ensure that it\ncan be properly scanned. It is a minimum: spare pixels make the quiet zone wider.', control: 'number', table: { defaultValue: { summary: '4' } }, }, @@ -87,54 +94,101 @@ const metadata: Meta<IgcQrCodeComponent> = { "The margin around the logo in pixels. This is the whitespace area surrounding the logo within the QR code,\nwhich helps ensure that the logo does not interfere with the QR code's scannability.", control: 'number', }, - dotStyle: { + logoShape: { type: { name: 'enum', value: ['square', 'circle', 'rounded', 'squircle'], }, description: - "The style of the data modules (dots) in the QR code. This can be 'square', 'circle',\n'rounded', or 'squircle'. The inner dot of each finder-pattern corner uses the same style\nunless `cornerDotStyle` is set.", + "The shape of the logo: 'square', 'circle', 'rounded' or 'squircle'. The shape fills the logo\nbox, so a 'circle' logo with a wide image is an ellipse. The image is clipped to the shape,\nand the cutout holds only the modules that the shape covers, in part or in full.", options: ['square', 'circle', 'rounded', 'squircle'], control: { type: 'select' }, table: { defaultValue: { summary: 'square' } }, }, + dotStyle: { + type: { + name: 'enum', + value: [ + 'square', + 'circle', + 'rounded', + 'squircle', + 'diamond', + 'plus', + 'liquid', + 'horizontal-bars', + 'vertical-bars', + ], + }, + description: + "The style of the data modules (dots) in the QR code. This can be 'square', 'circle',\n'rounded', 'squircle', 'diamond', 'plus', 'liquid', 'horizontal-bars' or 'vertical-bars'.\n'liquid' is 'rounded' with a smooth fill in the inside corners where modules join. The bar\nstyles draw each run of dark modules in a row or a column as one bar with round ends.\n\nThe inner dot of each finder-pattern corner uses the same style unless `cornerDotStyle` is\nset. It draws 'diamond' and 'plus' as 'square', and 'liquid' and the bar styles as\n'rounded'.", + options: [ + 'square', + 'circle', + 'rounded', + 'squircle', + 'diamond', + 'plus', + 'liquid', + 'horizontal-bars', + 'vertical-bars', + ], + control: { type: 'select' }, + table: { defaultValue: { summary: 'square' } }, + }, dotScale: { type: 'number', description: - "The size of each data module, as a ratio of its cell in the module grid. The value is a\nnumber from 0.7 to 1. Other values are clamped. A value below 1 leaves a gap between the\nmodules, so 'rounded' modules do not join their neighbors. The finder-pattern corners keep\ntheir full size. A smaller value can make the code harder to scan with a camera.", + "The size of each data module, as a ratio of its cell in the module grid. The value is a\nnumber from 0.7 to 1. Other values are clamped. A value below 1 leaves a gap between the\nmodules, so 'rounded' modules do not join their neighbors, and 'liquid' draws as 'rounded'.\nFor the bar styles, it sets the thickness of the bars and shortens their ends. The\nfinder-pattern corners keep their full size. A smaller value can make the code harder to\nscan with a camera.", control: 'number', table: { defaultValue: { summary: '1' } }, }, squareStyle: { type: { name: 'enum', - value: ['square', 'circle', 'rounded', 'squircle'], + value: ['square', 'circle', 'rounded', 'squircle', 'leaf'], }, description: - "The style of the corner squares in the QR code. This can be 'square', 'circle', 'rounded',\nor 'squircle'.", - options: ['square', 'circle', 'rounded', 'squircle'], + "The style of the corner squares in the QR code. This can be 'square', 'circle', 'rounded',\n'squircle' or 'leaf'. A 'leaf' has two opposite round corners on the diagonal toward the\ncenter of the code. The rings of the alignment patterns use the same style, and a 'leaf'\nring there has the shape of the top-left corner square.", + options: ['square', 'circle', 'rounded', 'squircle', 'leaf'], control: { type: 'select' }, table: { defaultValue: { summary: 'square' } }, }, cornerDotStyle: { type: { name: 'enum', - value: ['square', 'circle', 'rounded', 'squircle'], + value: ['square', 'circle', 'rounded', 'squircle', 'leaf'], }, description: - "The style of the inner dot of each finder-pattern corner. This can be 'square', 'circle',\n'rounded', or 'squircle'. When it is not set, the inner dot uses `dotStyle`.", - options: ['square', 'circle', 'rounded', 'squircle'], + "The style of the inner dot of each finder-pattern corner. This can be 'square', 'circle',\n'rounded', 'squircle' or 'leaf'. When it is not set, the inner dot uses `dotStyle`. The\ncenters of the alignment patterns use the same style.\n\nIn a 'circle' corner square, a 'square' or 'leaf' dot draws as 'circle', because scanners\ndo not find the pattern reliably with corners in a round ring.", + options: ['square', 'circle', 'rounded', 'squircle', 'leaf'], control: { type: 'select' }, }, + gradient: { + type: { name: 'enum', value: ['linear', 'radial'] }, + description: + "The gradient of the dark modules: 'linear' or 'radial'. When it is not set, or has another\nvalue, the modules have one color. The gradient goes from `--ig-qr-code-gradient-start` to\n`--ig-qr-code-gradient-end` over the code without its quiet zone. It also paints the corners,\nunless `--ig-qr-code-corner-square-color` or `--ig-qr-code-corner-dot-color` is set.\n\nKeep both colors much darker than the background.", + options: ['linear', 'radial'], + control: { type: 'inline-radio' }, + }, + gradientAngle: { + type: 'number', + description: + "The angle of a 'linear' gradient in degrees, clockwise. At 0 the gradient goes from left to\nright, and at 90 from top to bottom.", + control: 'number', + table: { defaultValue: { summary: '0' } }, + }, }, args: { errorLevel: 'M', size: 128, margin: 4, logoSize: 0.4, + logoShape: 'square', dotStyle: 'square', dotScale: 1, squareStyle: 'square', + gradientAngle: 0, }, }; @@ -165,12 +219,18 @@ interface IgcQrCodeArgs { * `undefined` or remove the attribute. */ errorLevel: 'L' | 'M' | 'Q' | 'H'; - /** The size of the QR code in pixels. This determines the width and height of the generated QR code. The default value is 128 pixels. */ + /** + * The size of the QR code in pixels. This determines the width and height of the generated QR code. The default value is 128 pixels. + * + * Each module covers a whole number of pixels, so the edges stay sharp. The pixels that are + * left over widen the quiet zone, and the code can be smaller than `size`. An exported image + * gets whole pixels at its own size. + */ size: number; /** * The margin (quiet zone) around the QR code, expressed as a number of QR code modules rather * than pixels. This is the blank border area surrounding the code, which helps ensure that it - * can be properly scanned. + * can be properly scanned. It is a minimum: spare pixels make the quiet zone wider. */ margin: number; /** @@ -200,29 +260,71 @@ interface IgcQrCodeArgs { * which helps ensure that the logo does not interfere with the QR code's scannability. */ logoMargin: number; + /** + * The shape of the logo: 'square', 'circle', 'rounded' or 'squircle'. The shape fills the logo + * box, so a 'circle' logo with a wide image is an ellipse. The image is clipped to the shape, + * and the cutout holds only the modules that the shape covers, in part or in full. + */ + logoShape: 'square' | 'circle' | 'rounded' | 'squircle'; /** * The style of the data modules (dots) in the QR code. This can be 'square', 'circle', - * 'rounded', or 'squircle'. The inner dot of each finder-pattern corner uses the same style - * unless `cornerDotStyle` is set. + * 'rounded', 'squircle', 'diamond', 'plus', 'liquid', 'horizontal-bars' or 'vertical-bars'. + * 'liquid' is 'rounded' with a smooth fill in the inside corners where modules join. The bar + * styles draw each run of dark modules in a row or a column as one bar with round ends. + * + * The inner dot of each finder-pattern corner uses the same style unless `cornerDotStyle` is + * set. It draws 'diamond' and 'plus' as 'square', and 'liquid' and the bar styles as + * 'rounded'. */ - dotStyle: 'square' | 'circle' | 'rounded' | 'squircle'; + dotStyle: + | 'square' + | 'circle' + | 'rounded' + | 'squircle' + | 'diamond' + | 'plus' + | 'liquid' + | 'horizontal-bars' + | 'vertical-bars'; /** * The size of each data module, as a ratio of its cell in the module grid. The value is a * number from 0.7 to 1. Other values are clamped. A value below 1 leaves a gap between the - * modules, so 'rounded' modules do not join their neighbors. The finder-pattern corners keep - * their full size. A smaller value can make the code harder to scan with a camera. + * modules, so 'rounded' modules do not join their neighbors, and 'liquid' draws as 'rounded'. + * For the bar styles, it sets the thickness of the bars and shortens their ends. The + * finder-pattern corners keep their full size. A smaller value can make the code harder to + * scan with a camera. */ dotScale: number; /** * The style of the corner squares in the QR code. This can be 'square', 'circle', 'rounded', - * or 'squircle'. + * 'squircle' or 'leaf'. A 'leaf' has two opposite round corners on the diagonal toward the + * center of the code. The rings of the alignment patterns use the same style, and a 'leaf' + * ring there has the shape of the top-left corner square. */ - squareStyle: 'square' | 'circle' | 'rounded' | 'squircle'; + squareStyle: 'square' | 'circle' | 'rounded' | 'squircle' | 'leaf'; /** * The style of the inner dot of each finder-pattern corner. This can be 'square', 'circle', - * 'rounded', or 'squircle'. When it is not set, the inner dot uses `dotStyle`. + * 'rounded', 'squircle' or 'leaf'. When it is not set, the inner dot uses `dotStyle`. The + * centers of the alignment patterns use the same style. + * + * In a 'circle' corner square, a 'square' or 'leaf' dot draws as 'circle', because scanners + * do not find the pattern reliably with corners in a round ring. */ - cornerDotStyle: 'square' | 'circle' | 'rounded' | 'squircle'; + cornerDotStyle: 'square' | 'circle' | 'rounded' | 'squircle' | 'leaf'; + /** + * The gradient of the dark modules: 'linear' or 'radial'. When it is not set, or has another + * value, the modules have one color. The gradient goes from `--ig-qr-code-gradient-start` to + * `--ig-qr-code-gradient-end` over the code without its quiet zone. It also paints the corners, + * unless `--ig-qr-code-corner-square-color` or `--ig-qr-code-corner-dot-color` is set. + * + * Keep both colors much darker than the background. + */ + gradient: 'linear' | 'radial'; + /** + * The angle of a 'linear' gradient in degrees, clockwise. At 0 the gradient goes from left to + * right, and at 90 from top to bottom. + */ + gradientAngle: number; } type Story = StoryObj<IgcQrCodeArgs>; @@ -231,6 +333,9 @@ type Story = StoryObj<IgcQrCodeArgs>; const productUrl = 'https://www.infragistics.com/products/ignite-ui-web-components'; +/** A short value: a code of 25 modules, so the modules are large enough to compare shapes. */ +const shortUrl = 'https://infragistics.com'; + const samples = html` <style> .qr-samples { @@ -249,18 +354,49 @@ const samples = html` } .qr-samples figcaption { - max-width: 12rem; + max-width: 15rem; text-align: center; } + + .qr-samples code { + overflow-wrap: anywhere; + } + + .qr-section { + margin-block: 2rem 1rem; + } + + .qr-section:first-of-type { + margin-block-start: 0; + } </style> `; /** Makes a square logo with a short text as an SVG data URI. */ -function logo(background: string, color: string, text: string): string { - const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="${background}"/><text x="32" y="43" fill="${color}" font-family="sans-serif" font-size="28" font-weight="700" text-anchor="middle">${text}</text></svg>`; +function logo( + background: string, + color: string, + text: string, + radius = 14 +): string { + const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="${radius}" fill="${background}"/><text x="32" y="43" fill="${color}" font-family="sans-serif" font-size="28" font-weight="700" text-anchor="middle">${text}</text></svg>`; return `data:image/svg+xml,${encodeURIComponent(svg)}`; } +/** Makes a logo twice as wide as it is high, with a short text, as an SVG data URI. */ +function wideLogo(background: string, color: string, text: string): string { + const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="128" height="64" viewBox="0 0 128 64"><rect width="128" height="64" fill="${background}"/><text x="64" y="43" fill="${color}" font-family="sans-serif" font-size="28" font-weight="700" text-anchor="middle">${text}</text></svg>`; + return `data:image/svg+xml,${encodeURIComponent(svg)}`; +} + +/** A code with a caption. */ +function sample(caption: unknown, code: unknown) { + return html`<figure> + ${code} + <figcaption>${caption}</figcaption> + </figure>`; +} + export const Default: Story = { parameters: { docs: { @@ -272,6 +408,7 @@ export const Default: Story = { }, args: { value: productUrl, + size: 256, }, }; @@ -281,93 +418,144 @@ export const Shapes: Story = { docs: { description: { story: - '`dot-style` sets the shape of the data modules and of the inner dot of each corner. `square-style` sets the shape of the outer corner squares. The table shows all 16 combinations for the same value. Below it, `corner-dot-style` gives the inner corner dots a shape of their own, and `dot-scale` shrinks the data modules to leave a gap between them.', + '`dot-style` sets the shape of the data modules. Without `corner-dot-style`, the inner corner dots follow it: `diamond` and `plus` give square dots, and `liquid` and the bars give rounded dots. `square-style` sets the shape of the outer corner squares and of the alignment rings. `corner-dot-style` sets the shape of the inner corner dots and of the alignment centers. In a `circle` corner square, a `square` or `leaf` corner dot draws as a circle, so that scanners find the corner. `dot-scale` makes the data modules smaller, with a gap between them. The samples encode a short value, so the modules are large.', }, }, }, render: () => { - const shapes = ['square', 'circle', 'rounded', 'squircle'] as const; - const variants = [ + const dotStyles = [ + 'square', + 'circle', + 'rounded', + 'squircle', + 'diamond', + 'plus', + 'liquid', + 'horizontal-bars', + 'vertical-bars', + ] as const; + const cornerStyles = [ + 'square', + 'circle', + 'rounded', + 'squircle', + 'leaf', + ] as const; + const scales = [ + { dot: 'circle', scale: 1 }, + { dot: 'circle', scale: 0.85 }, + { dot: 'circle', scale: 0.7 }, + { dot: 'rounded', scale: 0.85 }, + { dot: 'horizontal-bars', scale: 0.7 }, + ] as const; + const combinations = [ { - caption: 'Squircle modules with circle corner dots', + caption: 'Squircle modules and corners with circle corner dots', dot: 'squircle', square: 'squircle', cornerDot: 'circle', - scale: 1, }, { - caption: 'Square modules at dot-scale 0.8', - dot: 'square', - square: 'square', - cornerDot: undefined, - scale: 0.8, + caption: 'Liquid modules with rounded corners', + dot: 'liquid', + square: 'rounded', + }, + { + caption: 'Horizontal bars with leaf corners', + dot: 'horizontal-bars', + square: 'leaf', + cornerDot: 'leaf', }, { - caption: 'Circle modules at dot-scale 0.7', - dot: 'circle', + caption: 'Plus modules with circle corners', + dot: 'plus', square: 'circle', - cornerDot: undefined, - scale: 0.7, }, { - caption: 'Rounded modules at dot-scale 0.85, which do not join', - dot: 'rounded', - square: 'rounded', - cornerDot: undefined, - scale: 0.85, + caption: 'Diamond modules with squircle corners and square dots', + dot: 'diamond', + square: 'squircle', + cornerDot: 'square', }, ] as const; return html` ${samples} - <div style="overflow-x: auto"> - <table style="border-spacing: 1.5rem 1rem; text-align: center"> - <thead> - <tr> - <td></td> - ${shapes.map( - (shape) => html`<th scope="col">dot-style="${shape}"</th>` - )} - </tr> - </thead> - <tbody> - ${shapes.map( - (square) => html` - <tr> - <th scope="row">square-style="${square}"</th> - ${shapes.map( - (dot) => html` - <td> - <igc-qr-code - value=${productUrl} - size="112" - dot-style=${dot} - square-style=${square} - ></igc-qr-code> - </td> - ` - )} - </tr> - ` - )} - </tbody> - </table> + <h3 class="qr-section">dot-style</h3> + <div class="qr-samples"> + ${dotStyles.map((dot) => + sample( + html`<code>dot-style="${dot}"</code>`, + html`<igc-qr-code + value=${shortUrl} + size="220" + dot-style=${dot} + ></igc-qr-code>` + ) + )} </div> + + <h3 class="qr-section">square-style</h3> <div class="qr-samples"> - ${variants.map( - (variant) => html` - <figure> - <igc-qr-code - value=${productUrl} - size="160" - dot-style=${variant.dot} - square-style=${variant.square} - corner-dot-style=${ifDefined(variant.cornerDot)} - dot-scale=${variant.scale} - ></igc-qr-code> - <figcaption>${variant.caption}</figcaption> - </figure> - ` + ${cornerStyles.map((square) => + sample( + html`<code>square-style="${square}"</code>`, + html`<igc-qr-code + value=${shortUrl} + size="220" + square-style=${square} + ></igc-qr-code>` + ) + )} + </div> + + <h3 class="qr-section">corner-dot-style</h3> + <div class="qr-samples"> + ${cornerStyles.map((cornerDot) => + sample( + html`<code>corner-dot-style="${cornerDot}"</code>`, + html`<igc-qr-code + value=${shortUrl} + size="220" + square-style="rounded" + corner-dot-style=${cornerDot} + ></igc-qr-code>` + ) + )} + </div> + + <h3 class="qr-section">dot-scale</h3> + <div class="qr-samples"> + ${scales.map(({ dot, scale }) => + sample( + html`<code>dot-style="${dot}"</code><br /><code + >dot-scale="${scale}"</code + >`, + html`<igc-qr-code + value=${shortUrl} + size="220" + dot-style=${dot} + dot-scale=${scale} + ></igc-qr-code>` + ) + )} + </div> + + <h3 class="qr-section">Combinations</h3> + <div class="qr-samples"> + ${combinations.map((variant) => + sample( + variant.caption, + html`<igc-qr-code + value=${shortUrl} + size="220" + dot-style=${variant.dot} + square-style=${variant.square} + corner-dot-style=${ifDefined( + 'cornerDot' in variant ? variant.cornerDot : undefined + )} + ></igc-qr-code>` + ) )} </div> `; @@ -380,12 +568,17 @@ export const Colors: Story = { docs: { description: { story: - 'CSS custom properties set the colors. `--ig-qr-code-dark-color` colors the data modules and, by default, the corners. `--ig-qr-code-corner-square-color` and `--ig-qr-code-corner-dot-color` override the two parts of the corners. The colors do not follow the light and dark theme variants, because a code that inverts itself can stop to scan. Keep a strong contrast between the modules and the background: some older readers cannot scan an inverted code, and most readers cannot scan a code with low contrast.', + 'CSS custom properties set the colors. `--ig-qr-code-dark-color` colors the data modules and, by default, the corners. `--ig-qr-code-corner-square-color` and `--ig-qr-code-corner-dot-color` override the two parts of the corners. `gradient` paints the modules with a `linear` or `radial` gradient from `--ig-qr-code-gradient-start` to `--ig-qr-code-gradient-end`. `gradient-angle` turns a linear gradient. The colors do not follow the light and dark theme variants, because some readers cannot scan an inverted code. Keep the dark colors and both gradient colors much darker than the background. Most readers cannot scan a code with low contrast. Test the colors with the phones and the apps of your users.', }, }, }, render: () => { - const variants = [ + const variants: { + caption: string; + style: string; + gradient?: 'linear' | 'radial'; + angle?: number; + }[] = [ { caption: 'Brand colors', style: @@ -396,6 +589,38 @@ export const Colors: Story = { style: '--ig-qr-code-dark-color: #1f2937; --ig-qr-code-corner-square-color: #e63946; --ig-qr-code-corner-dot-color: #457b9d;', }, + { + caption: 'Linear gradient, left to right (gradient-angle 0)', + style: + '--ig-qr-code-gradient-start: #1a237e; --ig-qr-code-gradient-end: #880e4f;', + gradient: 'linear', + }, + { + caption: 'Linear gradient, corner to corner (gradient-angle 45)', + style: + '--ig-qr-code-gradient-start: #0b3d91; --ig-qr-code-gradient-end: #2a7f62;', + gradient: 'linear', + angle: 45, + }, + { + caption: 'Linear gradient, top to bottom (gradient-angle 90)', + style: + '--ig-qr-code-gradient-start: #4a148c; --ig-qr-code-gradient-end: #b71c1c;', + gradient: 'linear', + angle: 90, + }, + { + caption: 'Radial gradient, center to corners', + style: + '--ig-qr-code-gradient-start: #6a1b9a; --ig-qr-code-gradient-end: #0d47a1;', + gradient: 'radial', + }, + { + caption: 'Radial gradient with accent corner dots', + style: + '--ig-qr-code-gradient-start: #0b3d91; --ig-qr-code-gradient-end: #1d6f65; --ig-qr-code-corner-dot-color: #e63946;', + gradient: 'radial', + }, { caption: 'Inverted, for a dark print', style: @@ -411,24 +636,85 @@ export const Colors: Story = { return html` ${samples} <div class="qr-samples"> - ${variants.map( - ({ caption, style }) => html` - <figure> - <igc-qr-code - value=${productUrl} - size="160" - dot-style="rounded" - style=${style} - ></igc-qr-code> - <figcaption>${caption}</figcaption> - </figure> - ` + ${variants.map(({ caption, style, gradient, angle }) => + sample( + caption, + html`<igc-qr-code + value=${shortUrl} + size="220" + dot-style="rounded" + square-style="rounded" + gradient=${ifDefined(gradient)} + gradient-angle=${ifDefined(angle)} + style=${style} + ></igc-qr-code>` + ) )} </div> `; }, }; +/** The gradient colors are CSS custom properties, not attributes, so they are not in the generated args. */ +type GradientStory = StoryObj< + IgcQrCodeArgs & { gradientStart: string; gradientEnd: string } +>; + +export const Gradient: GradientStory = { + argTypes: { + ...disableStoryControls(metadata), + gradient: metadata.argTypes!.gradient, + gradientAngle: { + ...metadata.argTypes!.gradientAngle, + control: { type: 'range', min: 0, max: 360, step: 15 }, + }, + gradientStart: { + control: 'color', + description: 'The value of `--ig-qr-code-gradient-start`.', + }, + gradientEnd: { + control: 'color', + description: 'The value of `--ig-qr-code-gradient-end`.', + }, + dotStyle: metadata.argTypes!.dotStyle, + squareStyle: metadata.argTypes!.squareStyle, + }, + args: { + gradient: 'linear', + gradientAngle: 45, + gradientStart: '#1a237e', + gradientEnd: '#880e4f', + dotStyle: 'liquid', + squareStyle: 'rounded', + }, + parameters: { + docs: { + description: { + story: + 'Use the controls to change the gradient. `gradient` sets the type, `gradient-angle` turns a linear gradient clockwise, and the color pickers set `--ig-qr-code-gradient-start` and `--ig-qr-code-gradient-end`. The gradient spans the modules, not the quiet zone. Keep both colors much darker than the background.', + }, + }, + }, + render: ({ + gradient, + gradientAngle, + gradientStart, + gradientEnd, + dotStyle, + squareStyle, + }) => html` + <igc-qr-code + value=${productUrl} + size="320" + gradient=${ifDefined(gradient)} + gradient-angle=${gradientAngle} + dot-style=${dotStyle} + square-style=${squareStyle} + style="--ig-qr-code-gradient-start: ${gradientStart}; --ig-qr-code-gradient-end: ${gradientEnd};" + ></igc-qr-code> + `, +}; + export const ErrorCorrection: Story = { argTypes: disableStoryControls(metadata), parameters: { @@ -507,12 +793,12 @@ export const WithLogo: Story = { docs: { description: { story: - '`logo-src` puts an image at the center of the code and removes the modules under it. `logo-size` is a ratio of the area that the error correction level can restore, not of the full code: `1` covers 9% of the code at level `H`. `logo-margin` adds whitespace around the logo, in pixels. Without `error-level`, the code uses level `M`, and a logo larger than the safe area of `M` raises the level to the smallest one that holds it, as in the first two codes. An explicit level caps the logo to the area of that level, so the logo in the last code shrinks. A logo source must be an image: a `javascript:` URL or a data URI of another type is ignored.', + '`logo-src` puts an image at the center of the code and removes the modules under it. `logo-size` is a ratio of the area that the error correction level can restore, not of the full code: `1` covers 9% of the code at level `H`. `logo-margin` adds whitespace around the logo, in pixels. Without `error-level`, the code uses level `M`, and a logo larger than the safe area of `M` raises the level to the smallest one that holds it, as in the first two codes. An explicit level caps the logo to the area of that level, so the logo in the fourth code shrinks. `logo-shape` clips the logo to a `circle`, `rounded` or `squircle` shape that fills the logo box, and the code removes only the modules under the shape. A wide image in a `circle` gives an ellipse. A `rounded` or `liquid` module and a bar end round at the edge of the removed area. A logo source must be an image: a `javascript:` URL or a data URI of another type is ignored.', }, }, }, render: () => { - const variants: { + const sizes: { caption: string; logo: string; size: number; @@ -551,67 +837,144 @@ export const WithLogo: Story = { style: '--ig-qr-code-dark-color: #1d6f65;', }, ]; + const shapes: { + caption: unknown; + logo: string; + shape: 'square' | 'circle' | 'rounded' | 'squircle'; + dot: 'square' | 'rounded' | 'liquid' | 'horizontal-bars'; + }[] = [ + { + caption: html`<code>logo-shape="square"</code>`, + logo: logo('#e63946', '#ffffff', 'GO', 0), + shape: 'square', + dot: 'square', + }, + { + caption: html`<code>logo-shape="circle"</code>`, + logo: logo('#e63946', '#ffffff', 'GO', 0), + shape: 'circle', + dot: 'square', + }, + { + caption: html`<code>logo-shape="rounded"</code>`, + logo: logo('#e63946', '#ffffff', 'GO', 0), + shape: 'rounded', + dot: 'square', + }, + { + caption: html`<code>logo-shape="squircle"</code>`, + logo: logo('#e63946', '#ffffff', 'GO', 0), + shape: 'squircle', + dot: 'square', + }, + { + caption: 'A wide image in a circle: an ellipse', + logo: wideLogo('#0b3d91', '#ffffff', 'IGNITE'), + shape: 'circle', + dot: 'square', + }, + { + caption: 'Liquid modules end round at a circle logo', + logo: logo('#0b3d91', '#ffffff', 'UI', 0), + shape: 'circle', + dot: 'liquid', + }, + { + caption: 'Bars end round at a squircle logo', + logo: logo('#2a9d8f', '#ffffff', 'ECO', 0), + shape: 'squircle', + dot: 'horizontal-bars', + }, + ]; return html` ${samples} + <h3 class="qr-section">logo-size and error-level</h3> <div class="qr-samples"> - ${variants.map( - (variant) => html` - <figure> - <igc-qr-code - value=${productUrl} - size="200" - dot-style="circle" - square-style="rounded" - error-level=${ifDefined(variant.level)} - logo-src=${variant.logo} - logo-size=${variant.size} - .logoMargin=${variant.margin} - style=${variant.style} - ></igc-qr-code> - <figcaption>${variant.caption}</figcaption> - </figure> - ` + ${sizes.map((variant) => + sample( + variant.caption, + html`<igc-qr-code + value=${productUrl} + size="240" + dot-style="circle" + square-style="rounded" + error-level=${ifDefined(variant.level)} + logo-src=${variant.logo} + logo-size=${variant.size} + .logoMargin=${variant.margin} + style=${variant.style} + ></igc-qr-code>` + ) + )} + </div> + + <h3 class="qr-section">logo-shape</h3> + <div class="qr-samples"> + ${shapes.map((variant) => + sample( + variant.caption, + html`<igc-qr-code + value=${shortUrl} + size="240" + dot-style=${variant.dot} + square-style="rounded" + logo-src=${variant.logo} + logo-size="1" + logo-shape=${variant.shape} + ></igc-qr-code>` + ) )} </div> `; }, }; -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, string>) => string } + { + label: string; + encode: (fields: Record<string, string>) => 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 +985,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 +995,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 +1008,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 +1116,12 @@ export const Generator: Story = { value="Ivanova" @igcInput=${update} ></igc-input> + <igc-input + name="organization" + label="Company" + value="Example Ltd." + @igcInput=${update} + ></igc-input> <igc-input name="phone" type="tel" @@ -762,6 +1138,67 @@ export const Generator: Story = { ></igc-input> </div> + <div data-type="payment" hidden> + <igc-input + name="beneficiary" + label="Beneficiary" + value="Example Charity e.V." + @igcInput=${update} + ></igc-input> + <igc-input + name="iban" + label="IBAN" + value="DE89 3704 0044 0532 0130 00" + @igcInput=${update} + ></igc-input> + <igc-input + name="amount" + type="number" + label="Amount in euros" + value="25.00" + @igcInput=${update} + ></igc-input> + <igc-input + name="remittance" + label="Remittance text" + value="Donation 2026" + @igcInput=${update} + ></igc-input> + </div> + + <div data-type="event" hidden> + <igc-input + name="summary" + label="Title" + value="Team meetup" + @igcInput=${update} + ></igc-input> + <igc-input + name="date" + label="Date (YYYY-MM-DD)" + value="2026-12-04" + @igcInput=${update} + ></igc-input> + <igc-input + name="start" + label="Start time (HH:MM)" + value="18:00" + @igcInput=${update} + ></igc-input> + <igc-input + name="end" + label="End time (HH:MM)" + value="21:00" + @igcInput=${update} + ></igc-input> + <igc-input + name="location" + label="Location" + value="Main hall" + @igcInput=${update} + ></igc-input> + </div> + <div data-type="text" hidden> <igc-input name="text" @@ -791,6 +1228,47 @@ export const Generator: Story = { }, }; +export const PhoneActions: Story = { + argTypes: disableStoryControls(metadata), + parameters: { + docs: { + description: { + story: + 'Codes that open an app on the phone: an email draft, a call, a text message and a place on a map. They are plain URLs, so they need no helper. Encode the text parts with `encodeURIComponent()`. The text message uses the `SMSTO:` form with one number. Readers differ in how they fill in a message, so test the code on the phones of your users.', + }, + }, + }, + render: () => { + const actions = [ + { + caption: 'Email draft', + value: `mailto:support@example.com?subject=${encodeURIComponent('Order 1042')}&body=${encodeURIComponent('Hello, I have a question about my order.')}`, + }, + { caption: 'Phone call', value: 'tel:+15550100' }, + { caption: 'Text message', value: 'SMSTO:+15550100:Table 12 is ready' }, + { caption: 'Place on a map', value: 'geo:42.6977,23.3219' }, + ]; + + return html` + ${samples} + <div class="qr-samples"> + ${actions.map( + ({ caption, value }) => html` + <figure> + <igc-qr-code + value=${value} + size="160" + aria-label="${caption} QR code" + ></igc-qr-code> + <figcaption>${caption}<br /><code>${value}</code></figcaption> + </figure> + ` + )} + </div> + `; + }, +}; + export const Tickets: Story = { argTypes: disableStoryControls(metadata), parameters: { @@ -888,6 +1366,55 @@ export const Tickets: Story = { }, }; +export const TableCard: Story = { + argTypes: disableStoryControls(metadata), + parameters: { + docs: { + description: { + story: + 'A table card in a café, with a "Scan me" frame around the code. The frame is plain HTML and CSS: a `figure` with a border, a title and a caption. The component draws only the code, so `toImage()` and `copyToClipboard()` export the code without the frame. To print the card, print the page. Keep the quiet zone of the code between the frame and the modules.', + }, + }, + }, + render: () => html` + <style> + .table-card { + display: grid; + justify-items: center; + gap: 0.75rem; + inline-size: max-content; + margin: 0; + padding: 1.5rem 2rem; + border: 4px solid var(--ig-gray-900); + border-radius: 1.5rem; + text-align: center; + } + + .table-card .title { + margin: 0; + font-size: 1.5rem; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; + } + </style> + + <figure class="table-card"> + <p class="title">Scan me</p> + <igc-qr-code + value="https://example.com/menu?table=12" + aria-label="Menu QR code" + size="200" + dot-style="rounded" + square-style="rounded" + ></igc-qr-code> + <figcaption> + See the menu and order from table 12.<br />example.com/menu + </figcaption> + </figure> + `, +}; + export const Export: Story = { argTypes: disableStoryControls(metadata), parameters: {