All files / src/astro Trans.astro

100% Statements 16/16
100% Branches 12/12
100% Functions 3/3
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 365x                               5x 5x 15x 5x   5x 5x     5x 1x         15x 5x 5x    
---
interface Props {
  /**
   * Translation template. Placeholders use `{{name}}` and are filled by Astro slots with the same name.
   * When there is only one placeholder, the default slot can be used instead.
   *
   * @example
   * ```astro
   * <Trans message="a{{b}}c">
   *   <strong>B</strong>
   * </Trans>
   * ```
   */
  message: string;
}
 
const { message = "" } = Astro.props;
const parts = message.split(/{{(\S+?)}}/gi);
const keys = parts.filter((_, i) => i % 2);
const slots = new Map<string, string>();
 
for (const key of keys) {
  if (Astro.slots.has(key)) slots.set(key, await Astro.slots.render(key));
}
 
if (keys.length === 1 && !slots.has(keys[0]) && Astro.slots.has("default")) {
  slots.set(keys[0], await Astro.slots.render("default"));
}
---
 
{parts.map((part, i) => {
  if (i % 2 === 0) return part;
  const html = slots.get(part);
  return html === undefined ? `{{${part}}}` : <Fragment set:html={html} />;
})}