kana.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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 f(vowel: StateMachine): StateMachine {
  72. const end = vowel.initialState.display;
  73. return mergeMachines(literal(`f${end}`, 0), appendMachines(fu(), vowel));
  74. }
  75. function v(vowel: StateMachine): StateMachine {
  76. const end = vowel.initialState.display;
  77. return mergeMachines(
  78. literal(`v${end}`, 0),
  79. appendMachines(literal('vu'), vowel)
  80. );
  81. }
  82. function y(base: StateMachine, vowel: StateMachine): StateMachine {
  83. const newState = base.initialState.transform((state) => {
  84. return [
  85. state.display.replace(/i$/, vowel.initialState.display),
  86. state.meta,
  87. ];
  88. });
  89. const newVowelState = vowel.initialState.transform((state) => {
  90. return [state.display, state.meta + 1];
  91. });
  92. for (const state of newState.closure()) {
  93. for (const key in state.transitions) {
  94. const nextState = state.transitions[key];
  95. if (nextState.display === vowel.initialState.display) {
  96. state.transitions[key] = newVowelState;
  97. }
  98. }
  99. }
  100. return mergeMachines(
  101. new StateMachine(newState),
  102. appendMachines(base, SMALL_KANA_MAPPING.get(vowel)!)
  103. );
  104. }
  105. function ji(): StateMachine {
  106. return state.buildFromTransitions('ji', [
  107. t('ji', 'j', 'i'),
  108. t('ji', 'z', 'i'),
  109. t('i', 'i', '', 1),
  110. ]);
  111. }
  112. function sh(vowel: StateMachine): StateMachine {
  113. const end = vowel.initialState.display.replace(/^y/, '');
  114. let source = 'sh' + end;
  115. let middle = 'h' + end;
  116. return mergeMachines(
  117. state.buildFromTransitions(source, [
  118. t(source, 's', middle, 1),
  119. t(middle, 'h', end),
  120. t(middle, 'y', end),
  121. t(end, end, '', 2),
  122. ]),
  123. appendMachines(shi(), SMALL_KANA_MAPPING.get(vowel)!)
  124. );
  125. }
  126. function ch(vowel: StateMachine): StateMachine {
  127. const end = vowel.initialState.display.replace(/^y/, '');
  128. let source = 'ch' + end;
  129. let middle = 'h' + end;
  130. let altMiddle = 'y' + end;
  131. return mergeMachines(
  132. state.buildFromTransitions(source, [
  133. t(source, 'c', middle),
  134. t(middle, 'h', end, 1),
  135. t(source, 't', altMiddle, 1),
  136. t(altMiddle, 'y', end),
  137. t(end, end, '', 2),
  138. ]),
  139. appendMachines(chi(), SMALL_KANA_MAPPING.get(vowel)!)
  140. );
  141. }
  142. function j(vowel: StateMachine): StateMachine {
  143. const end = vowel.initialState.display.replace(/^y/, '');
  144. return mergeMachines(literal(`j${end}`, 0), y(ji(), vowel));
  145. }
  146. function smallTsu(base: StateMachine): StateMachine {
  147. let { display, transitions } = base.initialState;
  148. const newState = new State(display.charAt(0) + display, 0);
  149. Object.keys(transitions).forEach((k) => {
  150. const nextState = transitions[k];
  151. const intermediateState = new State(k, 0);
  152. intermediateState.addTransition(k, new State('', 1));
  153. newState.addTransition(k, appendStates(intermediateState, nextState));
  154. });
  155. return mergeMachines(
  156. new StateMachine(newState),
  157. appendMachines(SMALL_KANA_MAPPING.get(KANA_MAPPING['つ'])!, base)
  158. );
  159. }
  160. function smallKana(base: StateMachine): StateMachine {
  161. let newState = base.initialState.clone();
  162. newState.addTransition('l', base.initialState);
  163. newState.addTransition('x', base.initialState);
  164. return new StateMachine(newState);
  165. }
  166. function n(base: StateMachine): StateMachine {
  167. const allowSingleN = ['n', 'a', 'i', 'u', 'e', 'o', 'y'].every((k) => {
  168. return base.initialState.transition(k) === undefined;
  169. });
  170. if (allowSingleN) {
  171. return mergeMachines(
  172. appendMachines(literal('n'), base),
  173. appendMachines(literal('nn'), base)
  174. );
  175. } else {
  176. throw new Error(
  177. `Invalid base ${base.initialState.display}, just defer to literal`
  178. );
  179. }
  180. }
  181. interface KanaMapping {
  182. [index: string]: StateMachine;
  183. }
  184. interface StringMapping {
  185. [index: string]: string;
  186. }
  187. const WHITESPACE = state.buildFromTransitions('_', [
  188. t('_', '_', ''),
  189. t('_', ' ', ''),
  190. ]);
  191. const KATAKANA_MAPPING: StringMapping = {
  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. ギ: 'ぎ',
  242. グ: 'ぐ',
  243. ゲ: 'げ',
  244. ゴ: 'ご',
  245. ザ: 'ざ',
  246. ジ: 'じ',
  247. ズ: 'ず',
  248. ゼ: 'ぜ',
  249. ゾ: 'ぞ',
  250. ダ: 'だ',
  251. ヂ: 'ぢ',
  252. ヅ: 'づ',
  253. デ: 'で',
  254. ド: 'ど',
  255. バ: 'ば',
  256. ビ: 'び',
  257. ブ: 'ぶ',
  258. ベ: 'べ',
  259. ボ: 'ぼ',
  260. パ: 'ぱ',
  261. ピ: 'ぴ',
  262. プ: 'ぷ',
  263. ペ: 'ぺ',
  264. ポ: 'ぽ',
  265. ヴ: 'ゔ',
  266. ァ: 'ぁ',
  267. ィ: 'ぃ',
  268. ゥ: 'ぅ',
  269. ェ: 'ぇ',
  270. ォ: 'ぉ',
  271. ャ: 'ゃ',
  272. ュ: 'ゅ',
  273. ョ: 'ょ',
  274. ッ: 'っ',
  275. };
  276. export const KANA_MAPPING: KanaMapping = {
  277. あ: literal('a'),
  278. い: literal('i'),
  279. う: literal('u'),
  280. え: literal('e'),
  281. お: literal('o'),
  282. か: literal('ka'),
  283. き: literal('ki'),
  284. く: literal('ku'),
  285. け: literal('ke'),
  286. こ: literal('ko'),
  287. さ: literal('sa'),
  288. し: shi(),
  289. す: literal('su'),
  290. せ: literal('se'),
  291. そ: literal('so'),
  292. た: literal('ta'),
  293. ち: chi(),
  294. つ: tsu(),
  295. て: literal('te'),
  296. と: literal('to'),
  297. な: literal('na'),
  298. に: literal('ni'),
  299. ぬ: literal('nu'),
  300. ね: literal('ne'),
  301. の: literal('no'),
  302. は: literal('ha'),
  303. ひ: literal('hi'),
  304. ふ: fu(),
  305. へ: literal('he'),
  306. ほ: literal('ho'),
  307. ま: literal('ma'),
  308. み: literal('mi'),
  309. む: literal('mu'),
  310. め: literal('me'),
  311. も: literal('mo'),
  312. や: literal('ya'),
  313. ゆ: literal('yu'),
  314. よ: literal('yo'),
  315. ら: literal('ra'),
  316. り: literal('ri'),
  317. る: literal('ru'),
  318. れ: literal('re'),
  319. ろ: literal('ro'),
  320. わ: literal('wa'),
  321. ゐ: literal('i'),
  322. ゑ: literal('e'),
  323. を: literal('wo'),
  324. ん: literal('nn'),
  325. が: literal('ga'),
  326. ぎ: literal('gi'),
  327. ぐ: literal('gu'),
  328. げ: literal('ge'),
  329. ご: literal('go'),
  330. ざ: literal('za'),
  331. じ: ji(),
  332. ず: literal('zu'),
  333. ぜ: literal('ze'),
  334. ぞ: literal('zo'),
  335. だ: literal('da'),
  336. ぢ: literal('di'),
  337. づ: literal('du'),
  338. で: literal('de'),
  339. ど: literal('do'),
  340. ば: literal('ba'),
  341. び: literal('bi'),
  342. ぶ: literal('bu'),
  343. べ: literal('be'),
  344. ぼ: literal('bo'),
  345. ぱ: literal('pa'),
  346. ぴ: literal('pi'),
  347. ぷ: literal('pu'),
  348. ぺ: literal('pe'),
  349. ぽ: literal('po'),
  350. ゔ: literal('vu'),
  351. ー: literal('-'),
  352. ' ': WHITESPACE,
  353. };
  354. 'abcdefghijklmnopqrstuvwxyz'.split('').forEach((letter) => {
  355. KANA_MAPPING[letter] = literal(letter);
  356. });
  357. const SMALL_KANA_MAPPING: Map<StateMachine, StateMachine> = new Map();
  358. [
  359. ['ぁ', 'あ'],
  360. ['ぃ', 'い'],
  361. ['ぅ', 'う'],
  362. ['ぇ', 'え'],
  363. ['ぉ', 'お'],
  364. ['ヵ', 'か'],
  365. ['っ', 'つ'],
  366. ['ゃ', 'や'],
  367. ['ゅ', 'ゆ'],
  368. ['ょ', 'よ'],
  369. ].forEach((pair) => {
  370. let [small, big] = pair;
  371. KANA_MAPPING[small] = smallKana(KANA_MAPPING[big]);
  372. SMALL_KANA_MAPPING.set(KANA_MAPPING[big], KANA_MAPPING[small]);
  373. });
  374. Object.assign(KANA_MAPPING, {
  375. きゃ: y(KANA_MAPPING['き'], KANA_MAPPING['や']),
  376. きゅ: y(KANA_MAPPING['き'], KANA_MAPPING['ゆ']),
  377. きょ: y(KANA_MAPPING['き'], KANA_MAPPING['よ']),
  378. しゃ: sh(KANA_MAPPING['や']),
  379. しゅ: sh(KANA_MAPPING['ゆ']),
  380. しょ: sh(KANA_MAPPING['よ']),
  381. ちゃ: ch(KANA_MAPPING['や']),
  382. ちゅ: ch(KANA_MAPPING['ゆ']),
  383. ちょ: ch(KANA_MAPPING['よ']),
  384. にゃ: y(KANA_MAPPING['に'], KANA_MAPPING['や']),
  385. にゅ: y(KANA_MAPPING['に'], KANA_MAPPING['ゆ']),
  386. にょ: y(KANA_MAPPING['に'], KANA_MAPPING['よ']),
  387. ひゃ: y(KANA_MAPPING['ひ'], KANA_MAPPING['や']),
  388. ひゅ: y(KANA_MAPPING['ひ'], KANA_MAPPING['ゆ']),
  389. ひょ: y(KANA_MAPPING['ひ'], KANA_MAPPING['よ']),
  390. みゃ: y(KANA_MAPPING['み'], KANA_MAPPING['や']),
  391. みゅ: y(KANA_MAPPING['み'], KANA_MAPPING['ゆ']),
  392. みょ: y(KANA_MAPPING['み'], KANA_MAPPING['よ']),
  393. りゃ: y(KANA_MAPPING['り'], KANA_MAPPING['や']),
  394. りゅ: y(KANA_MAPPING['り'], KANA_MAPPING['ゆ']),
  395. りょ: y(KANA_MAPPING['り'], KANA_MAPPING['よ']),
  396. ぎゃ: y(KANA_MAPPING['ぎ'], KANA_MAPPING['や']),
  397. ぎゅ: y(KANA_MAPPING['ぎ'], KANA_MAPPING['ゆ']),
  398. ぎょ: y(KANA_MAPPING['ぎ'], KANA_MAPPING['よ']),
  399. じゃ: j(KANA_MAPPING['や']),
  400. じゅ: j(KANA_MAPPING['ゆ']),
  401. じょ: j(KANA_MAPPING['よ']),
  402. ぢゃ: y(KANA_MAPPING['ぢ'], KANA_MAPPING['や']),
  403. ぢゅ: y(KANA_MAPPING['ぢ'], KANA_MAPPING['ゆ']),
  404. ぢょ: y(KANA_MAPPING['ぢ'], KANA_MAPPING['よ']),
  405. びゃ: y(KANA_MAPPING['び'], KANA_MAPPING['や']),
  406. びゅ: y(KANA_MAPPING['び'], KANA_MAPPING['ゆ']),
  407. びょ: y(KANA_MAPPING['び'], KANA_MAPPING['よ']),
  408. ぴゃ: y(KANA_MAPPING['ぴ'], KANA_MAPPING['や']),
  409. ぴゅ: y(KANA_MAPPING['ぴ'], KANA_MAPPING['ゆ']),
  410. ぴょ: y(KANA_MAPPING['ぴ'], KANA_MAPPING['よ']),
  411. ふぁ: f(KANA_MAPPING['ぁ']),
  412. ふぃ: f(KANA_MAPPING['ぃ']),
  413. ふぇ: f(KANA_MAPPING['ぇ']),
  414. ふぉ: f(KANA_MAPPING['ぉ']),
  415. ゔぁ: v(KANA_MAPPING['ぁ']),
  416. ゔぃ: v(KANA_MAPPING['ぃ']),
  417. ゔぇ: v(KANA_MAPPING['ぇ']),
  418. ゔぉ: v(KANA_MAPPING['ぉ']),
  419. });
  420. [
  421. 'か',
  422. 'き',
  423. 'く',
  424. 'け',
  425. 'こ',
  426. 'さ',
  427. 'し',
  428. 'す',
  429. 'せ',
  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. 'ぺ',
  465. 'ぽ',
  466. 'ゔ',
  467. ].forEach((kana) => {
  468. KANA_MAPPING['っ' + kana] = smallTsu(KANA_MAPPING[kana]);
  469. KANA_MAPPING['ん' + kana] = n(KANA_MAPPING[kana]);
  470. });
  471. [
  472. 'きゃ',
  473. 'きゅ',
  474. 'きょ',
  475. 'しゃ',
  476. 'しゅ',
  477. 'しょ',
  478. 'ちゃ',
  479. 'ちゅ',
  480. 'ちょ',
  481. 'ぎゃ',
  482. 'ぎゅ',
  483. 'ぎょ',
  484. 'じゃ',
  485. 'じゅ',
  486. 'じょ',
  487. 'ぢゃ',
  488. 'ぢゅ',
  489. 'ぢょ',
  490. 'びゃ',
  491. 'びゅ',
  492. 'びょ',
  493. 'ぴゃ',
  494. 'ぴゅ',
  495. 'ぴょ',
  496. 'ふぁ',
  497. 'ふぃ',
  498. 'ふぇ',
  499. 'ふぉ',
  500. 'ゔぁ',
  501. 'ゔぃ',
  502. 'ゔぇ',
  503. 'ゔぉ',
  504. ].forEach((kana) => {
  505. KANA_MAPPING['っ' + kana] = smallTsu(KANA_MAPPING[kana]);
  506. KANA_MAPPING['ん' + kana] = n(KANA_MAPPING[kana]);
  507. });
  508. /**
  509. * This normalizes input for matching. All alphabet is lower-cased, katakana
  510. * is transformed to hiragana. All whitespace is now just a space. We take
  511. * care to not change the length of the string as we have to match it
  512. * one-for-one so we can display the original source kana.
  513. */
  514. export function normalizeInput(input: string): string {
  515. return input
  516. .toLowerCase()
  517. .split('')
  518. .map((letter) => {
  519. let transform = KATAKANA_MAPPING[letter];
  520. if (transform !== undefined) {
  521. return transform;
  522. } else if (/\s/.test(letter)) {
  523. return ' ';
  524. } else {
  525. return letter;
  526. }
  527. })
  528. .join('');
  529. }
  530. export class KanaInputState {
  531. kana: string[];
  532. stateMachines: StateMachine[];
  533. currentIndex: number;
  534. constructor(input: string) {
  535. let kana: string[] = [];
  536. let machines: StateMachine[] = [];
  537. let position = 0;
  538. // we pad the input so checking 3 at a time is simpler
  539. let normalized = normalizeInput(input) + ' ';
  540. while (position < input.length) {
  541. // we check substrings of length 3, 2, then 1
  542. for (let i = 3; i > 0; --i) {
  543. let original = input.substr(position, i);
  544. let segment = normalized.substr(position, i);
  545. let machine = KANA_MAPPING[segment];
  546. if (machine != undefined) {
  547. kana.push(original);
  548. let nextMachine = machine.clone();
  549. if (machines.length > 0) {
  550. let prevMachine = machines[machines.length - 1];
  551. prevMachine.nextMachine = nextMachine;
  552. }
  553. machines.push(nextMachine);
  554. position += i - 1;
  555. break;
  556. }
  557. }
  558. // even if we don't find a match, keep progressing
  559. // unmapped characters will be ignored
  560. position += 1;
  561. }
  562. this.kana = kana;
  563. this.stateMachines = machines;
  564. this.currentIndex = 0;
  565. }
  566. map<T>(func: (s: string, m: StateMachine) => T): T[] {
  567. let result: T[] = [];
  568. for (let i = 0; i < this.kana.length; ++i) {
  569. result.push(func(this.kana[i], this.stateMachines[i]));
  570. }
  571. return result;
  572. }
  573. handleInput(input: string): boolean {
  574. if (this.currentIndex >= this.stateMachines.length) return false;
  575. let currentMachine = this.stateMachines[this.currentIndex];
  576. currentMachine.transition(input);
  577. while (currentMachine.isFinished()) {
  578. this.currentIndex += 1;
  579. currentMachine = this.stateMachines[this.currentIndex];
  580. if (currentMachine == null) {
  581. return true;
  582. }
  583. }
  584. return this.currentIndex >= this.stateMachines.length;
  585. }
  586. isFinished(): boolean {
  587. return this.currentIndex >= this.stateMachines.length;
  588. }
  589. getRemainingInput(): string {
  590. let remaining = '';
  591. for (let i = this.currentIndex; i < this.stateMachines.length; ++i) {
  592. remaining += this.stateMachines[i].getDisplay();
  593. }
  594. return remaining;
  595. }
  596. }