record static method
The token for one read: == the value, and its own object.
Not the stored string. A catalog compiled as a const Dart map
hands out canonicalised literals, so two keys sharing a value would be one
object — and, worse, a hardcoded 'Cancel' in the UI would be identical
to the catalog's and be attributed to a key it never came from.
Measured on a real catalog: 29 values shared by 66 of 545 keys. Minting
a copy makes the mechanism independent of how the catalog is stored.
String.fromCharCodes because it is one of only two expressions that
actually allocate. '$value', value.substring(0) and a StringBuffer
all hand back the same instance — the obvious ways to force a copy
silently do nothing, and would have made this work on a JSON catalog and
fail on a compiled one.
Implementation
static String record(
String catalog,
String key,
String value, {
bool expansion = false,
}) {
if (!recording) return value;
if (!expansion) (_read[catalog] ??= {})[key] = value;
// An empty value has no glyphs to carry identity, and the empty string is
// canonical besides. Recorded above, so a key that renders nothing is still
// reportable; it just cannot be found on a screen.
if (value.isEmpty) return value;
// A budget pass pads what renders, never what was read: `_read` above
// keeps the real value. Expansions pad too — the built string is the one
// on screen, so it is the one whose room is being measured.
var minted = switch (expandPercent) {
var percent? =>
value +
expansionPadding(
catalog,
key,
expansionLength(value.length, percent),
),
_ => value,
};
var token = _tokens.putIfAbsent(
'$catalog$key$minted',
() => String.fromCharCodes(minted.codeUnits),
);
_keys[token] = TranslationKey(catalog, key);
return token;
}