> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sparklane.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Code 128

> The general-purpose linear barcode for text and numbers: its three code sets, structure, mod-103 check character, and how to scan it.

export const Barcode = ({view, ...props}) => {
  const BARCODE_GROUPS = [{
    key: 'retail',
    name: 'Retail product',
    anchor: 'retail-product'
  }, {
    key: 'logistics',
    name: 'Logistics and shipping',
    anchor: 'logistics-and-shipping'
  }, {
    key: 'gs1',
    name: 'GS1',
    anchor: 'gs1'
  }, {
    key: 'linear',
    name: '1D (linear)',
    anchor: '1d-linear'
  }, {
    key: 'matrix',
    name: '2D (matrix)',
    anchor: '2d-matrix'
  }, {
    key: 'postal',
    name: 'Postal',
    anchor: 'postal'
  }, {
    key: 'id',
    name: 'ID and documents',
    anchor: 'id-and-documents'
  }];
  const BARCODE_TYPES = [{
    slug: 'upc-a',
    name: 'UPC-A',
    dimension: '1D',
    data: 'Digits 0–9',
    length: '12 digits',
    check: {
      label: 'GS1 mod-10',
      method: 'gs1-mod10'
    },
    groups: ['retail', 'linear'],
    standard: 'ISO/IEC 15420:2025, GS1 General Specifications',
    status: 'active',
    example: '061414100007',
    verified: true
  }, {
    slug: 'upc-e',
    name: 'UPC-E',
    dimension: '1D',
    data: 'Digits 0–9',
    length: '8 digits (expands to 12)',
    check: {
      label: 'GS1 mod-10, on the expanded UPC-A',
      method: 'upc-e'
    },
    groups: ['retail', 'linear'],
    standard: 'ISO/IEC 15420:2025, GS1 General Specifications',
    status: 'active',
    example: '01234565',
    verified: true
  }, {
    slug: 'ean-13',
    name: 'EAN-13',
    dimension: '1D',
    data: 'Digits 0–9',
    length: '13 digits',
    check: {
      label: 'GS1 mod-10',
      method: 'gs1-mod10'
    },
    groups: ['retail', 'linear'],
    standard: 'ISO/IEC 15420:2025, GS1 General Specifications',
    status: 'active',
    example: '9521234567899',
    verified: true
  }, {
    slug: 'ean-8',
    name: 'EAN-8',
    dimension: '1D',
    data: 'Digits 0–9',
    length: '8 digits',
    check: {
      label: 'GS1 mod-10',
      method: 'gs1-mod10'
    },
    groups: ['retail', 'linear'],
    standard: 'ISO/IEC 15420:2025, GS1 General Specifications',
    status: 'active',
    example: '95212340',
    verified: true
  }, {
    slug: 'isbn',
    name: 'ISBN',
    dimension: '1D',
    data: 'Digits 0–9',
    length: '13 digits, starting 978 or 979',
    check: {
      label: 'GS1 mod-10 (ISBN-10: mod-11)',
      method: 'gs1-mod10'
    },
    groups: ['retail', 'linear'],
    standard: 'ISO 2108, encoded as EAN-13',
    status: 'active',
    example: '9780306406157',
    verified: true
  }, {
    slug: 'issn',
    name: 'ISSN',
    dimension: '1D',
    data: 'Digits 0–9',
    length: '13 digits, starting 977, often with a 2-digit add-on',
    check: {
      label: 'GS1 mod-10 (the ISSN itself: mod-11)',
      method: 'gs1-mod10'
    },
    groups: ['retail', 'linear'],
    standard: 'ISO 3297, encoded as EAN-13',
    status: 'active',
    example: '9771234567003',
    verified: true
  }, {
    slug: 'gs1-databar',
    name: 'GS1 DataBar',
    dimension: '1D',
    data: 'A GTIN; Expanded adds GS1 data such as weight and expiry',
    length: '14 digits; Expanded up to 74 digits or 41 letters',
    check: {
      label: 'Built-in check, plus the GTIN check digit',
      method: null
    },
    groups: ['retail', 'gs1', 'linear'],
    standard: 'ISO/IEC 24724',
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'gs1-composite',
    name: 'GS1 Composite',
    dimension: '1D with a 2D component',
    data: 'GS1 Application Identifier element strings',
    length: 'Up to 56, 338 or 2,361 digits in the 2D part',
    check: {
      label: 'Each component has its own',
      method: null
    },
    groups: ['gs1'],
    standard: 'ISO/IEC 24723',
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'itf-14',
    name: 'ITF-14',
    dimension: '1D',
    data: 'Digits 0–9',
    length: '14 digits',
    check: {
      label: 'GS1 mod-10',
      method: 'gs1-mod10'
    },
    groups: ['logistics', 'linear'],
    standard: 'ISO/IEC 16390, GS1 General Specifications',
    status: 'active',
    example: '19521234567896',
    verified: true
  }, {
    slug: 'code-128',
    name: 'Code 128',
    dimension: '1D',
    data: 'All 128 ASCII characters',
    length: 'Variable',
    check: {
      label: 'Mod-103 check character',
      method: null
    },
    groups: ['linear'],
    standard: 'ISO/IEC 15417',
    status: 'active',
    example: null,
    verified: true
  }, {
    slug: 'gs1-128',
    name: 'GS1-128',
    dimension: '1D',
    data: 'GS1 Application Identifier element strings',
    length: 'Up to 48 characters',
    check: {
      label: 'Mod-103 check character, plus mod-10 inside GTINs and SSCCs',
      method: null
    },
    groups: ['logistics', 'gs1', 'linear'],
    standard: 'ISO/IEC 15417, GS1 General Specifications',
    status: 'active',
    example: null,
    verified: true
  }, {
    slug: 'code-39',
    name: 'Code 39',
    dimension: '1D',
    data: 'A–Z, 0–9 and - . space $ / + %',
    length: 'Variable',
    check: {
      label: 'Optional mod-43',
      method: null
    },
    groups: ['linear'],
    standard: 'ISO/IEC 16388',
    status: 'active',
    example: null,
    verified: true
  }, {
    slug: 'interleaved-2-of-5',
    name: 'Interleaved 2 of 5',
    dimension: '1D',
    data: 'Digits 0–9',
    length: 'Even number of digits',
    check: {
      label: 'Optional',
      method: null
    },
    groups: ['linear'],
    standard: 'ISO/IEC 16390',
    status: 'active',
    example: null,
    verified: true
  }, {
    slug: 'code-93',
    name: 'Code 93',
    dimension: '1D',
    data: 'A–Z, 0–9 and - . space $ / + %, plus shift pairs for the rest of ASCII',
    length: 'Variable',
    check: {
      label: 'Two check characters (C and K)',
      method: null
    },
    groups: ['linear'],
    standard: null,
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'codabar',
    name: 'Codabar',
    dimension: '1D',
    data: 'Digits 0–9 and - $ : / . +',
    length: 'Variable',
    check: {
      label: 'None required',
      method: null
    },
    groups: ['linear'],
    standard: null,
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'code-11',
    name: 'Code 11',
    dimension: '1D',
    data: 'Digits 0–9 and -',
    length: 'Variable',
    check: {
      label: 'One or two check characters',
      method: null
    },
    groups: ['linear'],
    standard: null,
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'msi-plessey',
    name: 'MSI Plessey',
    dimension: '1D',
    data: 'Digits 0–9',
    length: 'Variable',
    check: {
      label: 'Mod-10 or mod-11, sometimes two',
      method: null
    },
    groups: ['linear'],
    standard: null,
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'industrial-2-of-5',
    name: 'Industrial 2 of 5',
    dimension: '1D',
    data: 'Digits 0–9',
    length: 'Variable',
    check: {
      label: 'None required',
      method: null
    },
    groups: ['linear'],
    standard: null,
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'matrix-2-of-5',
    name: 'Matrix 2 of 5',
    dimension: '1D',
    data: 'Digits 0–9',
    length: 'Variable',
    check: {
      label: 'None required',
      method: null
    },
    groups: ['linear'],
    standard: null,
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'qr-code',
    name: 'QR Code',
    dimension: '2D',
    data: 'Any text or binary',
    length: 'Up to 7,089 digits or 2,953 bytes',
    check: {
      label: 'Reed–Solomon, levels L, M, Q and H',
      method: null
    },
    groups: ['retail', 'matrix', 'gs1'],
    groupWhen: {
      retail: 'with a GTIN'
    },
    standard: 'ISO/IEC 18004',
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'datamatrix',
    name: 'Data Matrix',
    dimension: '2D',
    data: 'Any text or binary',
    length: 'Up to 3,116 digits or 1,556 bytes',
    check: {
      label: 'Reed–Solomon, fixed by size',
      method: null
    },
    groups: ['retail', 'matrix', 'gs1'],
    groupWhen: {
      retail: 'with a GTIN'
    },
    standard: 'ISO/IEC 16022',
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'pdf417',
    name: 'PDF417',
    dimension: '2D (stacked)',
    data: 'Any text or binary',
    length: 'Up to about 2,710 digits or 1,108 bytes',
    check: {
      label: 'Reed–Solomon, levels 0 to 8',
      method: null
    },
    groups: ['matrix', 'id'],
    standard: 'ISO/IEC 15438',
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'aztec',
    name: 'Aztec',
    dimension: '2D',
    data: 'Any text or binary',
    length: 'Up to 3,832 digits or 1,914 bytes',
    check: {
      label: 'Reed–Solomon, 5% to 95%',
      method: null
    },
    groups: ['matrix'],
    standard: 'ISO/IEC 24778',
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'micro-qr',
    name: 'Micro QR Code',
    dimension: '2D',
    data: 'Any text or binary',
    length: 'Up to 35 digits or 15 bytes',
    check: {
      label: 'Reed–Solomon, levels L, M and Q',
      method: null
    },
    groups: ['matrix'],
    standard: 'ISO/IEC 18004',
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'micro-pdf417',
    name: 'MicroPDF417',
    dimension: '2D (stacked)',
    data: 'Any text or binary',
    length: null,
    check: {
      label: 'Reed–Solomon, fixed by size',
      method: null
    },
    groups: ['matrix'],
    standard: 'ISO/IEC 24728',
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'maxicode',
    name: 'MaxiCode',
    dimension: '2D',
    data: 'Any text; structured carrier messages',
    length: 'About 93 characters, in a fixed 1-inch square',
    check: {
      label: 'Reed–Solomon, set by the mode',
      method: null
    },
    groups: ['matrix', 'logistics'],
    standard: 'ISO/IEC 16023',
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'han-xin',
    name: 'Han Xin',
    dimension: '2D',
    data: 'Any text or binary, including Chinese characters',
    length: '23×23 to 189×189 modules',
    check: {
      label: 'Reed–Solomon, four levels',
      method: null
    },
    groups: ['matrix'],
    standard: 'ISO/IEC 20830',
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'grid-matrix',
    name: 'Grid Matrix',
    dimension: '2D',
    data: 'Any text or binary, including Chinese characters',
    length: '18×18 to 162×162 modules',
    check: {
      label: 'Five levels, 10% to 50%',
      method: null
    },
    groups: ['matrix'],
    standard: 'AIMD014',
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'usps-intelligent-mail',
    name: 'USPS Intelligent Mail',
    dimension: '4-state',
    data: 'Digits 0–9',
    length: 'A 20-digit tracking code and a routing code of 0, 5, 9 or 11 digits',
    check: {
      label: 'Built into the encoding',
      method: null
    },
    groups: ['postal'],
    standard: 'USPS-B-3200',
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'postnet',
    name: 'POSTNET',
    dimension: '2-state (bar height)',
    data: 'Digits 0–9',
    length: '5, 9 or 11 digits, plus a correction digit (32, 52 or 62 bars)',
    check: {
      label: 'Mod-10 correction digit',
      method: null
    },
    groups: ['postal'],
    standard: 'USPS Domestic Mail Manual (archived)',
    status: 'retired',
    example: null,
    verified: false
  }, {
    slug: 'planet',
    name: 'PLANET',
    dimension: '2-state (bar height)',
    data: 'Digits 0–9',
    length: '12 or 14 digits, including a check digit',
    check: {
      label: 'Check digit',
      method: null
    },
    groups: ['postal'],
    standard: 'USPS Domestic Mail Manual (archived)',
    status: 'retired',
    example: null,
    verified: false
  }, {
    slug: 'royal-mail-4-state',
    name: 'Royal Mail 4-State (RM4SCC)',
    dimension: '4-state',
    data: 'A–Z, 0–9',
    length: 'A postcode and delivery point suffix',
    check: {
      label: 'Checksum character',
      method: null
    },
    groups: ['postal'],
    standard: 'Royal Mail',
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'mailmark',
    name: 'Royal Mail Mailmark',
    dimension: '4-state and 2D',
    data: 'Uppercase letters, digits and space',
    length: '22 or 26 characters (4-state); 51, 70 or 90 (2D)',
    check: {
      label: 'At least 25% error correction',
      method: null
    },
    groups: ['postal'],
    standard: 'Royal Mail Mailmark barcode definition',
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'australia-post',
    name: 'Australia Post 4-State',
    dimension: '4-state',
    data: 'A delivery point identifier, plus optional customer information',
    length: '37, 52 or 67 bars',
    check: {
      label: 'Reed–Solomon',
      method: null
    },
    groups: ['postal'],
    standard: 'Australia Post Customer Barcoding Technical Specifications',
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'japan-post',
    name: 'Japan Post',
    dimension: '4-state',
    data: 'Digits, hyphens and letters',
    length: 'A 7-digit postal code and a 13-character address number',
    check: {
      label: 'Mod-19 check digit',
      method: null
    },
    groups: ['postal'],
    standard: 'Japan Post',
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'kix',
    name: 'KIX',
    dimension: '4-state',
    data: 'A–Z, 0–9',
    length: 'A postcode, house number and optional addition',
    check: {
      label: 'None',
      method: null
    },
    groups: ['postal'],
    standard: 'PostNL',
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'korea-post',
    name: 'Korea Post',
    dimension: '1D (bar position)',
    data: 'Digits 0–9',
    length: '6 digits plus a check digit',
    check: {
      label: 'Modified mod-10 check digit',
      method: null
    },
    groups: ['postal'],
    standard: null,
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'china-post-2-of-5',
    name: 'China Post 2 of 5',
    dimension: '1D',
    data: 'Digits 0–9',
    length: null,
    check: null,
    groups: ['postal'],
    standard: null,
    status: 'active',
    example: null,
    verified: false
  }, {
    slug: 'mrz',
    name: 'MRZ (machine-readable zone)',
    path: '/reference/documents/mrz',
    dimension: 'Printed text (OCR-B)',
    data: 'A–Z, 0–9 and <',
    length: '2 or 3 lines of 30, 36 or 44 characters',
    check: {
      label: 'Mod-10 with weights 7, 3, 1 on each field',
      method: 'mrz-td3'
    },
    groups: ['id'],
    standard: 'ICAO Doc 9303',
    status: 'active',
    example: 'L898902C36UTO7408122F1204159ZE184226B<<<<<10',
    verified: false
  }];
  const READERS = [{
    key: 'camera',
    name: 'Camera',
    detail: null,
    reads: ['upc-a', 'upc-e', 'ean-13', 'ean-8', 'isbn', 'issn', 'gs1-databar', 'itf-14', 'interleaved-2-of-5', 'code-128', 'code-39', 'code-93', 'codabar', 'msi-plessey', 'qr-code', 'micro-qr', 'datamatrix', 'pdf417', 'micro-pdf417', 'aztec', 'mailmark'],
    unknown: ['gs1-128', 'mrz'],
    notes: {
      'upc-a': 'as EAN-13 with a leading 0',
      isbn: 'as EAN-13',
      issn: 'as EAN-13, without add-ons',
      mailmark: 'the 2D form only, as Data Matrix'
    }
  }, {
    key: 'series-5',
    name: '5 series',
    detail: 'barcodes',
    reads: [],
    unknown: ['upc-a', 'upc-e', 'ean-13', 'ean-8', 'isbn', 'issn', 'gs1-databar', 'gs1-composite', 'itf-14', 'interleaved-2-of-5', 'code-128', 'gs1-128', 'code-39', 'code-93', 'codabar', 'code-11', 'msi-plessey', 'industrial-2-of-5', 'matrix-2-of-5', 'qr-code', 'micro-qr', 'datamatrix', 'pdf417', 'micro-pdf417', 'aztec', 'maxicode', 'han-xin', 'grid-matrix', 'usps-intelligent-mail', 'postnet', 'planet', 'royal-mail-4-state', 'mailmark', 'australia-post', 'japan-post', 'kix', 'korea-post', 'china-post-2-of-5'],
    notes: {}
  }, {
    key: 'series-7',
    name: '7 series',
    detail: 'barcodes + printed text',
    reads: ['upc-a', 'upc-e', 'ean-13', 'ean-8', 'isbn', 'issn', 'gs1-databar', 'gs1-composite', 'itf-14', 'interleaved-2-of-5', 'code-128', 'gs1-128', 'code-39', 'code-93', 'codabar', 'code-11', 'msi-plessey', 'industrial-2-of-5', 'matrix-2-of-5', 'qr-code', 'micro-qr', 'datamatrix', 'pdf417', 'micro-pdf417', 'aztec', 'maxicode', 'han-xin', 'grid-matrix', 'usps-intelligent-mail', 'postnet', 'planet', 'royal-mail-4-state', 'mailmark', 'australia-post', 'japan-post', 'kix', 'korea-post', 'china-post-2-of-5', 'mrz'],
    unknown: [],
    notes: {}
  }];
  const findType = slug => BARCODE_TYPES.find(t => t.slug === slug);
  const findGroup = key => BARCODE_GROUPS.find(g => g.key === key);
  const href = t => t.path || `/reference/barcode-types/${t.slug}`;
  const readerName = r => r.detail ? `${r.name} (${r.detail})` : r.name;
  const support = (r, slug) => {
    if (r.reads.includes(slug)) return {
      text: 'Yes',
      note: r.notes[slug]
    };
    if (r.unknown.includes(slug)) return {
      text: 'TBC'
    };
    return {
      text: 'No'
    };
  };
  const SupportCell = ({r, slug}) => {
    const {text, note} = support(r, slug);
    return <td style={text === 'TBC' ? muted : undefined}>
        {text}
        {note && <span style={muted}>, {note}</span>}
      </td>;
  };
  const muted = {
    opacity: 0.6
  };
  const nums = {
    fontVariantNumeric: 'tabular-nums'
  };
  const Facts = ({type}) => {
    const t = findType(type);
    if (!t) return null;
    const groups = t.groups.map((key, i) => {
      const g = findGroup(key);
      return <span key={key}>
          {i > 0 && ', '}
          <a href={`/reference/barcode-groups#${g.anchor}`}>{g.name}</a>
          {t.groupWhen && t.groupWhen[key] && ` (${t.groupWhen[key]})`}
        </span>;
    });
    const rows = [['Kind', t.dimension], ['Encodes', t.data], ['Length', t.length], ['Check', t.check && t.check.label], ['Groups', groups], ['Standard', t.standard], ['Status', t.status === 'retired' ? 'Retired' : 'In use']];
    return <table>
        <caption className="sr-only">{t.name} at a glance</caption>
        <tbody>
          {rows.map(([label, value]) => <tr key={label}>
              <th scope="row" className="font-medium">{label}</th>
              <td>{value == null ? <span style={muted}>TBC</span> : value}</td>
            </tr>)}
        </tbody>
      </table>;
  };
  const SupportMatrix = ({type, types}) => {
    if (type) {
      const t = findType(type);
      if (!t) return null;
      return <table>
            <thead>
              <tr>
                <th scope="col">Reader</th>
                <th scope="col">Reads {t.name}</th>
              </tr>
            </thead>
            <tbody>
              {READERS.map(r => <tr key={r.key}>
                  <th scope="row" className="font-medium">{readerName(r)}</th>
                  <SupportCell r={r} slug={t.slug} />
                </tr>)}
            </tbody>
          </table>;
    }
    const rows = types ? types.split(',').map(x => findType(x.trim())).filter(Boolean) : BARCODE_TYPES;
    return <div className="overflow-x-auto">
        <table>
          <thead>
            <tr>
              <th scope="col">Barcode type</th>
              {READERS.map(r => <th scope="col" key={r.key}>{readerName(r)}</th>)}
            </tr>
          </thead>
          <tbody>
            {rows.map(t => <tr key={t.slug}>
                <th scope="row" className="font-medium"><a href={href(t)}>{t.name}</a></th>
                {READERS.map(r => <SupportCell key={r.key} r={r} slug={t.slug} />)}
              </tr>)}
          </tbody>
        </table>
      </div>;
  };
  const GroupMatrix = () => <div className="overflow-x-auto">
      <table>
        <thead>
          <tr>
            <th scope="col">Barcode type</th>
            {BARCODE_GROUPS.map(g => <th scope="col" key={g.key}><a href={`#${g.anchor}`}>{g.name}</a></th>)}
          </tr>
        </thead>
        <tbody>
          {BARCODE_TYPES.map(t => <tr key={t.slug}>
              <th scope="row" className="font-medium">
                <a href={href(t)}>{t.name}</a>
              </th>
              {BARCODE_GROUPS.map(g => <td key={g.key} className="text-center">
                  {t.groups.includes(g.key) ? <>
                      <span aria-hidden="true">✓</span>
                      <span className="sr-only">Yes</span>
                      {t.groupWhen && t.groupWhen[g.key] && <span className="text-sm" style={muted}> {t.groupWhen[g.key]}</span>}
                    </> : <span className="sr-only">No</span>}
                </td>)}
            </tr>)}
        </tbody>
      </table>
    </div>;
  const CheckDigitSteps = ({value}) => {
    const digits = String(value).split('').map(Number);
    const data = digits.slice(0, -1);
    const given = digits[digits.length - 1];
    const weights = data.map((_, i) => (data.length - i) % 2 === 1 ? 3 : 1);
    const products = data.map((d, i) => d * weights[i]);
    const sum = products.reduce((a, b) => a + b, 0);
    const next = Math.ceil(sum / 10) * 10;
    const check = next - sum;
    const row = (label, cells, strong) => <tr>
        <th scope="row" className="font-medium whitespace-nowrap">{label}</th>
        {cells.map((c, i) => <td key={i} className={strong ? 'text-center font-semibold' : 'text-center'} style={nums}>{c}</td>)}
      </tr>;
    return <div>
        <div className="overflow-x-auto">
          <table>
            <caption className="sr-only">Check digit calculation for {value}</caption>
            <tbody>
              {row('Digit', data)}
              {row('× Weight', weights)}
              {row('= Product', products, true)}
            </tbody>
          </table>
        </div>
        <p>
          Sum of products: <strong style={nums}>{sum}</strong>. Round up to the next
          multiple of 10: <strong style={nums}>{next}</strong>. Check digit:{' '}
          <span style={nums}>{next} − {sum} = </span>
          <strong style={nums}>{check}</strong>
          {check === given ? `, which matches the last digit of ${value}.` : `, but ${value} ends in ${given}: this number is not valid.`}
        </p>
      </div>;
  };
  const EAN_L = ['0001101', '0011001', '0010011', '0111101', '0100011', '0110001', '0101111', '0111011', '0110111', '0001011'];
  const EAN_R = EAN_L.map(p => p.replace(/./g, c => c === '0' ? '1' : '0'));
  const EAN_G = EAN_R.map(p => p.split('').reverse().join(''));
  const EAN_PARITY = ['LLLLLL', 'LLGLGG', 'LLGGLG', 'LLGGGL', 'LGLLGG', 'LGGLLG', 'LGGGLL', 'LGLGLG', 'LGLGGL', 'LGGLGL'];
  const leftChar = k => 3 + 7 * k + 3.5;
  const rightChar = (k, halfWidth) => 3 + halfWidth + 5 + 7 * k + 3.5;
  const ANATOMY = {
    'ean-13': {
      length: 13,
      quiet: [11, 7],
      encode: d => {
        const parity = EAN_PARITY[d[0]];
        const left = d.slice(1, 7).map((n, i) => (parity[i] === 'L' ? EAN_L : EAN_G)[n]).join('');
        const right = d.slice(7).map(n => EAN_R[n]).join('');
        return '101' + left + '01010' + right + '101';
      },
      hri: i => i === 0 ? -6 : i <= 6 ? leftChar(i - 1) : rightChar(i - 7, 42),
      number: [[0, 3, 'GS1 prefix', 'Which national GS1 office issued the company prefix. Not the country the product was made in.'], [3, 12, 'Company prefix and item reference', 'The brand owner’s GS1 company prefix followed by its number for this item. Where one ends and the other begins depends on the prefix length, which you can’t tell from the digits alone.'], [12, 13, 'Check digit', 'Calculated from the other 12 digits with GS1 mod-10.']],
      leftNote: 'Six digits, each seven modules wide. Each digit is drawn in one of two patterns, and the combination of patterns encodes the first digit, which has no bars of its own.'
    },
    'upc-a': {
      length: 12,
      quiet: [9, 9],
      encode: d => '101' + d.slice(0, 6).map(n => EAN_L[n]).join('') + '01010' + d.slice(6).map(n => EAN_R[n]).join('') + '101',
      hri: i => i === 0 ? -5 : i <= 5 ? leftChar(i) : i <= 10 ? rightChar(i - 6, 42) : 95 + 5,
      extended: [[3, 10], [85, 92]],
      number: [[0, 11, 'Company prefix and item reference', 'The brand owner’s GS1 company prefix followed by its number for this item.'], [11, 12, 'Check digit', 'Calculated from the other 11 digits with GS1 mod-10.']],
      leftNote: 'Six digits, each seven modules wide.'
    },
    'ean-8': {
      length: 8,
      quiet: [7, 7],
      encode: d => '101' + d.slice(0, 4).map(n => EAN_L[n]).join('') + '01010' + d.slice(4).map(n => EAN_R[n]).join('') + '101',
      hri: i => i <= 3 ? leftChar(i) : rightChar(i - 4, 28),
      number: [[0, 3, 'GS1-8 prefix', 'Which national GS1 office issued the number.'], [3, 7, 'Item reference', 'Assigned by that GS1 office for this item.'], [7, 8, 'Check digit', 'Calculated from the other 7 digits with GS1 mod-10.']],
      leftNote: 'Four digits, each seven modules wide.'
    },
    'upc-e': {
      length: 8,
      quiet: [9, 7],
      encode: d => {
        const forZero = ['GGGLLL', 'GGLGLL', 'GGLLGL', 'GGLLLG', 'GLGGLL', 'GLLGGL', 'GLLLGG', 'GLGLGL', 'GLGLLG', 'GLLGLG'][d[7]];
        const parity = d[0] === 0 ? forZero : forZero.replace(/./g, c => c === 'G' ? 'L' : 'G');
        return '101' + d.slice(1, 7).map((n, i) => (parity[i] === 'L' ? EAN_L : EAN_G)[n]).join('') + '010101';
      },
      hri: i => i === 0 ? -5 : i <= 6 ? leftChar(i - 1) : 51 + 4,
      guards: () => [[0, 3], [45, 51]],
      structure: () => [['Start guard', 0, 3, 'Three modules (bar, space, bar) that tell the scanner where the symbol starts and how wide one module is.'], ['Six digits', 3, 45, 'Each digit is seven modules wide and drawn in one of two patterns. The combination of patterns encodes the number system and the check digit, which have no bars of their own.'], ['End guard', 45, 51, 'Six modules that mark the end of the symbol.']],
      number: [[0, 1, 'Number system', 'Always 0 or 1.'], [1, 7, 'Zero-suppressed digits', 'The company prefix and item reference with their zeros removed. The last of the six says where the zeros go back.'], [7, 8, 'Check digit', 'The check digit of the full 12-digit UPC-A.']]
    }
  };
  ANATOMY.isbn = {
    ...ANATOMY['ean-13'],
    number: [[0, 3, 'Prefix', '978 or 979, which mark the number as a book.'], [3, 12, 'Registration group, registrant and publication', 'The language area or country, the publisher, and the edition. Each part varies in length, which is what the hyphens in a printed ISBN show.'], [12, 13, 'Check digit', 'Calculated from the other 12 digits with GS1 mod-10.']]
  };
  ANATOMY.issn = {
    ...ANATOMY['ean-13'],
    number: [[0, 3, 'Prefix', '977, which marks the number as a serial publication.'], [3, 10, 'ISSN', 'The first seven digits of the ISSN. Its own check digit is left out.'], [10, 12, 'Variant', 'Usually 00. Publishers change it for a special issue or a price change.'], [12, 13, 'Check digit', 'Calculated from the other 12 digits with GS1 mod-10.']]
  };
  const Anatomy = ({type, value, plain}) => {
    const spec = ANATOMY[type];
    const digits = String(value).split('').map(Number);
    if (!spec || digits.length !== spec.length || digits.some(isNaN)) {
      return <p style={muted}>Can’t draw {type} for “{value}”.</p>;
    }
    const modules = spec.encode(digits);
    const n = modules.length;
    const half = (n - 11) / 2;
    const guards = spec.guards ? spec.guards() : [[0, 3], [3 + half, 8 + half], [n - 3, n]];
    const tall = [...guards, ...spec.extended || []];
    const isTall = m => tall.some(([a, b]) => m >= a && m < b);
    const M = 4;
    const [qL, qR] = spec.quiet;
    const x = m => (qL + m) * M;
    const width = (qL + n + qR) * M;
    const labelTop = plain ? 0 : 30, barTop = labelTop + 6, barH = 70, guardH = 76, hriY = barTop + guardH + 4, labelBottom = hriY + 6;
    const bottomBracket = labelBottom + 8, height = plain ? labelBottom : bottomBracket + 22;
    const bars = [];
    for (let m = 0; m < n; m++) {
      if (modules[m] !== '1') continue;
      let end = m;
      while (modules[end + 1] === '1') end++;
      bars.push(<rect key={m} x={x(m)} y={barTop} width={(end - m + 1) * M} height={isTall(m) ? guardH : barH} />);
      m = end;
    }
    const structure = spec.structure ? spec.structure() : [['Start guard', 0, 3, 'Three modules (bar, space, bar) that tell the scanner where the symbol starts and how wide one module is.'], ['Left half', 3, 3 + half, spec.leftNote], ['Center guard', 3 + half, 8 + half, 'Five modules that separate the two halves. Scanners decode each half on its own, then join them.'], ['Right half', 8 + half, n - 3, 'The remaining digits, each seven modules wide, always drawn from the same set of patterns.'], ['End guard', n - 3, n, 'Three modules that mark the end of the symbol.']];
    const numberSegs = spec.number.map(([a, b, name, meaning]) => [name, spec.hri(a) - 3.5, spec.hri(b - 1) + 3.5, meaning]);
    const legend = [...structure, ...numberSegs];
    const bracket = (key, x1, x2, y, up) => {
      const t = up ? y - 4 : y + 4;
      return <path key={key} d={`M${x1 + 1} ${t} V${y} H${x2 - 1} V${t}`} fill="none" stroke="currentColor" strokeWidth="1" />;
    };
    const marker = (key, label, cx, y) => <text key={key} x={cx} y={y} textAnchor="middle" fontSize="10" fontWeight="600" fill="currentColor">{label}</text>;
    const label = <>
        {}
        <rect x="0" y={labelTop} width={width} height={labelBottom - labelTop} fill="#ffffff" rx={plain ? 0 : 4} />
        <g fill="#111214">
          {bars}
          {digits.map((d, i) => <text key={i} x={x(spec.hri(i))} y={hriY} textAnchor="middle" fontSize="13" fontFamily="ui-monospace, SFMono-Regular, Menlo, monospace">{d}</text>)}
        </g>
      </>;
    if (plain) {
      return <figure className="not-prose my-6">
          <svg viewBox={`0 0 ${width} ${height}`} role="img" aria-label={`${type.toUpperCase()} barcode for ${value}`} style={{
        width: '100%',
        maxWidth: 360,
        height: 'auto'
      }}>
            {label}
          </svg>
        </figure>;
    }
    return <figure className="not-prose my-6">
        <svg viewBox={`0 0 ${width} ${height}`} role="img" aria-labelledby={`anatomy-${type}-title`} style={{
      width: '100%',
      height: 'auto'
    }}>
          <title id={`anatomy-${type}-title`}>{`Annotated ${type.toUpperCase()} barcode for ${value}`}</title>
          {structure.map(([, a, b], i) => <g key={`s${i}`}>
              {bracket(`sb${i}`, x(a), x(b), 22, false)}
              {marker(`sm${i}`, i + 1, (x(a) + x(b)) / 2, 16)}
            </g>)}
          {label}
          {numberSegs.map(([, a, b], i) => <g key={`n${i}`}>
              {bracket(`nb${i}`, x(a), x(b), bottomBracket, true)}
              {marker(`nm${i}`, structure.length + i + 1, (x(a) + x(b)) / 2, bottomBracket + 14)}
            </g>)}
        </svg>
        <figcaption className="mt-4">
          <ol className="list-decimal pl-5 text-sm">
            {legend.map(([name, , , meaning]) => <li key={name}><strong>{name}.</strong> {meaning}</li>)}
          </ol>
        </figcaption>
      </figure>;
  };
  const C128 = [[2, 1, 2, 2, 2, 2], [2, 2, 2, 1, 2, 2], [2, 2, 2, 2, 2, 1], [1, 2, 1, 2, 2, 3], [1, 2, 1, 3, 2, 2], [1, 3, 1, 2, 2, 2], [1, 2, 2, 2, 1, 3], [1, 2, 2, 3, 1, 2], [1, 3, 2, 2, 1, 2], [2, 2, 1, 2, 1, 3], [2, 2, 1, 3, 1, 2], [2, 3, 1, 2, 1, 2], [1, 1, 2, 2, 3, 2], [1, 2, 2, 1, 3, 2], [1, 2, 2, 2, 3, 1], [1, 1, 3, 2, 2, 2], [1, 2, 3, 1, 2, 2], [1, 2, 3, 2, 2, 1], [2, 2, 3, 2, 1, 1], [2, 2, 1, 1, 3, 2], [2, 2, 1, 2, 3, 1], [2, 1, 3, 2, 1, 2], [2, 2, 3, 1, 1, 2], [3, 1, 2, 1, 3, 1], [3, 1, 1, 2, 2, 2], [3, 2, 1, 1, 2, 2], [3, 2, 1, 2, 2, 1], [3, 1, 2, 2, 1, 2], [3, 2, 2, 1, 1, 2], [3, 2, 2, 2, 1, 1], [2, 1, 2, 1, 2, 3], [2, 1, 2, 3, 2, 1], [2, 3, 2, 1, 2, 1], [1, 1, 1, 3, 2, 3], [1, 3, 1, 1, 2, 3], [1, 3, 1, 3, 2, 1], [1, 1, 2, 3, 1, 3], [1, 3, 2, 1, 1, 3], [1, 3, 2, 3, 1, 1], [2, 1, 1, 3, 1, 3], [2, 3, 1, 1, 1, 3], [2, 3, 1, 3, 1, 1], [1, 1, 2, 1, 3, 3], [1, 1, 2, 3, 3, 1], [1, 3, 2, 1, 3, 1], [1, 1, 3, 1, 2, 3], [1, 1, 3, 3, 2, 1], [1, 3, 3, 1, 2, 1], [3, 1, 3, 1, 2, 1], [2, 1, 1, 3, 3, 1], [2, 3, 1, 1, 3, 1], [2, 1, 3, 1, 1, 3], [2, 1, 3, 3, 1, 1], [2, 1, 3, 1, 3, 1], [3, 1, 1, 1, 2, 3], [3, 1, 1, 3, 2, 1], [3, 3, 1, 1, 2, 1], [3, 1, 2, 1, 1, 3], [3, 1, 2, 3, 1, 1], [3, 3, 2, 1, 1, 1], [3, 1, 4, 1, 1, 1], [2, 2, 1, 4, 1, 1], [4, 3, 1, 1, 1, 1], [1, 1, 1, 2, 2, 4], [1, 1, 1, 4, 2, 2], [1, 2, 1, 1, 2, 4], [1, 2, 1, 4, 2, 1], [1, 4, 1, 1, 2, 2], [1, 4, 1, 2, 2, 1], [1, 1, 2, 2, 1, 4], [1, 1, 2, 4, 1, 2], [1, 2, 2, 1, 1, 4], [1, 2, 2, 4, 1, 1], [1, 4, 2, 1, 1, 2], [1, 4, 2, 2, 1, 1], [2, 4, 1, 2, 1, 1], [2, 2, 1, 1, 1, 4], [4, 1, 3, 1, 1, 1], [2, 4, 1, 1, 1, 2], [1, 3, 4, 1, 1, 1], [1, 1, 1, 2, 4, 2], [1, 2, 1, 1, 4, 2], [1, 2, 1, 2, 4, 1], [1, 1, 4, 2, 1, 2], [1, 2, 4, 1, 1, 2], [1, 2, 4, 2, 1, 1], [4, 1, 1, 2, 1, 2], [4, 2, 1, 1, 1, 2], [4, 2, 1, 2, 1, 1], [2, 1, 2, 1, 4, 1], [2, 1, 4, 1, 2, 1], [4, 1, 2, 1, 2, 1], [1, 1, 1, 1, 4, 3], [1, 1, 1, 3, 4, 1], [1, 3, 1, 1, 4, 1], [1, 1, 4, 1, 1, 3], [1, 1, 4, 3, 1, 1], [4, 1, 1, 1, 1, 3], [4, 1, 1, 3, 1, 1], [1, 1, 3, 1, 4, 1], [1, 1, 4, 1, 3, 1], [3, 1, 1, 1, 4, 1], [4, 1, 1, 1, 3, 1], [2, 1, 1, 4, 1, 2], [2, 1, 1, 2, 1, 4], [2, 1, 1, 2, 3, 2], [2, 3, 3, 1, 1, 1, 2]];
  const C39_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%';
  const C39 = [0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00d, 0x10c, 0x04c, 0x01c, 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, 0x181, 0x0c1, 0x1c0, 0x091, 0x190, 0x0d0, 0x085, 0x184, 0x0c4, 0x0a8, 0x0a2, 0x08a, 0x02a];
  const C39_STAR = 0x094;
  const I25 = ['NNWWN', 'WNNNW', 'NWNNW', 'WWNNN', 'NNWNW', 'WNWNN', 'NWWNN', 'NNNWW', 'WNNWN', 'NWNWN'];
  const C93 = [0x114, 0x148, 0x144, 0x142, 0x128, 0x124, 0x122, 0x150, 0x112, 0x10a, 0x1a8, 0x1a4, 0x1a2, 0x194, 0x192, 0x18a, 0x168, 0x164, 0x162, 0x134, 0x11a, 0x158, 0x14c, 0x146, 0x12c, 0x116, 0x1b4, 0x1b2, 0x1ac, 0x1a6, 0x196, 0x19a, 0x16c, 0x166, 0x136, 0x13a, 0x12e, 0x1d4, 0x1d2, 0x1ca, 0x16e, 0x176, 0x1ae, 0x126, 0x1da, 0x1d6, 0x132, 0x15e];
  const code93 = text => {
    const values = [...text].map(c => C39_CHARS.indexOf(c));
    const weighted = (vs, max) => vs.reduceRight((acc, v, i) => acc + v * ((vs.length - 1 - i) % max + 1), 0) % 47;
    const c = weighted(values, 20);
    const k = weighted([...values, c], 15);
    const modules = [47, ...values, c, k, 47].map(v => C93[v].toString(2).padStart(9, '0')).join('') + '1';
    const widths = [];
    for (let i = 0; i < modules.length; ) {
      let j = i;
      while (modules[j] === modules[i]) j++;
      widths.push(j - i);
      i = j;
    }
    const n = values.length;
    const name = v => C39_CHARS[v] || `value ${v}`;
    return {
      widths,
      hri: text,
      segments: [['Start character', 0, 9, 'Marks the start. Scanners don’t send it.'], ['Data', 9, 9 * (n + 1), 'Each character is 9 modules: three bars and three spaces, each 1 to 4 modules wide.'], ['Check character C', 9 * (n + 1), 9 * (n + 2), `Mod-47 over the data, with weights 1 to 20. Here, ${name(c)}.`], ['Check character K', 9 * (n + 2), 9 * (n + 3), `Mod-47 over the data and C, with weights 1 to 15. Here, ${name(k)}.`], ['Stop', 9 * (n + 3), 9 * (n + 4) + 1, 'The stop character, then a single-module bar that ends the symbol.']]
    };
  };
  const code39 = text => {
    const chars = [...text];
    const check = C39_CHARS[chars.reduce((sum, c) => sum + C39_CHARS.indexOf(c), 0) % 43];
    const element = bits => Array.from({
      length: 9
    }, (_, i) => bits >> 8 - i & 1 ? 3 : 1);
    const parts = [C39_STAR, ...chars.map(c => C39[C39_CHARS.indexOf(c)]), C39[C39_CHARS.indexOf(check)], C39_STAR];
    const widths = [];
    parts.forEach((bits, i) => {
      widths.push(...element(bits));
      if (i < parts.length - 1) widths.push(1);
    });
    const char = 16;
    const n = parts.length;
    return {
      widths,
      hri: text + check,
      segments: [['Start character', 0, 15, 'An asterisk. It marks the start, and scanners don’t send it.'], ['Data', char, char * (n - 2) - 1, 'Each character is nine elements, five bars and four spaces, three of them wide. A narrow gap separates characters.'], ['Check character', char * (n - 2), char * (n - 1) - 1, `Optional. The mod-43 check for this data is ${check}.`], ['Stop character', char * (n - 1), char * n - 1, 'Another asterisk, which marks the end.']]
    };
  };
  const code128Values = (text, gs1) => {
    const digitsAt = i => {
      let n = 0;
      while ((/\d/).test(text[i + n] || '')) n++;
      return n;
    };
    let set = digitsAt(0) >= 4 ? 'C' : 'B';
    const values = [set === 'C' ? 105 : 104];
    if (gs1) values.push(102);
    for (let i = 0; i < text.length; ) {
      if (text[i] === '\x1d') {
        values.push(102);
        i += 1;
        continue;
      }
      if (set === 'C') {
        if (digitsAt(i) >= 2) {
          values.push(Number(text.slice(i, i + 2)));
          i += 2;
        } else {
          values.push(100);
          set = 'B';
        }
      } else if (digitsAt(i) >= 4 && digitsAt(i) % 2 === 0) {
        values.push(99);
        set = 'C';
      } else {
        values.push(text.charCodeAt(i) - 32);
        i += 1;
      }
    }
    return values;
  };
  const code128 = (text, gs1) => {
    const data = gs1 ? gs1Text(text) : text;
    const values = code128Values(data, gs1);
    const check = values.reduce((sum, v, i) => sum + v * (i || 1), 0) % 103;
    const widths = [...values, check, 106].flatMap(v => C128[v]);
    const head = gs1 ? 22 : 11;
    const end = values.length * 11;
    const startSet = values[0] === 105 ? 'C' : 'B';
    const startNote = startSet === 'C' ? 'The first characters are digits, packed two to a character.' : 'The first characters are text. The start code also counts toward the check.';
    return {
      widths,
      hri: text,
      segments: [[`Start code ${startSet}`, 0, 11, startNote], ...gs1 ? [['FNC1', 11, 22, 'A special character that marks the barcode as GS1-128. Scanners don’t send it as data.']] : [], ['Data', head, end, gs1 ? 'Each character is 11 modules: three bars and three spaces. Digits are packed two to a character in code set C, then a switch to code set B handles the letters.' : 'Each character is 11 modules: three bars and three spaces, each 1 to 4 modules wide.'], ['Check character', end, end + 11, `Mod-103 check, value ${check}. Scanners verify it, then drop it.`], ['Stop', end + 11, end + 24, 'Thirteen modules, ending in a final bar.']]
    };
  };
  const itf = (digits, wide = 2.5) => {
    const widths = [1, 1, 1, 1];
    for (let i = 0; i < digits.length; i += 2) {
      const bars = I25[digits[i]], spaces = I25[digits[i + 1]];
      for (let k = 0; k < 5; k++) widths.push(bars[k] === 'W' ? wide : 1, spaces[k] === 'W' ? wide : 1);
    }
    widths.push(wide, 1, 1);
    const pair = 2 * (3 + 2 * wide);
    const end = 4 + pair * (digits.length / 2);
    return {
      widths,
      hri: digits,
      segments: [['Start', 0, 4, 'Four narrow elements: bar, space, bar, space.'], ['Digit pairs', 4, end, 'Each pair of digits shares five bars and five spaces. The first digit sets which bars are wide, the second which spaces are wide.'], ['Stop', end, end + wide + 2, 'A wide bar, a narrow space and a narrow bar.']]
    };
  };
  const GS1_AI_NAMES = {
    '00': ['SSCC', 'The serial shipping container code: an 18-digit number for one pallet or parcel.'],
    '01': ['GTIN', 'The product’s 14-digit GTIN.'],
    10: ['Batch or lot', 'Up to 20 characters. Variable length, so it comes last or is followed by a separator.'],
    11: ['Production date', 'YYMMDD.'],
    15: ['Best before date', 'YYMMDD.'],
    17: ['Expiry date', 'YYMMDD.'],
    21: ['Serial number', 'Up to 20 characters.'],
    37: ['Count', 'How many trade items the unit contains.']
  };
  const LINEAR = {
    'code-39': {
      quiet: 10,
      encode: v => code39(v)
    },
    'code-93': {
      quiet: 10,
      encode: v => code93(v)
    },
    'code-128': {
      quiet: 10,
      encode: v => code128(v, false)
    },
    'gs1-128': {
      quiet: 10,
      encode: v => code128(v, true),
      numbers: hri => [...hri.matchAll(/\((\d{2,4})\)[^(]*/g)].map(m => {
        const [name, meaning] = GS1_AI_NAMES[m[1]] || [`AI ${m[1]}`, ''];
        return [m.index, m.index + m[0].length, `(${m[1]}) ${name}`, meaning];
      })
    },
    'interleaved-2-of-5': {
      quiet: 10,
      encode: v => itf(v)
    },
    'itf-14': {
      quiet: 10,
      bearer: true,
      encode: v => itf(v),
      numbers: () => [[0, 1, 'Indicator digit', 'The packaging level. 1 to 8 mean a case or other grouping of the same item.'], [1, 13, 'Item number', 'Often the first 12 digits of the item’s own GTIN-13, but not always.'], [13, 14, 'Check digit', 'GS1 mod-10, calculated over all 14 digits.']]
    }
  };
  const Linear = ({type, value, plain}) => {
    const spec = LINEAR[type];
    if (!spec || !value) return <p style={muted}>Can’t draw {type} for “{value}”.</p>;
    const {widths, hri, segments} = spec.encode(String(value));
    const numbers = spec.numbers ? spec.numbers(hri) : [];
    const total = widths.reduce((a, b) => a + b, 0);
    const q = spec.quiet;
    const M = Math.max(2, Math.min(4, 520 / (total + 2 * q)));
    const x = m => (q + m) * M;
    const width = (total + 2 * q) * M;
    const bearer = spec.bearer ? 6 : 0;
    const labelTop = plain ? 0 : 30, barTop = labelTop + 6 + bearer, barH = 70;
    const hriY = barTop + barH + bearer + 16, labelBottom = hriY + 6;
    const bottomBracket = labelBottom + 8, height = plain ? labelBottom : bottomBracket + 22;
    const slot = total / hri.length;
    const charX = i => x((i + 0.5) * slot);
    const bars = [];
    let pos = 0;
    widths.forEach((w, i) => {
      if (i % 2 === 0) bars.push(<rect key={i} x={x(pos)} y={barTop} width={w * M} height={barH} />);
      pos += w;
    });
    const label = <>
        <rect x="0" y={labelTop} width={width} height={labelBottom - labelTop} fill="#ffffff" rx={plain ? 0 : 4} />
        <g fill="#111214">
          {spec.bearer && <rect x={x(-q / 2)} y={barTop - bearer} width={(total + q) * M} height={bearer - 1} />}
          {spec.bearer && <rect x={x(-q / 2)} y={barTop + barH + 1} width={(total + q) * M} height={bearer - 1} />}
          {bars}
          {[...hri].map((c, i) => <text key={i} x={charX(i)} y={hriY} textAnchor="middle" fontSize="12" fontFamily="ui-monospace, SFMono-Regular, Menlo, monospace">{c}</text>)}
        </g>
      </>;
    const name = (findType(type) || ({
      name: type
    })).name;
    if (plain) {
      return <figure className="not-prose my-6">
          <svg viewBox={`0 0 ${width} ${height}`} role="img" aria-label={`${name} barcode for ${hri}`} style={{
        width: '100%',
        maxWidth: 480,
        height: 'auto'
      }}>
            {label}
          </svg>
        </figure>;
    }
    const bracket = (key, x1, x2, y, up) => {
      const t = up ? y - 4 : y + 4;
      return <path key={key} d={`M${x1 + 1} ${t} V${y} H${x2 - 1} V${t}`} fill="none" stroke="currentColor" strokeWidth="1" />;
    };
    const marker = (key, n, cx, y) => <text key={key} x={cx} y={y} textAnchor="middle" fontSize="10" fontWeight="600" fill="currentColor">{n}</text>;
    const numberSegs = numbers.map(([a, b, title, meaning]) => [title, charX(a) - slot * M / 2, charX(b - 1) + slot * M / 2, meaning]);
    return <figure className="not-prose my-6">
        <svg viewBox={`0 0 ${width} ${height}`} role="img" aria-labelledby={`anatomy-${type}-title`} style={{
      width: '100%',
      height: 'auto'
    }}>
          <title id={`anatomy-${type}-title`}>{`Annotated ${name} barcode for ${hri}`}</title>
          {segments.map(([, a, b], i) => <g key={`s${i}`}>
              {bracket(`sb${i}`, x(a), x(b), 22, false)}
              {marker(`sm${i}`, i + 1, (x(a) + x(b)) / 2, 16)}
            </g>)}
          {label}
          {numberSegs.map(([, a, b], i) => <g key={`n${i}`}>
              {bracket(`nb${i}`, a, b, bottomBracket, true)}
              {marker(`nm${i}`, segments.length + i + 1, (a + b) / 2, bottomBracket + 14)}
            </g>)}
        </svg>
        <figcaption className="mt-4">
          <ol className="list-decimal pl-5 text-sm">
            {[...segments, ...numberSegs].map(([title, , , meaning]) => <li key={title}><strong>{title}.</strong> {meaning}</li>)}
          </ol>
        </figcaption>
      </figure>;
  };
  const gf = poly => {
    const exp = new Array(512), log = new Array(256);
    let x = 1;
    for (let i = 0; i < 255; i++) {
      exp[i] = x;
      log[x] = i;
      x <<= 1;
      if (x & 0x100) x ^= poly;
    }
    for (let i = 255; i < 512; i++) exp[i] = exp[i - 255];
    const mul = (a, b) => a && b ? exp[log[a] + log[b]] : 0;
    const generator = (n, first) => {
      let g = [1];
      for (let i = 0; i < n; i++) {
        const next = new Array(g.length + 1).fill(0);
        g.forEach((c, j) => {
          next[j] ^= c;
          next[j + 1] ^= mul(c, exp[first + i]);
        });
        g = next;
      }
      return g.slice(1);
    };
    const remainder = (data, n, first) => {
      const g = generator(n, first);
      const rem = new Array(n).fill(0);
      for (const d of data) {
        const factor = d ^ rem.shift();
        rem.push(0);
        g.forEach((c, j) => {
          rem[j] ^= mul(c, factor);
        });
      }
      return rem;
    };
    return {
      remainder
    };
  };
  const QR_EC_PER_BLOCK = {
    L: [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
    M: [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28],
    Q: [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
    H: [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30]
  };
  const QR_BLOCKS = {
    L: [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25],
    M: [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49],
    Q: [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68],
    H: [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81]
  };
  const QR_FORMAT_EC = {
    L: 1,
    M: 0,
    Q: 3,
    H: 2
  };
  const qrRawModules = v => {
    let r = (16 * v + 128) * v + 64;
    if (v >= 2) {
      const n = Math.floor(v / 7) + 2;
      r -= (25 * n - 10) * n - 55;
      if (v >= 7) r -= 36;
    }
    return r;
  };
  const qrDataCodewords = (v, ec) => Math.floor(qrRawModules(v) / 8) - QR_EC_PER_BLOCK[ec][v] * QR_BLOCKS[ec][v];
  const qrAlignment = v => {
    if (v === 1) return [];
    const n = Math.floor(v / 7) + 2, size = v * 4 + 17;
    const step = v === 32 ? 26 : Math.ceil((v * 4 + 4) / (n * 2 - 2)) * 2;
    const out = [6];
    for (let pos = size - 7; out.length < n; pos -= step) out.splice(1, 0, pos);
    return out;
  };
  const qrMask = [(x, y) => (x + y) % 2 === 0, (x, y) => y % 2 === 0, x => x % 3 === 0, (x, y) => (x + y) % 3 === 0, (x, y) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0, (x, y) => x * y % 2 + x * y % 3 === 0, (x, y) => (x * y % 2 + x * y % 3) % 2 === 0, (x, y) => ((x + y) % 2 + x * y % 3) % 2 === 0];
  const qrPenalty = m => {
    const n = m.length;
    let p = 0;
    const lines = [];
    for (let i = 0; i < n; i++) {
      lines.push(m[i]);
      lines.push(m.map(row => row[i]));
    }
    for (const line of lines) {
      for (let i = 0; i < n; ) {
        let j = i;
        while (j < n && line[j] === line[i]) j++;
        if (j - i >= 5) p += 3 + (j - i - 5);
        i = j;
      }
      const s = line.map(b => b ? 1 : 0).join('');
      for (const pat of ['10111010000', '00001011101']) for (let i = s.indexOf(pat); i !== -1; i = s.indexOf(pat, i + 1)) p += 40;
    }
    for (let y = 0; y < n - 1; y++) for (let x = 0; x < n - 1; x++) {
      const c = m[y][x];
      if (c === m[y][x + 1] && c === m[y + 1][x] && c === m[y + 1][x + 1]) p += 3;
    }
    const dark = m.flat().filter(Boolean).length;
    p += Math.floor(Math.abs(dark * 20 - n * n * 10) / (n * n)) * 10;
    return p;
  };
  const encodeQR = (text, ec = 'M') => {
    const bytes = [...new TextEncoder().encode(text)];
    let v = 1;
    const bitsNeeded = ver => 4 + (ver < 10 ? 8 : 16) + bytes.length * 8;
    while (v <= 40 && bitsNeeded(v) > qrDataCodewords(v, ec) * 8) v++;
    if (v > 40) throw new Error('Too much data for a QR Code');
    const capacity = qrDataCodewords(v, ec);
    const bits = [];
    const put = (val, len) => {
      for (let i = len - 1; i >= 0; i--) bits.push(val >> i & 1);
    };
    put(0b0100, 4);
    put(bytes.length, v < 10 ? 8 : 16);
    bytes.forEach(b => put(b, 8));
    put(0, Math.min(4, capacity * 8 - bits.length));
    while (bits.length % 8) bits.push(0);
    const data = [];
    for (let i = 0; i < bits.length; i += 8) data.push(parseInt(bits.slice(i, i + 8).join(''), 2));
    for (let pad = 0xec; data.length < capacity; pad ^= 0xec ^ 0x11) data.push(pad);
    const rs = gf(0x11d);
    const numBlocks = QR_BLOCKS[ec][v], ecLen = QR_EC_PER_BLOCK[ec][v];
    const raw = Math.floor(qrRawModules(v) / 8);
    const shortBlocks = numBlocks - raw % numBlocks, shortLen = Math.floor(raw / numBlocks);
    const blocks = [];
    for (let i = 0, k = 0; i < numBlocks; i++) {
      const len = shortLen - ecLen + (i < shortBlocks ? 0 : 1);
      const d = data.slice(k, k + len);
      k += len;
      blocks.push({
        d,
        e: rs.remainder(d, ecLen, 0)
      });
    }
    const codewords = [];
    for (let i = 0; i <= shortLen - ecLen; i++) blocks.forEach(b => {
      if (i < b.d.length) codewords.push(b.d[i]);
    });
    for (let i = 0; i < ecLen; i++) blocks.forEach(b => codewords.push(b.e[i]));
    const size = v * 4 + 17;
    const m = Array.from({
      length: size
    }, () => new Array(size).fill(false));
    const role = Array.from({
      length: size
    }, () => new Array(size).fill(null));
    const set = (x, y, dark, r) => {
      m[y][x] = dark;
      role[y][x] = r;
    };
    for (let i = 0; i < size; i++) {
      set(6, i, i % 2 === 0, 'timing');
      set(i, 6, i % 2 === 0, 'timing');
    }
    for (const [cx, cy] of [[3, 3], [size - 4, 3], [3, size - 4]]) {
      for (let dy = -4; dy <= 4; dy++) for (let dx = -4; dx <= 4; dx++) {
        const x = cx + dx, y = cy + dy;
        if (x < 0 || y < 0 || x >= size || y >= size) continue;
        const d = Math.max(Math.abs(dx), Math.abs(dy));
        set(x, y, d !== 2 && d !== 4, d === 4 ? 'separator' : 'finder');
      }
    }
    const align = qrAlignment(v);
    align.forEach((ax, i) => align.forEach((ay, j) => {
      if (i === 0 && j === 0 || i === 0 && j === align.length - 1 || i === align.length - 1 && j === 0) return;
      for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) set(ax + dx, ay + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1, 'alignment');
    }));
    const formatCells = [];
    for (let i = 0; i < 9; i++) {
      if (i !== 6) {
        formatCells.push([8, i], [i, 8]);
      }
    }
    for (let i = 0; i < 8; i++) formatCells.push([size - 1 - i, 8], [8, size - 1 - i]);
    formatCells.forEach(([x, y]) => set(x, y, false, 'format'));
    set(8, size - 8, true, 'format');
    if (v >= 7) {
      let rem = v;
      for (let i = 0; i < 12; i++) rem = rem << 1 ^ (rem >> 11) * 0x1f25;
      const vb = v << 12 | rem;
      for (let i = 0; i < 18; i++) {
        const bit = (vb >> i & 1) === 1, a = size - 11 + i % 3, b = Math.floor(i / 3);
        set(a, b, bit, 'version');
        set(b, a, bit, 'version');
      }
    }
    let i = 0;
    for (let right = size - 1; right >= 1; right -= 2) {
      if (right === 6) right = 5;
      for (let vert = 0; vert < size; vert++) for (let j = 0; j < 2; j++) {
        const x = right - j, upward = (right + 1 & 2) === 0, y = upward ? size - 1 - vert : vert;
        if (role[y][x]) continue;
        role[y][x] = i < codewords.length * 8 ? 'data' : 'remainder';
        m[y][x] = i < codewords.length * 8 ? (codewords[i >> 3] >> 7 - (i & 7) & 1) === 1 : false;
        i++;
      }
    }
    const formatBits = mask => {
      const d = QR_FORMAT_EC[ec] << 3 | mask;
      let rem = d;
      for (let k = 0; k < 10; k++) rem = rem << 1 ^ (rem >> 9) * 0x537;
      return (d << 10 | rem) ^ 0x5412;
    };
    const apply = mask => {
      const out = m.map((row, y) => row.map((dark, x) => (role[y][x] === 'data' || role[y][x] === 'remainder') && qrMask[mask](x, y) ? !dark : dark));
      const fb = formatBits(mask), bit = k => (fb >> k & 1) === 1;
      for (let k = 0; k <= 5; k++) out[k][8] = bit(k);
      out[7][8] = bit(6);
      out[8][8] = bit(7);
      out[8][7] = bit(8);
      for (let k = 9; k < 15; k++) out[8][14 - k] = bit(k);
      for (let k = 0; k < 8; k++) out[8][size - 1 - k] = bit(k);
      for (let k = 8; k < 15; k++) out[size - 15 + k][8] = bit(k);
      out[size - 8][8] = true;
      return out;
    };
    let best = null;
    for (let mask = 0; mask < 8; mask++) {
      const candidate = apply(mask), p = qrPenalty(candidate);
      if (!best || p < best.p) best = {
        p,
        mask,
        grid: candidate
      };
    }
    return {
      grid: best.grid,
      role,
      size,
      version: v,
      ec,
      mask: best.mask,
      quiet: 4,
      dataCodewords: capacity,
      ecCodewords: ecLen * numBlocks
    };
  };
  const DM_SIZES = [[10, 8, 3, 5], [12, 10, 5, 7], [14, 12, 8, 10], [16, 14, 12, 12], [18, 16, 18, 14], [20, 18, 22, 18], [22, 20, 30, 20], [24, 22, 36, 24], [26, 24, 44, 28], [32, 14, 62, 36], [36, 16, 86, 42], [40, 18, 114, 48], [44, 20, 144, 56], [48, 22, 174, 68]];
  const dmPlacement = (nrow, ncol) => {
    const a = new Array(nrow * ncol).fill(0);
    const module = (row, col, chr, bit) => {
      if (row < 0) {
        row += nrow;
        col += 4 - (nrow + 4) % 8;
      }
      if (col < 0) {
        col += ncol;
        row += 4 - (ncol + 4) % 8;
      }
      a[row * ncol + col] = 10 * chr + bit;
    };
    const utah = (row, col, chr) => {
      module(row - 2, col - 2, chr, 1);
      module(row - 2, col - 1, chr, 2);
      module(row - 1, col - 2, chr, 3);
      module(row - 1, col - 1, chr, 4);
      module(row - 1, col, chr, 5);
      module(row, col - 2, chr, 6);
      module(row, col - 1, chr, 7);
      module(row, col, chr, 8);
    };
    const corner = (chr, cells) => cells.forEach(([r, c], k) => module(r, c, chr, k + 1));
    let chr = 1, row = 4, col = 0;
    do {
      if (row === nrow && col === 0) corner(chr++, [[nrow - 1, 0], [nrow - 1, 1], [nrow - 1, 2], [0, ncol - 2], [0, ncol - 1], [1, ncol - 1], [2, ncol - 1], [3, ncol - 1]]);
      if (row === nrow - 2 && col === 0 && ncol % 4) corner(chr++, [[nrow - 3, 0], [nrow - 2, 0], [nrow - 1, 0], [0, ncol - 4], [0, ncol - 3], [0, ncol - 2], [0, ncol - 1], [1, ncol - 1]]);
      if (row === nrow - 2 && col === 0 && ncol % 8 === 4) corner(chr++, [[nrow - 3, 0], [nrow - 2, 0], [nrow - 1, 0], [0, ncol - 2], [0, ncol - 1], [1, ncol - 1], [2, ncol - 1], [3, ncol - 1]]);
      if (row === nrow + 4 && col === 2 && !(ncol % 8)) corner(chr++, [[nrow - 1, 0], [nrow - 1, ncol - 1], [0, ncol - 3], [0, ncol - 2], [0, ncol - 1], [1, ncol - 3], [1, ncol - 2], [1, ncol - 1]]);
      do {
        if (row < nrow && col >= 0 && !a[row * ncol + col]) utah(row, col, chr++);
        row -= 2;
        col += 2;
      } while (row >= 0 && col < ncol);
      row += 1;
      col += 3;
      do {
        if (row >= 0 && col < ncol && !a[row * ncol + col]) utah(row, col, chr++);
        row += 2;
        col -= 2;
      } while (row < nrow && col >= 0);
      row += 3;
      col += 1;
    } while (row < nrow || col < ncol);
    if (!a[nrow * ncol - 1]) {
      a[nrow * ncol - 1] = 1;
      a[nrow * ncol - ncol - 2] = 1;
    }
    return a;
  };
  const encodeDataMatrix = (text, gs1 = false) => {
    const cw = gs1 ? [232] : [];
    for (let i = 0; i < text.length; ) {
      const c = text.charCodeAt(i);
      if ((/\d\d/).test(text.slice(i, i + 2))) {
        cw.push(130 + Number(text.slice(i, i + 2)));
        i += 2;
      } else if (c === 0x1d && gs1) {
        cw.push(232);
        i += 1;
      } else if (c < 128) {
        cw.push(c + 1);
        i += 1;
      } else {
        cw.push(235, c - 128 + 1);
        i += 1;
      }
    }
    const spec = DM_SIZES.find(([, , d]) => d >= cw.length);
    if (!spec) throw new Error('Too much data for this Data Matrix encoder');
    const [size, region, dataLen, ecLen] = spec;
    const data = [...cw];
    if (data.length < dataLen) data.push(129);
    while (data.length < dataLen) {
      let pad = 129 + 149 * (data.length + 1) % 253 + 1;
      if (pad > 254) pad -= 254;
      data.push(pad);
    }
    const codewords = [...data, ...gf(0x12d).remainder(data, ecLen, 1)];
    const per = size / (region + 2);
    const n = region * per;
    const place = dmPlacement(n, n);
    const grid = Array.from({
      length: size
    }, () => new Array(size).fill(false));
    const role = Array.from({
      length: size
    }, () => new Array(size).fill(null));
    for (let by = 0; by < per; by++) for (let bx = 0; bx < per; bx++) {
      const y0 = by * (region + 2), x0 = bx * (region + 2);
      for (let k = 0; k < region + 2; k++) {
        grid[y0 + region + 1][x0 + k] = true;
        role[y0 + region + 1][x0 + k] = 'finder';
        grid[y0 + k][x0] = true;
        role[y0 + k][x0] = 'finder';
      }
      for (let k = 0; k < region + 2; k++) {
        if (!role[y0][x0 + k]) {
          grid[y0][x0 + k] = k % 2 === 0;
          role[y0][x0 + k] = 'timing';
        }
        if (!role[y0 + k][x0 + region + 1]) {
          grid[y0 + k][x0 + region + 1] = k % 2 === 1;
          role[y0 + k][x0 + region + 1] = 'timing';
        }
      }
    }
    for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) {
      const y = Math.floor(r / region) * (region + 2) + 1 + r % region;
      const x = Math.floor(c / region) * (region + 2) + 1 + c % region;
      const v = place[r * n + c];
      const chr = Math.floor(v / 10), bit = v % 10;
      grid[y][x] = v === 1 ? true : chr > 0 ? (codewords[chr - 1] >> 8 - bit & 1) === 1 : false;
      role[y][x] = chr > dataLen ? 'ec' : 'data';
    }
    return {
      grid,
      role,
      size,
      quiet: 1,
      dataCodewords: dataLen,
      ecCodewords: ecLen,
      used: cw.length
    };
  };
  const GS1_FIXED = /^(0[0-3]|1[1-35-7]|20|3[1-6]\d\d|41[0-7])$/;
  const gs1Text = hri => {
    const fields = [...hri.matchAll(/\((\d{2,4})\)([^(]*)/g)];
    return fields.map(([, ai, v], i) => ai + v + (i < fields.length - 1 && !GS1_FIXED.test(ai) ? '\x1d' : '')).join('');
  };
  const MATRIX_ROLES = {
    'qr-code': [['finder', 'rgba(37, 99, 235, 0.45)', 'Finder patterns', 'Three squares that let a scanner find the symbol and work out its size and angle, from any direction.'], ['separator', null, null, null], ['timing', 'rgba(234, 88, 12, 0.55)', 'Timing patterns', 'Alternating dark and light modules between the finder patterns, which set the module grid.'], ['alignment', 'rgba(147, 51, 234, 0.5)', 'Alignment patterns', 'Smaller squares that help correct for a curved or skewed surface. Larger versions have more of them.'], ['format', 'rgba(22, 163, 74, 0.55)', 'Format information', 'The error correction level and the mask, stored twice so one copy can be damaged.'], ['version', 'rgba(219, 39, 119, 0.5)', 'Version information', 'The symbol’s size, stored twice. Only versions 7 and up have it.'], ['data', null, 'Data and error correction', 'Everything unshaded. Codewords run in two-module columns, zigzagging up and down from the bottom right.']],
    datamatrix: [['finder', 'rgba(37, 99, 235, 0.45)', 'Finder pattern', 'A solid L along the left and bottom edges, which shows a scanner where the symbol is and which way up it is.'], ['timing', 'rgba(234, 88, 12, 0.55)', 'Clock track', 'Alternating modules along the top and right edges, which set the module grid. Larger sizes repeat both inside the symbol.'], ['data', null, 'Data', 'Unshaded. The encoded data, eight modules to a codeword.'], ['ec', 'rgba(22, 163, 74, 0.4)', 'Error correction', 'Reed–Solomon codewords that let a scanner rebuild damaged data.']]
  };
  const Matrix2D = ({type, value, ec, plain, damage}) => {
    const sym = type === 'qr-code' ? encodeQR(String(value), ec || 'M') : encodeDataMatrix(gs1Text(String(value)) || String(value), String(value).startsWith('('));
    const {grid, role, size} = sym;
    const quiet = Math.max(sym.quiet, 2);
    const M = 8, full = (size + 2 * quiet) * M, at = i => (i + quiet) * M;
    const roles = MATRIX_ROLES[type];
    const cells = [];
    grid.forEach((row, y) => row.forEach((dark, x) => {
      if (dark) cells.push(<rect key={`${x}-${y}`} x={at(x)} y={at(y)} width={M} height={M} />);
    }));
    const h = ({
      light: 0.16,
      heavy: 0.3,
      severe: 0.36
    })[damage] || 0.16, w = 0.5;
    const scratch = damage ? <g fill="#ffffff">
        <rect x={at(size * 0.38)} y={at(size * 0.5)} width={size * w * M} height={size * h * M} transform={`rotate(-12 ${at(size * 0.67)} ${at(size * 0.58)})`} />
      </g> : null;
    const overlays = [];
    if (!plain && !damage) {
      roles.forEach(([r, color]) => {
        if (!color) return;
        grid.forEach((row, y) => row.forEach((_, x) => {
          if (role[y][x] === r) overlays.push(<rect key={`${r}-${x}-${y}`} x={at(x)} y={at(y)} width={M} height={M} fill={color} />);
        }));
      });
    }
    const legend = roles.filter(([, , title]) => title);
    const name = (findType(type) || ({
      name: type
    })).name;
    const label = `${name} for ${String(value)}`;
    const svg = <svg viewBox={`0 0 ${full} ${full}`} role="img" aria-label={damage ? `${label}, scratched, with error correction level ${ec}` : label} style={{
      width: '100%',
      maxWidth: plain || damage ? 240 : 360,
      height: 'auto'
    }}>
        <rect x="0" y="0" width={full} height={full} fill="#ffffff" rx={plain ? 0 : 6} />
        <g fill="#111214">{cells}</g>
        <g data-overlay="">{overlays}</g>
        {scratch}
      </svg>;
    if (plain || damage) return <figure className="not-prose my-6">{svg}</figure>;
    return <figure className="not-prose my-6">
        {svg}
        <figcaption className="mt-4">
          <ul className="pl-0 text-sm" style={{
      listStyle: 'none'
    }}>
            {legend.map(([r, color, title, meaning]) => <li key={r} style={{
      marginBottom: 6
    }}>
                <span aria-hidden="true" style={{
      display: 'inline-block',
      width: 12,
      height: 12,
      marginRight: 8,
      verticalAlign: 'middle',
      background: color || '#ffffff',
      border: '1px solid currentColor',
      opacity: color ? 1 : 0.5
    }} />
                <strong>{title}.</strong> {meaning}
              </li>)}
          </ul>
          <p className="text-sm" style={muted}>
            {type === 'qr-code' ? `Version ${sym.version} (${size}×${size} modules), error correction level ${sym.ec}, mask ${sym.mask}: ${sym.dataCodewords} data codewords and ${sym.ecCodewords} error correction codewords.` : `${size}×${size} modules: ${sym.dataCodewords} data codewords and ${sym.ecCodewords} error correction codewords.`}
          </p>
        </figcaption>
      </figure>;
  };
  const Damage = ({type = 'qr-code', value, levels = 'L,H', severity = 'light'}) => <div className="not-prose" style={{
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fit, minmax(110px, 1fr))',
    gap: 12
  }}>
      {levels.split(',').map(ec => {
    const {size} = encodeQR(String(value), ec.trim());
    return <div key={ec}>
            {Matrix2D({
      type,
      value,
      ec: ec.trim(),
      damage: severity
    })}
            <p className="text-sm" style={{
      textAlign: 'center',
      marginTop: -12
    }}>Level {ec.trim()} · {size}×{size}</p>
          </div>;
  })}
    </div>;
  const BarStates = ({kind = 'four-state', labels}) => {
    const names = labels ? labels.split(',').map(l => l.trim()) : kind === 'height' ? ['Tall', 'Short'] : ['Full', 'Ascender', 'Descender', 'Tracker'];
    const shapes = kind === 'height' ? [[0, 40], [24, 16]] : [[0, 40], [0, 26], [14, 26], [14, 12]];
    const gap = 92, width = names.length * gap;
    return <figure className="not-prose my-6">
        <svg viewBox={`0 0 ${width} 78`} role="img" aria-label={`Bar shapes: ${names.join(', ')}`} style={{
      width: '100%',
      maxWidth: width * 1.4,
      height: 'auto'
    }}>
          {kind !== 'height' && <rect x="0" y="14" width={width} height="12" fill="currentColor" opacity="0.08" />}
          {shapes.map(([top, h], i) => <g key={i}>
              <rect x={i * gap + gap / 2 - 5} y={top} width="10" height={h} fill="currentColor" />
              <text x={i * gap + gap / 2} y="72" textAnchor="middle" fontSize="12" fill="currentColor">{names[i]}</text>
            </g>)}
        </svg>
      </figure>;
  };
  const GroupMembers = ({group}) => {
    const members = BARCODE_TYPES.filter(t => t.groups.includes(group));
    if (!members.length) return <p style={muted}>No barcode types in “{group}”.</p>;
    return <ul>
        {members.map(t => <li key={t.slug}>
            <a href={href(t)}>{t.name}</a>
            {t.groupWhen && t.groupWhen[group] && `, ${t.groupWhen[group]}`}
          </li>)}
      </ul>;
  };
  const VIEWS = {
    facts: Facts,
    support: SupportMatrix,
    groups: GroupMatrix,
    'check-digit': CheckDigitSteps,
    anatomy: p => MATRIX_ROLES[p.type] ? Matrix2D(p) : LINEAR[p.type] ? Linear(p) : Anatomy(p),
    symbol: p => MATRIX_ROLES[p.type] ? Matrix2D({
      ...p,
      plain: true
    }) : LINEAR[p.type] ? Linear({
      ...p,
      plain: true
    }) : Anatomy({
      ...p,
      plain: true
    }),
    damage: Damage,
    'bar-states': BarStates,
    group: GroupMembers
  };
  const render = VIEWS[view];
  return render ? render(props) : <p style={muted}>Unknown barcode view “{view}”.</p>;
};

export const type_0 = "code-128"

Code 128 is the most widely used general-purpose linear barcode. It can encode any text a keyboard can type, and it packs digits two to a character, so it's compact for both.

<Barcode view="facts" type="code-128" />

<CardGroup cols={2}>
  <Card title="Decode one" icon="magnifying-glass" href={`/tools/barcode-anatomy?type=${type_0}`}>
    Scan or paste a barcode and see every part of it.
  </Card>

  <Card title="Make one" icon="wand-magic-sparkles" href={`/tools/generator?type=${type_0}`}>
    Generate a valid barcode from fields.
  </Card>
</CardGroup>

## Where you'll see it

* **Shipping labels.** Parcel carriers' tracking numbers are commonly Code 128.
* **Logistics labels** in the GS1 form, [GS1-128](/reference/barcode-types/gs1-128).
* **Inventory, asset and document labels**, wherever a business needs letters as well as numbers.

## Anatomy

<Barcode view="anatomy" type="code-128" value="ZipZap" />

### Characters

Every character is 11 modules wide, made of three bars and three spaces, each 1 to 4 modules wide. There are 107 different characters: 103 for data and control, three start codes, and a stop.

### Three code sets

The same 103 characters mean different things in each of three code sets:

| Code set | Contains | Use it for |
| - | - | - |
| A | Uppercase letters, digits, punctuation and control characters | Data with control characters, such as a tab |
| B | Uppercase and lowercase letters, digits and punctuation | Ordinary text |
| C | The pairs of digits 00 to 99 | Numbers, at two digits per character |

The start code chooses the first code set, and special characters switch between them part way through. An encoder picks the shortest combination, so `ABC12345678` is usually encoded as letters in code set B, then the digits in pairs in code set C.

You never see any of this in the data. A scanner returns the text, not the code sets.

### Size and quiet zones

Code 128 has no fixed size; each application sets its own. The quiet zones are at least 10 modules on each side.

## Check character

Every Code 128 barcode ends with a check character, calculated with mod-103 from the start code and every character after it. For `ZipZap`, it's the character with value 40.

Scanners verify it and then drop it, so it's never printed or sent, and you only need it to draw a barcode. The calculation is worked through in [Check digits](/reference/check-digits#code-128-mod-103).

## Variants and related types

* **[GS1-128](/reference/barcode-types/gs1-128)**: Code 128 with a special character at the start that marks GS1 data.
* **[Code 39](/reference/barcode-types/code-39)**: older, simpler and less dense, with uppercase letters only.
* **[Code 93](/reference/barcode-types/code-93)**: a denser successor to Code 39 that never displaced Code 128.

## Gotchas

* **A barcode that's too long to scan.** Long text makes a wide barcode. Past a certain width, phone cameras and handheld scanners can't fit it in view. Consider a QR code for long data.
* **Invisible characters in the data.** Code set A can carry control characters, such as a tab or a line break, that won't be visible when you print the scan. See [invisible characters](/reference/scan-vs-printed-number#invisible-characters).
* **A Code 128 barcode that's really GS1 data.** If it starts with digits like `01` or `00` and the scanner reports GS1-128, parse it as GS1 data, not as plain text.

## Scanning it in your app

<Barcode view="support" type="code-128" />

```swift theme={null}
ScanField("Tracking number", text: $tracking)
    .barcodeTypes(.code128)
    .validate(.matches(/^[A-Z0-9]{10,22}$/))
```

Code 128 accepts almost any text, so a pattern is the best way to make sure a scan is the kind of value you expect. See [Validation](/sdk/modifiers/validation).

## Specification

* ISO/IEC 15417: the Code 128 barcode specification.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.