Icu messageformat pluralization

From CraftOS-dev/craftbot-agent-bundles · View interactive version

Icu messageformat pluralization is an AI agent skill from the GitHub repository CraftOS-dev/craftbot-agent-bundles. ICU MessageFormat — plurals, gender, select, nested, dates/numbers/currency. CLDR plural rules per language. FormatJS CLI for lint + extract + compile. Use when the user asks "add plurals", "gender-aware strings", "ICU plural rules", or "fix CLDR categories".

How to use this skill

Skill file

ICU MessageFormat & Pluralization

ICU MessageFormat 1 (current 2026 standard) handles plurals, gender, select, dates/numbers/currency — without if/else logic in components. CLDR plural rules cover all 30+ plural categories (Arabic 6, Russian/Polish 4, English 2, CJK 1).

MessageFormat 2.0 is approaching standardization in 2026; plan for migration but ship MF1 today.

When to use

Trigger phrases: "ICU", "MessageFormat", "plurals", "CLDR plurals", "gender select", "FormatJS", "intl-messageformat", "MF2".

Setup

# FormatJS CLI (lint + extract + compile)
npm i -g @formatjs/cli

# Runtime (any of these)
npm i intl-messageformat               # standalone
npm i react-intl                       # React + FormatJS
npm i i18next i18next-icu              # i18next + ICU
npm i next-intl                        # Next.js (uses intl-messageformat under hood)

# Browser/Node 22+ have Intl.* APIs that ICU uses

Auth/env: none required.

CLDR plural categories (memorize)

| Language | Categories | Notes |

|---|---|---|

| English, German, Dutch | one, other | 1 vs 2+ |

| Spanish, Italian, Portuguese | one, many, other | 1 / 1M+ / 2-999K |

| French | one, many, other | 0,1 / 1M+ / 2+ |

| Russian, Polish, Ukrainian, Croatian | one, few, many, other | 1,21,31 / 2-4,22-24 / 0,5-20 |

| Arabic | zero, one, two, few, many, other | 0 / 1 / 2 / 3-10 / 11-99 / 100+ |

| Hebrew | one, two, many, other | 1 / 2 / 10,20,... / other |

| Japanese, Chinese, Korean, Thai, Vietnamese | other | all numbers |

| Welsh | zero, one, two, few, many, other | 0 / 1 / 2 / 3 / 6 / other |

Always provide other — it's the universal fallback.

Common recipes

Recipe 1: Basic plural

