kana.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. /**
  2. * This module is mainly for handling romaji input to match the provided kana
  3. * input. While most kana map one-to-one with romaji, some kana have multiple
  4. * ways to be inputted. In addition, we also have to handle っ which causes the
  5. * next consonant to be repeated.
  6. *
  7. * The state management is done by having a state machine for each kana and it
  8. * should handle all possible variations of the romaji to be inputted.
  9. * Additionally, it also keeps track of what is left to be input, and adjusts
  10. * itself accordingly if an alternative romaji was used.
  11. *
  12. * One of the key considerations is handling っ. It doesn't have a spelling in
  13. * and of itself, but just modifies the state machine that will come after it.
  14. * Intermediate states need to be created and care should be given in what shows
  15. * up in the display.
  16. */
  17. import * as state from './state';
  18. import {
  19. State,
  20. StateMachine,
  21. makeTransition as t,
  22. mergeMachines,
  23. appendMachines,
  24. appendStates,
  25. } from './state';
  26. function literal(source: string, ...extraBoundaries: number[]): StateMachine {
  27. let transitions: state.Transition[] = [];
  28. let meta = 0;
  29. for (let i = 0; i < source.length; ++i) {
  30. let from = source.substring(i);
  31. let input = source.charAt(i);
  32. let to = source.substring(i + 1);
  33. if (i === source.length - 1 || extraBoundaries.indexOf(i) >= 0) {
  34. meta += 1;
  35. }
  36. transitions.push(t(from, input, to, meta));
  37. }
  38. return state.buildFromTransitions(source, transitions);
  39. }
  40. function shi(): StateMachine {
  41. return state.buildFromTransitions('shi', [
  42. t('shi', 's', 'hi'),
  43. t('hi', 'h', 'i'),
  44. t('hi', 'i', '', 1),
  45. t('i', 'i', '', 1),
  46. ]);
  47. }
  48. function chi(): StateMachine {
  49. return state.buildFromTransitions('chi', [
  50. t('chi', 'c', 'hi'),
  51. t('chi', 't', 'i'),
  52. t('hi', 'h', 'i'),
  53. t('i', 'i', '', 1),
  54. ]);
  55. }
  56. function tsu(): StateMachine {
  57. return state.buildFromTransitions('tsu', [
  58. t('tsu', 't', 'su'),
  59. t('su', 's', 'u'),
  60. t('su', 'u', '', 1),
  61. t('u', 'u', '', 1),
  62. ]);
  63. }
  64. function fu(): StateMachine {
  65. return state.buildFromTransitions('fu', [
  66. t('fu', 'f', 'u'),
  67. t('fu', 'h', 'u'),
  68. t('u', 'u', '', 1),
  69. ]);
  70. }
  71. function ji(): StateMachine {
  72. return state.buildFromTransitions('ji', [
  73. t('ji', 'j', 'i'),
  74. t('ji', 'z', 'i'),
  75. t('i', 'i', '', 1),
  76. ]);
  77. }
  78. function sh(end: string): StateMachine {
  79. let source = 'sh' + end;
  80. let middle = 'h' + end;
  81. return state.buildFromTransitions(source, [
  82. t(source, 's', middle, 1),
  83. t(middle, 'h', end),
  84. t(middle, 'y', end),
  85. t(end, end, '', 2),
  86. ]);
  87. }
  88. function ch(end: string): StateMachine {
  89. let source = 'ch' + end;
  90. let middle = 'h' + end;
  91. let altMiddle = 'y' + end;
  92. return state.buildFromTransitions(source, [
  93. t(source, 'c', middle),
  94. t(middle, 'h', end, 1),
  95. t(source, 't', altMiddle, 1),
  96. t(altMiddle, 'y', end),
  97. t(end, end, '', 2),
  98. ]);
  99. }
  100. function j(end: string): StateMachine {
  101. return mergeMachines(
  102. literal(`j${end}`, 0),
  103. literal(`jy${end}`, 0),
  104. literal(`zy${end}`, 0)
  105. );
  106. }
  107. function smallTsu(base: StateMachine): StateMachine {
  108. let { display, transitions } = base.initialState;
  109. const newState = new State(display.charAt(0) + display, 0);
  110. Object.keys(transitions).forEach((k) => {
  111. const nextState = transitions[k];
  112. const intermediateState = new State(k, 0);
  113. intermediateState.addTransition(k, new State('', 1));
  114. newState.addTransition(k, appendStates(intermediateState, nextState));
  115. });
  116. return mergeMachines(
  117. new StateMachine(newState),
  118. appendMachines(
  119. state.buildFromTransitions('l', [t('l', 'l', ''), t('l', 'x', '')]),
  120. tsu(),
  121. base
  122. )
  123. );
  124. }
  125. function smallKana(base: StateMachine): StateMachine {
  126. let newState = base.initialState.clone();
  127. newState.addTransition('l', base.initialState);
  128. newState.addTransition('x', base.initialState);
  129. return new StateMachine(newState);
  130. }
  131. function n(base: StateMachine): StateMachine {
  132. const allowSingleN = ['n', 'a', 'i', 'u', 'e', 'o', 'y'].every((k) => {
  133. return base.initialState.transition(k) === undefined;
  134. });
  135. if (allowSingleN) {
  136. return mergeMachines(
  137. appendMachines(literal('n'), base),
  138. appendMachines(literal('nn'), base)
  139. );
  140. } else {
  141. throw new Error(
  142. `Invalid base ${base.initialState.display}, just defer to literal`
  143. );
  144. }
  145. }
  146. interface KanaMapping {
  147. [index: string]: StateMachine;
  148. }
  149. interface StringMapping {
  150. [index: string]: string;
  151. }
  152. const WHITESPACE = state.buildFromTransitions('_', [
  153. t('_', '_', ''),
  154. t('_', ' ', ''),
  155. ]);
  156. const KATAKANA_MAPPING: StringMapping = {
  157. ア: 'あ',
  158. イ: 'い',
  159. ウ: 'う',
  160. エ: 'え',
  161. オ: 'お',
  162. カ: 'か',
  163. キ: 'き',
  164. ク: 'く',
  165. ケ: 'け',
  166. コ: 'こ',
  167. サ: 'さ',
  168. シ: 'し',
  169. ス: 'す',
  170. セ: 'せ',
  171. ソ: 'そ',
  172. タ: 'た',
  173. チ: 'ち',
  174. ツ: 'つ',
  175. テ: 'て',
  176. ト: 'と',
  177. ナ: 'な',
  178. ニ: 'に',
  179. ヌ: 'ぬ',
  180. ネ: 'ね',
  181. ノ: 'の',
  182. ハ: 'は',
  183. ヒ: 'ひ',
  184. フ: 'ふ',
  185. ヘ: 'へ',
  186. ホ: 'ほ',
  187. マ: 'ま',
  188. ミ: 'み',
  189. ム: 'む',
  190. メ: 'め',
  191. モ: 'も',
  192. ヤ: 'や',
  193. ユ: 'ゆ',
  194. ヨ: 'よ',
  195. ラ: 'ら',
  196. リ: 'り',
  197. ル: 'る',
  198. レ: 'れ',
  199. ロ: 'ろ',
  200. ワ: 'わ',
  201. ヰ: 'ゐ',
  202. ヱ: 'ゑ',
  203. ヲ: 'を',
  204. ン: 'ん',
  205. ガ: 'が',
  206. ギ: 'ぎ',
  207. グ: 'ぐ',
  208. ゲ: 'げ',
  209. ゴ: 'ご',
  210. ザ: 'ざ',
  211. ジ: 'じ',
  212. ズ: 'ず',
  213. ゼ: 'ぜ',
  214. ゾ: 'ぞ',
  215. ダ: 'だ',
  216. ヂ: 'ぢ',
  217. ヅ: 'づ',
  218. デ: 'で',
  219. ド: 'ど',
  220. バ: 'ば',
  221. ビ: 'び',
  222. ブ: 'ぶ',
  223. ベ: 'べ',
  224. ボ: 'ぼ',
  225. パ: 'ぱ',
  226. ピ: 'ぴ',
  227. プ: 'ぷ',
  228. ペ: 'ぺ',
  229. ポ: 'ぽ',
  230. ヴ: 'ゔ',
  231. ァ: 'ぁ',
  232. ィ: 'ぃ',
  233. ゥ: 'ぅ',
  234. ェ: 'ぇ',
  235. ォ: 'ぉ',
  236. ャ: 'ゃ',
  237. ュ: 'ゅ',
  238. ョ: 'ょ',
  239. ッ: 'っ',
  240. };
  241. const SINGLE_KANA_MAPPING: KanaMapping = {
  242. あ: literal('a'),
  243. い: literal('i'),
  244. う: literal('u'),
  245. え: literal('e'),
  246. お: literal('o'),
  247. か: literal('ka'),
  248. き: literal('ki'),
  249. く: literal('ku'),
  250. け: literal('ke'),
  251. こ: literal('ko'),
  252. さ: literal('sa'),
  253. し: shi(),
  254. す: literal('su'),
  255. せ: literal('se'),
  256. そ: literal('so'),
  257. た: literal('ta'),
  258. ち: chi(),
  259. つ: tsu(),
  260. て: literal('te'),
  261. と: literal('to'),
  262. な: literal('na'),
  263. に: literal('ni'),
  264. ぬ: literal('nu'),
  265. ね: literal('ne'),
  266. の: literal('no'),
  267. は: literal('ha'),
  268. ひ: literal('hi'),
  269. ふ: fu(),
  270. へ: literal('he'),
  271. ほ: literal('ho'),
  272. ま: literal('ma'),
  273. み: literal('mi'),
  274. む: literal('mu'),
  275. め: literal('me'),
  276. も: literal('mo'),
  277. や: literal('ya'),
  278. ゆ: literal('yu'),
  279. よ: literal('yo'),
  280. ら: literal('ra'),
  281. り: literal('ri'),
  282. る: literal('ru'),
  283. れ: literal('re'),
  284. ろ: literal('ro'),
  285. わ: literal('wa'),
  286. ゐ: literal('i'),
  287. ゑ: literal('e'),
  288. を: literal('wo'),
  289. ん: literal('nn'),
  290. が: literal('ga'),
  291. ぎ: literal('gi'),
  292. ぐ: literal('gu'),
  293. げ: literal('ge'),
  294. ご: literal('go'),
  295. ざ: literal('za'),
  296. じ: ji(),
  297. ず: literal('zu'),
  298. ぜ: literal('ze'),
  299. ぞ: literal('zo'),
  300. だ: literal('da'),
  301. ぢ: literal('di'),
  302. づ: literal('du'),
  303. で: literal('de'),
  304. ど: literal('do'),
  305. ば: literal('ba'),
  306. び: literal('bi'),
  307. ぶ: literal('bu'),
  308. べ: literal('be'),
  309. ぼ: literal('bo'),
  310. ぱ: literal('pa'),
  311. ぴ: literal('pi'),
  312. ぷ: literal('pu'),
  313. ぺ: literal('pe'),
  314. ぽ: literal('po'),
  315. ゔ: literal('vu'),
  316. ー: literal('-'),
  317. ' ': WHITESPACE,
  318. };
  319. 'abcdefghijklmnopqrstuvwxyz'.split('').forEach((letter) => {
  320. SINGLE_KANA_MAPPING[letter] = literal(letter);
  321. });
  322. [
  323. ['ぁ', 'あ'],
  324. ['ぃ', 'い'],
  325. ['ぅ', 'う'],
  326. ['ぇ', 'え'],
  327. ['ぉ', 'お'],
  328. ['ヵ', 'か'],
  329. ].forEach((pair) => {
  330. let [small, big] = pair;
  331. SINGLE_KANA_MAPPING[small] = smallKana(SINGLE_KANA_MAPPING[big]);
  332. });
  333. const DOUBLE_KANA_MAPPING: KanaMapping = {
  334. きゃ: literal('kya', 0),
  335. きゅ: literal('kyu', 0),
  336. きょ: literal('kyo', 0),
  337. しゃ: sh('a'),
  338. しゅ: sh('u'),
  339. しょ: sh('o'),
  340. ちゃ: ch('a'),
  341. ちゅ: ch('u'),
  342. ちょ: ch('o'),
  343. にゃ: literal('nya', 0),
  344. にゅ: literal('nyu', 0),
  345. にょ: literal('nyo', 0),
  346. ひゃ: literal('hya', 0),
  347. ひゅ: literal('hyu', 0),
  348. ひょ: literal('hyo', 0),
  349. みゃ: literal('mya', 0),
  350. みゅ: literal('myu', 0),
  351. みょ: literal('myo', 0),
  352. りゃ: literal('rya', 0),
  353. りゅ: literal('ryu', 0),
  354. りょ: literal('ryo', 0),
  355. ぎゃ: literal('gya', 0),
  356. ぎゅ: literal('gyu', 0),
  357. ぎょ: literal('gyo', 0),
  358. じゃ: j('a'),
  359. じゅ: j('u'),
  360. じょ: j('o'),
  361. ぢゃ: literal('dya', 0),
  362. ぢゅ: literal('dyu', 0),
  363. ぢょ: literal('dyo', 0),
  364. びゃ: literal('bya', 0),
  365. びゅ: literal('byu', 0),
  366. びょ: literal('byo', 0),
  367. ぴゃ: literal('pya', 0),
  368. ぴゅ: literal('pyu', 0),
  369. ぴょ: literal('pyo', 0),
  370. ふぁ: literal('fa', 0),
  371. ふぃ: literal('fi', 0),
  372. ふぇ: literal('fe', 0),
  373. ふぉ: literal('fo', 0),
  374. ゔぁ: literal('va', 0),
  375. ゔぃ: literal('vi', 0),
  376. ゔぇ: literal('ve', 0),
  377. ゔぉ: literal('vo', 0),
  378. };
  379. const TRIPLE_KANA_MAPPING: KanaMapping = {};
  380. [
  381. 'か',
  382. 'き',
  383. 'く',
  384. 'け',
  385. 'こ',
  386. 'さ',
  387. 'し',
  388. 'す',
  389. 'せ',
  390. 'そ',
  391. 'た',
  392. 'ち',
  393. 'つ',
  394. 'て',
  395. 'と',
  396. 'は',
  397. 'ひ',
  398. 'ふ',
  399. 'へ',
  400. 'ほ',
  401. 'が',
  402. 'ぎ',
  403. 'ぐ',
  404. 'げ',
  405. 'ご',
  406. 'ざ',
  407. 'じ',
  408. 'ず',
  409. 'ぜ',
  410. 'ぞ',
  411. 'だ',
  412. 'ぢ',
  413. 'づ',
  414. 'で',
  415. 'ど',
  416. 'ば',
  417. 'び',
  418. 'ぶ',
  419. 'べ',
  420. 'ぼ',
  421. 'ぱ',
  422. 'ぴ',
  423. 'ぷ',
  424. 'ぺ',
  425. 'ぽ',
  426. 'ゔ',
  427. ].forEach((kana) => {
  428. DOUBLE_KANA_MAPPING['っ' + kana] = smallTsu(SINGLE_KANA_MAPPING[kana]);
  429. DOUBLE_KANA_MAPPING['ん' + kana] = n(SINGLE_KANA_MAPPING[kana]);
  430. });
  431. [
  432. 'きゃ',
  433. 'きゅ',
  434. 'きょ',
  435. 'しゃ',
  436. 'しゅ',
  437. 'しょ',
  438. 'ちゃ',
  439. 'ちゅ',
  440. 'ちょ',
  441. 'ぎゃ',
  442. 'ぎゅ',
  443. 'ぎょ',
  444. 'じゃ',
  445. 'じゅ',
  446. 'じょ',
  447. 'ぢゃ',
  448. 'ぢゅ',
  449. 'ぢょ',
  450. 'びゃ',
  451. 'びゅ',
  452. 'びょ',
  453. 'ぴゃ',
  454. 'ぴゅ',
  455. 'ぴょ',
  456. 'ふぁ',
  457. 'ふぃ',
  458. 'ふぇ',
  459. 'ふぉ',
  460. 'ゔぁ',
  461. 'ゔぃ',
  462. 'ゔぇ',
  463. 'ゔぉ',
  464. ].forEach((kana) => {
  465. TRIPLE_KANA_MAPPING['っ' + kana] = smallTsu(DOUBLE_KANA_MAPPING[kana]);
  466. TRIPLE_KANA_MAPPING['ん' + kana] = n(DOUBLE_KANA_MAPPING[kana]);
  467. });
  468. /**
  469. * This normalizes input for matching. All alphabet is lower-cased, katakana
  470. * is transformed to hiragana. All whitespace is now just a space. We take
  471. * care to not change the length of the string as we have to match it
  472. * one-for-one so we can display the original source kana.
  473. */
  474. export function normalizeInput(input: string): string {
  475. return input
  476. .toLowerCase()
  477. .split('')
  478. .map((letter) => {
  479. let transform = KATAKANA_MAPPING[letter];
  480. if (transform !== undefined) {
  481. return transform;
  482. } else if (/\s/.test(letter)) {
  483. return ' ';
  484. } else {
  485. return letter;
  486. }
  487. })
  488. .join('');
  489. }
  490. export class KanaInputState {
  491. kana: string[];
  492. stateMachines: StateMachine[];
  493. currentIndex: number;
  494. constructor(input: string) {
  495. let kana: string[] = [];
  496. let machines: StateMachine[] = [];
  497. let position = 0;
  498. let mappings = [
  499. SINGLE_KANA_MAPPING,
  500. DOUBLE_KANA_MAPPING,
  501. TRIPLE_KANA_MAPPING,
  502. ];
  503. // we pad the input so checking 3 at a time is simpler
  504. let normalized = normalizeInput(input) + ' ';
  505. while (position < input.length) {
  506. // we check substrings of length 3, 2, then 1
  507. for (let i = 3; i > 0; --i) {
  508. let original = input.substr(position, i);
  509. let segment = normalized.substr(position, i);
  510. let machine = mappings[i - 1][segment];
  511. if (machine != undefined) {
  512. kana.push(original);
  513. let nextMachine = machine.clone();
  514. if (machines.length > 0) {
  515. let prevMachine = machines[machines.length - 1];
  516. prevMachine.nextMachine = nextMachine;
  517. }
  518. machines.push(nextMachine);
  519. position += i - 1;
  520. break;
  521. }
  522. }
  523. // even if we don't find a match, keep progressing
  524. // unmapped characters will be ignored
  525. position += 1;
  526. }
  527. this.kana = kana;
  528. this.stateMachines = machines;
  529. this.currentIndex = 0;
  530. }
  531. map<T>(func: (s: string, m: StateMachine) => T): T[] {
  532. let result: T[] = [];
  533. for (let i = 0; i < this.kana.length; ++i) {
  534. result.push(func(this.kana[i], this.stateMachines[i]));
  535. }
  536. return result;
  537. }
  538. handleInput(input: string): boolean {
  539. if (this.currentIndex >= this.stateMachines.length) return false;
  540. let currentMachine = this.stateMachines[this.currentIndex];
  541. currentMachine.transition(input);
  542. while (currentMachine.isFinished()) {
  543. this.currentIndex += 1;
  544. currentMachine = this.stateMachines[this.currentIndex];
  545. if (currentMachine == null) {
  546. return true;
  547. }
  548. }
  549. return this.currentIndex >= this.stateMachines.length;
  550. }
  551. isFinished(): boolean {
  552. return this.currentIndex >= this.stateMachines.length;
  553. }
  554. getRemainingInput(): string {
  555. let remaining = '';
  556. for (let i = this.currentIndex; i < this.stateMachines.length; ++i) {
  557. remaining += this.stateMachines[i].getDisplay();
  558. }
  559. return remaining;
  560. }
  561. }