@vkontakte/vk-qr 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,254 @@
1
+ import { MODULE_CORNER_RADIUS, TILE_SIZE } from './constants.ts';
2
+ import type { Figure } from './figures.ts';
3
+
4
+ interface SvgPathOptions {
5
+ pixelSize?: number;
6
+ radius?: number;
7
+ }
8
+
9
+ interface Point {
10
+ x: number;
11
+ y: number;
12
+ }
13
+
14
+ interface Edge {
15
+ from: Point;
16
+ to: Point;
17
+ }
18
+
19
+ type CornerRadius = (prev: Point, current: Point, next: Point) => number;
20
+
21
+ export function figureToSvgPath(figure: Figure, options: SvgPathOptions = {}): string {
22
+ const pixelSize = options.pixelSize ?? TILE_SIZE;
23
+ const radius = options.radius ?? MODULE_CORNER_RADIUS;
24
+ const contours = buildContours(getBoundaryEdges(figure, pixelSize));
25
+ const cornerRadius = createCornerRadiusResolver(figure, pixelSize, radius);
26
+
27
+ return contours.map((contour) => contourToRoundedPath(contour, cornerRadius)).join(' ');
28
+ }
29
+
30
+ function hasPixel(pixels: boolean[][], x: number, y: number): boolean {
31
+ return pixels[y]?.[x] ?? false;
32
+ }
33
+
34
+ function getBoundaryEdges(figure: Figure, pixelSize: number): Edge[] {
35
+ const pixels = figure.pixels;
36
+ const height = pixels.length;
37
+ const width = pixels[0]?.length ?? 0;
38
+
39
+ const edges: Edge[] = [];
40
+
41
+ function px(x: number): number {
42
+ return (figure.x + x) * pixelSize;
43
+ }
44
+
45
+ function py(y: number): number {
46
+ return (figure.y + y) * pixelSize;
47
+ }
48
+
49
+ // Trace exposed edges with the filled module on their right.
50
+ for (let y = 0; y < height; y++) {
51
+ for (let x = 0; x < width; x++) {
52
+ if (!pixels[y][x]) continue;
53
+
54
+ const left = px(x);
55
+ const right = px(x + 1);
56
+ const top = py(y);
57
+ const bottom = py(y + 1);
58
+
59
+ if (!hasPixel(pixels, x, y - 1)) {
60
+ edges.push({
61
+ from: { x: left, y: top },
62
+ to: { x: right, y: top },
63
+ });
64
+ }
65
+
66
+ if (!hasPixel(pixels, x + 1, y)) {
67
+ edges.push({
68
+ from: { x: right, y: top },
69
+ to: { x: right, y: bottom },
70
+ });
71
+ }
72
+
73
+ if (!hasPixel(pixels, x, y + 1)) {
74
+ edges.push({
75
+ from: { x: right, y: bottom },
76
+ to: { x: left, y: bottom },
77
+ });
78
+ }
79
+
80
+ if (!hasPixel(pixels, x - 1, y)) {
81
+ edges.push({
82
+ from: { x: left, y: bottom },
83
+ to: { x: left, y: top },
84
+ });
85
+ }
86
+ }
87
+ }
88
+
89
+ return edges;
90
+ }
91
+
92
+ function hasFilledCorner(
93
+ pixels: boolean[][],
94
+ x: number,
95
+ y: number,
96
+ dx: number,
97
+ dy: number,
98
+ ): boolean {
99
+ return (
100
+ hasPixel(pixels, x + dx, y) && hasPixel(pixels, x, y + dy) && hasPixel(pixels, x + dx, y + dy)
101
+ );
102
+ }
103
+
104
+ function createCornerRadiusResolver(
105
+ figure: Figure,
106
+ pixelSize: number,
107
+ radius: number,
108
+ ): CornerRadius {
109
+ return (prev: Point, current: Point, next: Point): number => {
110
+ if (getTurn(prev, current, next) < 0) {
111
+ const x = Math.round(Math.min(prev.x, current.x, next.x) / pixelSize) - figure.x;
112
+ const y = Math.round(Math.min(prev.y, current.y, next.y) / pixelSize) - figure.y;
113
+
114
+ // Each old selector assignment reset the previous match when it failed.
115
+ // Consequently only n_rb could survive the final assignment.
116
+ const topLeft = hasFilledCorner(figure.pixels, x, y, -1, -1);
117
+ const bottomLeft = hasFilledCorner(figure.pixels, x, y, -1, 1);
118
+ const topRight = hasFilledCorner(figure.pixels, x, y, 1, -1);
119
+ const bottomRight = hasFilledCorner(figure.pixels, x, y, 1, 1);
120
+ const roundsBottomRight = bottomRight && (!topRight || (bottomLeft && !topLeft));
121
+
122
+ return roundsBottomRight &&
123
+ current.x === (figure.x + (x + 1)) * pixelSize &&
124
+ current.y === (figure.y + (y + 1)) * pixelSize
125
+ ? radius
126
+ : 0;
127
+ }
128
+
129
+ return radius;
130
+ };
131
+ }
132
+
133
+ function buildContours(edges: Edge[]): Point[][] {
134
+ const edgeMap = new Map<string, Point[]>();
135
+
136
+ for (const edge of edges) {
137
+ const key = pointKey(edge.from);
138
+ const list = edgeMap.get(key);
139
+ if (list) {
140
+ list.push(edge.to);
141
+ } else {
142
+ edgeMap.set(key, [edge.to]);
143
+ }
144
+ }
145
+
146
+ const contours: Point[][] = [];
147
+
148
+ while (true) {
149
+ const startKey = edgeMap.keys().next().value;
150
+ if (startKey === undefined) break;
151
+
152
+ const [x, y] = startKey.split(',').map(Number);
153
+ const start = { x, y };
154
+
155
+ const contour: Point[] = [start];
156
+ let current = start;
157
+
158
+ while (true) {
159
+ const candidates = edgeMap.get(pointKey(current));
160
+
161
+ if (!candidates || candidates.length === 0) {
162
+ throw new Error('Broken contour: edge chain is not closed');
163
+ }
164
+
165
+ // At a diagonal touch, keep the filled pixel on the right of the edge.
166
+ // Otherwise two convex corners become concave and a false hole is traced.
167
+ let nextIndex = 0;
168
+ if (candidates.length > 1 && contour.length > 1) {
169
+ const prev = contour[contour.length - 2];
170
+ const rightTurn = candidates.findIndex(
171
+ (candidate) => getTurn(prev, current, candidate) > 0,
172
+ );
173
+ if (rightTurn !== -1) nextIndex = rightTurn;
174
+ }
175
+ const [next] = candidates.splice(nextIndex, 1);
176
+ if (candidates.length === 0) edgeMap.delete(pointKey(current));
177
+
178
+ if (samePoint(next, start)) {
179
+ break;
180
+ }
181
+
182
+ contour.push(next);
183
+ current = next;
184
+ }
185
+
186
+ contours.push(contour);
187
+ }
188
+
189
+ return contours;
190
+ }
191
+
192
+ function contourToRoundedPath(contour: Point[], cornerRadius: CornerRadius): string {
193
+ const n = contour.length;
194
+
195
+ if (n === 0) return '';
196
+
197
+ const commands: string[] = [];
198
+
199
+ for (let i = 0; i < n; i++) {
200
+ const prev = contour[(i - 1 + n) % n];
201
+ const current = contour[i];
202
+ const next = contour[(i + 1) % n];
203
+
204
+ const incomingLength = distance(current, prev);
205
+ const outgoingLength = distance(current, next);
206
+
207
+ const r = Math.min(cornerRadius(prev, current, next), incomingLength / 2, outgoingLength / 2);
208
+
209
+ const beforeCorner = moveTowards(current, prev, r);
210
+ const afterCorner = moveTowards(current, next, r);
211
+
212
+ commands.push(`${i === 0 ? 'M' : 'L'} ${beforeCorner.x} ${beforeCorner.y}`);
213
+
214
+ if (r > 0) {
215
+ commands.push(`Q ${current.x} ${current.y} ${afterCorner.x} ${afterCorner.y}`);
216
+ }
217
+ }
218
+
219
+ commands.push('Z');
220
+
221
+ return commands.join(' ');
222
+ }
223
+
224
+ function moveTowards(from: Point, to: Point, distanceValue: number): Point {
225
+ const length = distance(from, to);
226
+
227
+ if (length === 0) {
228
+ return { ...from };
229
+ }
230
+
231
+ const ratio = distanceValue / length;
232
+
233
+ return {
234
+ x: from.x + (to.x - from.x) * ratio,
235
+ y: from.y + (to.y - from.y) * ratio,
236
+ };
237
+ }
238
+
239
+ function distance(a: Point, b: Point): number {
240
+ return Math.hypot(a.x - b.x, a.y - b.y);
241
+ }
242
+
243
+ function pointKey(point: Point): string {
244
+ return `${point.x},${point.y}`;
245
+ }
246
+
247
+ function samePoint(a: Point, b: Point): boolean {
248
+ return a.x === b.x && a.y === b.y;
249
+ }
250
+
251
+ /** Positive for a right turn in SVG's downward-pointing Y axis. */
252
+ function getTurn(prev: Point, current: Point, next: Point): number {
253
+ return (current.x - prev.x) * (next.y - current.y) - (current.y - prev.y) * (next.x - current.x);
254
+ }