Skip to content

Commit e4631a5

Browse files
fix(#68): Code 128 auto-encode now switches back from Code A to B
When encountering control characters, the encoder now uses SHIFT for isolated control chars and properly switches back to Code B for subsequent printable characters. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent b4e8107 commit e4631a5

1 file changed

Lines changed: 23 additions & 5 deletions

File tree

src/encoders/code128.ts

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ const START_C = 105;
132132
const CODE_A = 101;
133133
const CODE_B = 100;
134134
const CODE_C = 99;
135+
const SHIFT = 98;
135136

136137
/**
137138
* Encode text as Code 128 barcode
@@ -219,15 +220,32 @@ function autoEncode(text: string): number[] {
219220
} else {
220221
const charCode = text.charCodeAt(pos);
221222
if (charCode >= 32 && charCode <= 126) {
222-
// Code B
223+
// Printable character — needs Code B
224+
if (currentSet === "A") {
225+
codes.push(CODE_B);
226+
currentSet = "B";
227+
}
223228
codes.push(charCode - 32);
224229
} else if (charCode >= 0 && charCode < 32) {
225-
// Need Code A for control chars
230+
// Control character — needs Code A
226231
if (currentSet !== "A") {
227-
codes.push(CODE_A);
228-
currentSet = "A";
232+
// Check if this is a single control char followed by printable text
233+
// If so, use SHIFT to temporarily access Code A for one character
234+
const nextCharCode = pos + 1 < text.length ? text.charCodeAt(pos + 1) : -1;
235+
if (nextCharCode >= 32 && nextCharCode <= 126) {
236+
// Single control char surrounded by printable text — use SHIFT
237+
codes.push(SHIFT);
238+
codes.push(charCode + 64);
239+
// currentSet stays as "B" since SHIFT is temporary
240+
} else {
241+
// Multiple control chars or end of string — switch to Code A
242+
codes.push(CODE_A);
243+
currentSet = "A";
244+
codes.push(charCode + 64);
245+
}
246+
} else {
247+
codes.push(charCode + 64);
229248
}
230-
codes.push(charCode + 64);
231249
}
232250
pos++;
233251
}

0 commit comments

Comments
 (0)