Utilities

CombinationCode

One shareable code for a configuration, kept in the page URL

A combination code captures the selection of an ordered set of selection groups in one string. connectUrlState keeps it in the ?code= query parameter: a shared link opens on the same configuration, and back and forward walk through earlier ones.

Demo

Change the options below and watch the address bar. Try Gold with Insurance, Express and an engraving or a stale code, which applies what it can and, in development, logs a [urlState] warning for the rest.

Gift wrap
Insurance
Express
Card

0 / 20

demo
---
import ItemsGridBlock from '@alfadormx/blocks/composite/ItemsGrid.astro';
import TextAreaBlock from '@alfadormx/blocks/primitives/TextArea.astro';
import ToggleGroupBlock from '@alfadormx/blocks/primitives/ToggleGroup.astro';
import {
  ENGRAVING_GROUP,
  ENGRAVING_MAX_LENGTH,
  EXTRAS_GROUP,
  extrasItems,
  FINISH_GROUP,
  finishOptions,
} from './demoSpec';
---

<div class="flex flex-col gap-6">
  <ToggleGroupBlock group={FINISH_GROUP} label="Finish" options={finishOptions} />
  <ItemsGridBlock
    columns={4}
    selection={{ mode: 'multiple', group: EXTRAS_GROUP, label: 'Extras' }}
    items={extrasItems}
  />
  <div class="max-w-md">
    <TextAreaBlock
      group={ENGRAVING_GROUP}
      label="Engraving"
      maxLength={ENGRAVING_MAX_LENGTH}
      showCounter
      rows={2}
    />
  </div>
</div>

<script>
  import { connectUrlState } from '@alfadormx/blocks/url-state';
  import { demoSpec } from './demoSpec';

  connectUrlState({ spec: demoSpec });
</script>

Format

Groups sit in spec order, separated by -, after an optional product segment. Entries of a multiple group sit in spec option order, separated by ., so one configuration always yields one code. Option and product codes match [A-Za-z0-9]+, which keeps both separators free.

code     = [product "-"] segment *("-" segment)
segment  = "" | entry *("." entry) | text
entry    = 1*(A-Z / a-z / 0-9)
text     = encodeURIComponent(text) with "-" → %2D and "." → %2E

Worked examples

StateCode
Page-load defaults: Silver, Gift wrap, no engravingRING01-SV-GW-
Gold with every extraRING01-GD-GW.IN.EX.CD-
Rose gold, no extrasRING01-RG--
Silver, Card, engraving "Mia-Rose v2."RING01-SV-CD-Mia%2DRose%20v2%2E

Edge cases

Decoding is forgiving per group: whatever a stale or hand-edited code gets wrong falls back to that group’s page-load default, and the rest still applies. A code may select more options than a group’s max; limits are not enforced on decode.

CaseCodeOutcome
Empty selectionRING01-SV--An empty segment is an explicit empty selection.
Several entries in a multiple groupRING01-SV-GW.IN-Entries sit in spec option order.
TextRING01-SV-GW-For%20SamPercent-encoded; - and . are escaped as %2D and %2E.
Unknown optionRING01-SV-GW.XX-Known entries apply; the unknown one is dropped.
Every option unknownRING01-XX-YY-The group keeps its default.
Several entries in a single groupRING01-SV.GD-GW-The group keeps its default.
Missing trailing segmentRING01-GDMissing groups keep their defaults.
Extra segmentsRING01-GD-GW--ZZIgnored, so a newer code still opens on an older page.
Malformed textRING01-SV-GW-%E0%A4%AThe text group keeps its default.
Another productOTHER1-GD-IN-The whole code is ignored; every group keeps its default.

History

  • Every discrete change, such as a click, pushes one history entry.
  • Consecutive keystrokes in the same text group replace the current entry, so a typing burst is one entry.
  • Back and forward restore each entry’s configuration without writing a new entry.
  • An entry without a code, such as the page as first opened, restores the page-load defaults.
  • Other query parameters and the hash are preserved on every write.
  • Loading a page with a code writes nothing, even when the code is not canonical. Text longer than the field’s limit is truncated, and the URL is rewritten in place to match.
  • Returning to the defaults still writes a code; it is never stripped.

Append-only groups

Segments are positional. Removing or reordering a group shifts every later segment, and old codes are then silently misread. Add new groups at the end only; old codes keep working because a missing trailing segment keeps its default.

Usage

connectUrlState({ spec, param }) is browser-only: call it from a client <script>. It seeds the groups on DOMContentLoaded, after every block’s initial publish, so the code wins over block defaults. It re-runs after astro:after-swap and returns a function that disconnects it. param defaults to 'code'.

<script>
  import { connectUrlState } from '@alfadormx/blocks/url-state';

  const disconnect = connectUrlState({
    spec: {
      product: 'RING01',
      groups: [
        { name: 'ring-finish', mode: 'single', options: ['SV', 'GD', 'RG'] },
        { name: 'ring-extras', mode: 'multiple', options: ['GW', 'IN', 'EX', 'CD'] },
        { name: 'ring-engraving', mode: 'text' },
      ],
    },
    param: 'code',
  });
</script>

The codec is pure and safe anywhere, including frontmatter: validateCombinationSpec throws on an ambiguous spec, encode returns the code for a state, and decode returns the selections plus notes on what it dropped.

import { decode, encode, validateCombinationSpec } from '@alfadormx/blocks/utils/combinationCode';

validateCombinationSpec(spec);
const code = encode(spec, { 'ring-finish': [{ code: 'GD' }], 'ring-extras': [], 'ring-engraving': [] });
const result = decode(spec, code);
if (result.ok) result.selections.get('ring-finish'); // [{ code: 'GD' }]