distributeFurigana static method

List<RubyTextData> distributeFurigana(
  1. {required DictionaryHeading heading}
)

Generate Furigana for a DictionaryHeading.

Implementation

static List<RubyTextData> distributeFurigana(
    {required DictionaryHeading heading}) {
  if (_furiganaCache[heading] != null) {
    return _furiganaCache[heading]!;
  }

  String term = heading.term;
  String reading = heading.reading;

  if (reading == term) {
    // The term and reading are the same. No Furigana required.
    return [RubyTextData(term)];
  }

  List<FuriganaDistributionGroup> groups = [];

  FuriganaDistributionGroup? groupPre;
  bool? isKanaPre;

  for (int codePoint in term.runes) {
    String character = String.fromCharCode(codePoint);

    bool isKana = isCodePointKana(codePoint);
    if (isKanaPre == isKana) {
      groupPre!.text += character;
    } else {
      groupPre = FuriganaDistributionGroup(
        isKana: isKana,
        text: character,
        textNormalized: null,
      );
      groups.add(groupPre);
      isKanaPre = isKana;
    }
  }

  for (FuriganaDistributionGroup group in groups) {
    if (group.isKana) {
      group.textNormalized = _kanaKit.toHiragana(group.text);
    }
  }

  String readingNormalized = _kanaKit.toHiragana(reading);
  try {
    List<RubyTextData>? segments = segmentizeFurigana(
      reading: reading,
      readingNormalized: readingNormalized,
      groups: groups,
      groupsStart: 0,
    );
    if (segments != null) {
      return segments;
    }
  } catch (e) {
    /// This is the fallback upon failure.
    return [RubyTextData(term, ruby: reading)];
  }

  /// This is the fallback upon failure.
  return [RubyTextData(term, ruby: reading)];
}