{count, plural,
  =0 {No items}
  one {# item}
  other {# items}
}

=0, =1, =N match exact values (before category rules). one, other match CLDR category. # substitutes the count.

Recipe 2: Arabic 6-form plural

{count, plural,
  zero {لا توجد عناصر}
  one {عنصر واحد}
  two {عنصران}
  few {# عناصر}
  many {# عنصرًا}
  other {# عنصر}
}

All 6 categories required for translator UX. Translators get explicit warnings if any is missing.

Recipe 3: Gender select

{gender, select,
  male {He uploaded a photo.}
  female {She uploaded a photo.}
  other {They uploaded a photo.}
}

select is exact-match (not CLDR rules). Always include other as fallback.

Recipe 4: Nested plural + gender

{numPhotos, plural,
  =0 {{gender, select,
       female {She has no photos.}
       male {He has no photos.}
       other {They have no photos.}}}
  =1 {{gender, select,
       female {She has 1 photo.}
       male {He has 1 photo.}
       other {They have 1 photo.}}}
  other {{gender, select,
          female {She has # photos.}
          male {He has # photos.}
          other {They have # photos.}}}
}

Recipe 5: Date / time / number / currency

You have {count, number} items as of {date, date, long} ({date, time, short}).
Total: {amount, number, ::currency/EUR}
Discount: {pct, number, percent}

Skeleton syntax (ICU 1.5+):

{amount, number, ::currency/EUR .00}            EUR with 2 decimals
{date, date, ::yMMMd}                            "Apr 3, 2026"
{date, date, ::yMMMMEEEEd}                       "Saturday, April 3, 2026"

Recipe 6: react-intl extraction (FormatJS)

// src/components/Cart.tsx
import { FormattedMessage } from 'react-intl';

<FormattedMessage
  id="cart.itemCount"
  defaultMessage="{count, plural, =0 {No items} one {# item} other {# items}}"
  values={{ count }}
/>

<FormattedMessage
  id="cart.userPhotos"
  defaultMessage="{count, plural, =0 {{gender, select, female {She has no photos.} male {He has no photos.} other {They have no photos.}}} other {{gender, select, female {She has # photos.} male {He has # photos.} other {They have # photos.}}}}"
  values={{ count, gender }}
/>

Extract:

formatjs extract 'src/**/*.{ts,tsx}' --out-file lang/en.json \
  --id-interpolation-pattern '[sha512:contenthash:base64:6]'

Recipe 7: Lint catalogs for ICU correctness

formatjs lint 'lang/**/*.json'

# Catches:
# - Missing `other` fallback
# - Unbalanced braces
# - Missing CLDR categories per locale (e.g., `zero` missing in Arabic plural)
# - Unknown skeleton patterns

Recipe 8: Compile to AST (faster runtime)

formatjs compile lang/en.json --ast --out-file lang/compiled/en.json

AST is pre-parsed; runtime skips parse step. Useful for high-RPS pages.

Recipe 9: i18next + ICU

npm i i18next i18next-icu intl-messageformat
import i18next from 'i18next';
import ICU from 'i18next-icu';

i18next.use(ICU).init({
  lng: 'de',
  resources: {
    de: {
      translation: {
        'cart.items': '{count, plural, one {# Artikel} other {# Artikel}}',
      },
    },
  },
});

i18next.t('cart.items', { count: 3 });   // "3 Artikel"

Recipe 10: Standalone intl-messageformat

import IntlMessageFormat from 'intl-messageformat';

const msg = new IntlMessageFormat(
  '{count, plural, one {# item} other {# items}}',
  'en'
);
msg.format({ count: 3 });   // "3 items"

Recipe 11: Paraglide-js + ICU

npx @inlang/paraglide-js@latest init
npm i @inlang/paraglide-js-adapter-message-format
// messages/en.json
{
  "cart_items": "{count, plural, one {# item} other {# items}}"
}

// Use compiled:
import * as m from '$lib/paraglide/messages';
m.cart_items({ count: 3 });   // type-checked!

Recipe 12: next-intl + ICU (native)

// messages/en.json
{
  "Cart": {
    "items": "{count, plural, =0 {No items} one {# item} other {# items}}"
  }
}

// component.tsx
import { useTranslations } from 'next-intl';
const t = useTranslations('Cart');
t('items', { count: 3 });

Recipe 13: Skeleton number formats (ICU 1.5+)

{n, number, ::currency/USD}                     $1,234.56
{n, number, ::currency/JPY}                     ¥1,235        (no decimals — CLDR auto)
{n, number, ::compact-short}                    1.2K, 3.5M
{n, number, ::scientific}                       1.234E3
{n, number, ::percent .00}                      12.34%
{n, number, ::measure-unit/length-meter}        1,234 m
{n, number, ::measure-unit/length-meter unit-width-narrow}  1,234m

Recipe 14: Skeleton date formats

{d, date, ::yMd}              4/3/2026
{d, date, ::yMMMMd}           April 3, 2026
{d, date, ::yMMMMEEEEd}       Saturday, April 3, 2026
{d, date, ::hms}              3:45:32 PM
{d, date, ::EEEEMMMdjmm}      Sat, Apr 3, 3:45 PM

Recipe 15: Validate against CLDR rules per locale

// Build-time check — does locale 'ar' file have all 6 plural categories?
import { PluralRules } from 'intl-pluralrules';
const arRules = new Intl.PluralRules('ar');
const REQUIRED = ['zero', 'one', 'two', 'few', 'many', 'other'];
const present = new Set();
for (let n = 0; n < 200; n++) {
  present.add(arRules.select(n));
}
const missing = REQUIRED.filter(c => !present.has(c));
console.log({ missing });   // should be []

Recipe 16: MessageFormat 2.0 preview

.match {$count :number}
0  {{No items}}
one {{One item}}
*  {{{$count} items}}

MF2 is a structural rewrite — more readable, better tool support. ICU 75+ has MF2 parser. Plan migration when MF2 ships in stable Intl.MessageFormat (likely 2026-2027).

Examples

Example 1: Add cart-count plural to a SaaS app

Goal: Display "5 items in cart" with correct plural in 6 locales (incl. AR + RU).

Steps:

  1. Define in en.json: {count, plural, =0 {Cart is empty} one {# item in cart} other {# items in cart}}.
  2. Push to Crowdin. Translators see ICU editor with per-locale plural categories.
  3. AR translator fills zero/one/two/few/many/other. RU fills one/few/many/other.
  4. Pull: crowdin download.
  5. Lint: formatjs lint 'lang/**/*.json' → confirms each locale has required categories.
  6. Compile: formatjs compile lang/de.json --ast --out-file lang/compiled/de.json.
  7. Test:

Result: All locales render grammatically correct counts; translators no longer file "plural form" bugs.

Example 2: Gender + count nested for activity feed

Goal: "Alice uploaded 3 photos" with gender + count in 6 locales.

Steps:

  1. Define nested message (Recipe 4) in en.json.
  2. Source-side: <FormattedMessage id="feed.photos" values={{ name, gender, count }} />.
  3. Crowdin opens nested ICU editor — translators see each combination.
  4. Verify each locale handles gender + count combination correctly.
  5. Test edge cases: gender unknown (other), count 0, count 1, count 10, count 100.

Result: Activity feed reads naturally in every locale; "they have 1 photos" bug eliminated.

Edge cases / gotchas

```tsx

<FormattedMessage

id="welcome"

defaultMessage="Hello <b>{name}</b>"

values={{ name: 'Alice', b: chunks => <b>{chunks}</b> }}

/>

```

Sources

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.