All files / app-play/src/ui localized.ts

21.42% Statements 3/14
20% Branches 2/10
16.66% Functions 1/6
27.27% Lines 3/11

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 36 37 38 39 40 41 42                            227x 227x                                                 14x  
import { AsyncDirective } from 'lit/async-directive.js';
import { directive, type Part } from 'lit/directive.js';
import { onPlayerLangChange, playerText } from '../player-copy.ts';
 
type Shell = ReturnType<typeof playerText>['shell'];
type TextKey = { [K in keyof Shell]: Shell[K] extends string ? K : never }[keyof Shell];
type LocalizedValue = TextKey | (() => unknown);
 
/** Each binding owns its text/attribute; no selector pass rewrites Lit's child markers. */
class LocalizedDirective extends AsyncDirective {
  private value: LocalizedValue | undefined;
  private unsubscribe: (() => void) | undefined;
 
  override render(value: LocalizedValue): unknown {
    this.value = value;
    return typeof value === 'function' ? value() : playerText().shell[value];
  }
 
  override update(_part: Part, [value]: [LocalizedValue]): unknown {
    if (this.isConnected && this.unsubscribe === undefined) this.subscribe();
    return this.render(value);
  }
 
  protected override disconnected(): void {
    this.unsubscribe?.();
    this.unsubscribe = undefined;
  }
 
  protected override reconnected(): void {
    this.subscribe();
    if (this.value !== undefined) this.setValue(this.render(this.value));
  }
 
  private subscribe(): void {
    this.unsubscribe = onPlayerLangChange(() => {
      if (this.value !== undefined) this.setValue(this.render(this.value));
    });
  }
}
 
export const localized = directive(LocalizedDirective);