feat(desktop): built-in Han/Eng layout auto-switching, terminal/Vim support, and Unicode input
This commit is contained in:
parent
1da04b9e46
commit
a3ac44da2b
109 changed files with 8234 additions and 242 deletions
34
packages/core/__tests__/address-input.test.ts
Normal file
34
packages/core/__tests__/address-input.test.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
// packages/core/__tests__/address-input.test.ts
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isAddressInput } from '../src/input-intelligence'
|
||||
|
||||
describe('isAddressInput', () => {
|
||||
it('주소·경로·쿼리를 치는 중이면 true', () => {
|
||||
for (const prefix of [
|
||||
'https://youtube.com/shorts/32P7',
|
||||
'여기 봐 www.naver',
|
||||
'haramlog.app/ja/beta',
|
||||
'mail.google.com/mail/u/0/#inbox',
|
||||
'D:/workspace/맛집추천',
|
||||
'./src/main',
|
||||
'd3x9Z0iqC2/?stkn=em1z',
|
||||
'page?utm_source=meta'
|
||||
]) {
|
||||
expect(isAddressInput(prefix), prefix).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('문장·숫자·띄어 쓴 뒤는 false', () => {
|
||||
for (const prefix of [
|
||||
'언제쯤일까?',
|
||||
'1/2 정도만',
|
||||
'네.좋아요',
|
||||
'v1.10.1 배포',
|
||||
'오늘 회의는 내일',
|
||||
'https://youtube.com 이거 봐 ',
|
||||
'ok'
|
||||
]) {
|
||||
expect(isAddressInput(prefix), prefix).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
|
@ -49,9 +49,11 @@ describe('케어렛 신뢰도', () => {
|
|||
expect(isEditAtTextEnd('aXb', 'ab')).toBe(false)
|
||||
})
|
||||
|
||||
it('값 끝에 줄끝 문자를 붙여 주는 입력칸(RichEdit·카카오톡)에서도 끝 편집을 알아본다', () => {
|
||||
it('값 끝에 줄끝 문자를 붙여 주는 입력칸(RichEdit·카카오톡)이나 공백 끝 교체에서도 끝 편집을 알아본다', () => {
|
||||
expect(isEditAtTextEnd('안녕\r', '안녕하\r')).toBe(true)
|
||||
expect(isEditAtTextEnd('오늘 회의 자\r\n', '오늘 회의 자료\r\n')).toBe(true)
|
||||
expect(isEditAtTextEnd('dkssud ', '안녕 ')).toBe(true)
|
||||
expect(isEditAtTextEnd('아 된다. ㅗ디ㅣㅐ ', '아 된다. hello ')).toBe(true)
|
||||
// 줄끝 문자 앞의 진짜 중간 편집은 여전히 중간 편집이다
|
||||
expect(isEditAtTextEnd('첫 문장. 둘째\r', '첫 문장이. 둘째\r')).toBe(false)
|
||||
})
|
||||
|
|
|
|||
54
packages/core/__tests__/personal-ngram.test.ts
Normal file
54
packages/core/__tests__/personal-ngram.test.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
// packages/core/__tests__/personal-ngram.test.ts
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { PersonalNgramModel, predictPersonalContinuation } from '../src/personal-ngram'
|
||||
|
||||
function model(...texts: string[]): PersonalNgramModel {
|
||||
const built = new PersonalNgramModel()
|
||||
for (const text of texts) built.addText(text)
|
||||
return built
|
||||
}
|
||||
|
||||
describe('PersonalNgramModel', () => {
|
||||
it('단어를 끝냈으면 자주 이어 쓴 다음 어절과 짧은 구를 낸다', () => {
|
||||
const m = model('링크에서 확인할 수 있어요.', '앱에서 확인할 수 있어요.', '여기서 확인할 수 있어요')
|
||||
expect(m.predict('설정에서 확인할 ')).toMatchObject({ text: '수 있어요', joint: 'separate', support: 3 })
|
||||
})
|
||||
|
||||
it('단어 중간이면 그 어절의 나머지를 붙여 낸다', () => {
|
||||
const m = model('아기를 토닥여 줘요', '조금 토닥여 줬어요', '다시 토닥여 줘요')
|
||||
expect(m.predict('살살 토닥')).toMatchObject({ text: '여 줘요', joint: 'attach' })
|
||||
})
|
||||
|
||||
it('지지 횟수가 모자라거나 갈리면 내지 않는다', () => {
|
||||
expect(model('확인할 수 있어요').predict('확인할 ')).toBeNull()
|
||||
const split = model('그럼 이따가 봐', '그럼 내일 봐', '그럼 다음에 봐', '그럼 이따가 연락할게')
|
||||
expect(split.predict('그럼 ', { minConfidence: 0.6 })).toBeNull()
|
||||
expect(split.predict('그럼 ')).toMatchObject({ text: '이따가', support: 2 })
|
||||
})
|
||||
|
||||
it('문장 경계를 넘지 않고, 새 문장의 첫 어절은 예측하지 않는다', () => {
|
||||
const m = model('좋아요. 내일 봐요', '좋아요. 내일 봐요')
|
||||
expect(m.predict('좋아요. ')).toBeNull()
|
||||
expect(m.predict('좋아요 ')).toBeNull()
|
||||
})
|
||||
|
||||
it('따옴표·쉼표는 비교에서 떼고 대소문자를 가리지 않는다', () => {
|
||||
const m = model('Thank you so much', 'thank you, so much')
|
||||
expect(m.predict('Thank ')).toMatchObject({ text: 'you so much' })
|
||||
})
|
||||
|
||||
it('앱 예측: 공백 없이 멈췄어도 늘일 어절이 없으면 다음 어절을 띄어 쓰기로 낸다 ("그리고")', () => {
|
||||
const m = model('그리고 다음에 보자', '그리고 다음에 해', '그리고 오늘은 쉬자')
|
||||
expect(predictPersonalContinuation(m, '아 그리고')).toMatchObject({ text: '다음에', joint: 'separate' })
|
||||
})
|
||||
|
||||
it('앱 예측: 다음 어절이 갈려도 가장 흔한 것 하나는 내고, 둘째 어절은 확신할 때만 붙인다', () => {
|
||||
const m = model('그리고 다음에 보자', '그리고 다음에 해', '그리고 오늘은 쉬자', '그리고 내일 가자')
|
||||
expect(predictPersonalContinuation(m, '그리고 ')?.text).toBe('다음에')
|
||||
})
|
||||
|
||||
it('maxWords 까지만 늘인다', () => {
|
||||
const m = model('하나 둘 셋 넷 다섯', '하나 둘 셋 넷 다섯')
|
||||
expect(m.predict('하나 ', { maxWords: 2 })?.text).toBe('둘 셋')
|
||||
})
|
||||
})
|
||||
56
packages/core/__tests__/suggestion-confidence.test.ts
Normal file
56
packages/core/__tests__/suggestion-confidence.test.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
// packages/core/__tests__/suggestion-confidence.test.ts
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { copiesContext, cutByConfidence } from '../src/suggestion-confidence'
|
||||
|
||||
const t = (token: string, logprob: number) => ({ token, logprob })
|
||||
|
||||
describe('cutByConfidence', () => {
|
||||
it('첫 어절이 자신 있으면 확률이 꺾이는 어절 앞까지 남긴다', () => {
|
||||
const tokens = [t(' 수', -0.05), t(' 있', -0.2), t('어요', -0.1), t(' 그런데', -2.5), t(' 다음', -0.1)]
|
||||
expect(cutByConfidence(tokens)).toEqual({ keepChars: ' 수 있어요'.length, firstWordLogprob: -0.05 })
|
||||
})
|
||||
|
||||
it('첫 어절 확률 합이 낮으면 버린다', () => {
|
||||
expect(cutByConfidence([t(' 다음', -0.6), t('에', -0.5), t(' 봐', -0.1)])).toBeNull()
|
||||
})
|
||||
|
||||
it('어절 중간 토큰에서 꺾이면 그 어절을 통째로 뺀다', () => {
|
||||
const tokens = [t(' 내일', -0.1), t(' 오', -0.2), t('후', -1.5)]
|
||||
expect(cutByConfidence(tokens)?.keepChars).toBe(' 내일'.length)
|
||||
})
|
||||
|
||||
it('첫 어절 중간에서 꺾이면 남는 게 없어 버린다', () => {
|
||||
expect(cutByConfidence([t(' 내', -0.1), t('일', -1.2)])).toBeNull()
|
||||
})
|
||||
|
||||
it('문장 끝 부호에서 멈춘다', () => {
|
||||
const tokens = [t(' 좋아요', -0.1), t('.', -0.05), t(' 그럼', -0.1)]
|
||||
expect(cutByConfidence(tokens)?.keepChars).toBe(' 좋아요.'.length)
|
||||
})
|
||||
|
||||
it('단어에 붙여 쓰는 첫 토큰(단어 중간 이어쓰기)도 첫 어절로 센다', () => {
|
||||
expect(cutByConfidence([t('어요', -0.2), t(' 그럼', -0.3)])).toEqual({
|
||||
keepChars: '어요 그럼'.length,
|
||||
firstWordLogprob: -0.2
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('copiesContext', () => {
|
||||
it('후보 앞부분이 문맥에 그대로 있으면 베낀 것', () => {
|
||||
expect(copiesContext('00달러 이렇게만 나오고 있거든.', '지금 결제창에 00달러 이렇게만 나오고 있거든. 확인해 줘')).toBe(true)
|
||||
})
|
||||
it('짧은 후보나 새 글은 아니다', () => {
|
||||
expect(copiesContext('수 있어요', '확인할 수 있어요')).toBe(false)
|
||||
expect(copiesContext('내일 오후에 다시 볼게', '오늘은 바빠서')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('splitFirstWord', () => {
|
||||
it('첫 어절(문장부호 포함)과 나머지로 나눈다', async () => {
|
||||
const { splitFirstWord } = await import('../src/suggestion-text')
|
||||
expect(splitFirstWord(' 내일 오후에 볼게.')).toEqual({ word: '내일', rest: '오후에 볼게.' })
|
||||
expect(splitFirstWord('좋아요, 그럼')).toEqual({ word: '좋아요,', rest: '그럼' })
|
||||
expect(splitFirstWord('볼게.')).toEqual({ word: '볼게.', rest: '' })
|
||||
})
|
||||
})
|
||||
|
|
@ -102,6 +102,18 @@ describe('extractContinuation', () => {
|
|||
extractContinuation('첨부 파일 검토해 보시고 의견 주세요.', { mode: 'complete-sentence', prefill: '첨부 파일 검토해 보시고' })?.text
|
||||
).toBe('의견 주세요.')
|
||||
})
|
||||
|
||||
it('프롬프트 지시문("검색어입니다.", "키워드 몇 개로만 짧게 이어 쓰세요.")을 되풀이한 출력은 즉시 버린다', () => {
|
||||
expect(
|
||||
extractContinuation(' 검색어입니다.', { mode: 'complete-sentence', prefill: '탭 추가 @ 기호' })
|
||||
).toBeNull()
|
||||
expect(
|
||||
extractContinuation(' 검색어 키워드 몇 개로만 짧게 이어 쓰세요.', {
|
||||
mode: 'complete-sentence',
|
||||
prefill: '탭 추가 @ 기호'
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('문서 사실', () => {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,13 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
import { decideSuggestion, extractTerminalPromptPrefix, isTerminalApp } from '../src/input-intelligence'
|
||||
import {
|
||||
TerminalKeystrokeTracker,
|
||||
composeHangul2Set,
|
||||
decideSuggestion,
|
||||
extractTerminalActiveContext,
|
||||
extractTerminalPromptPrefix,
|
||||
isTerminalApp,
|
||||
isTerminalOrDeveloperSurface
|
||||
} from '../src/input-intelligence'
|
||||
|
||||
describe('terminal prompt extraction', () => {
|
||||
it('takes the Claude Code input line and ignores the status line below it', () => {
|
||||
|
|
@ -35,10 +43,291 @@ describe('terminal prompt extraction', () => {
|
|||
expect(extractTerminalPromptPrefix('output\n> ')).toBe('')
|
||||
})
|
||||
|
||||
it('recognises terminal apps', () => {
|
||||
it('recognises terminal apps and developer surfaces', () => {
|
||||
expect(isTerminalApp('WindowsTerminal.exe')).toBe(true)
|
||||
expect(isTerminalApp('Kitedesk.exe')).toBe(true)
|
||||
expect(isTerminalApp('wezterm-gui.exe')).toBe(true)
|
||||
expect(isTerminalApp('neovide.exe')).toBe(true)
|
||||
expect(isTerminalApp('KakaoTalk.exe')).toBe(false)
|
||||
expect(isTerminalApp(null)).toBe(false)
|
||||
expect(isTerminalOrDeveloperSurface('WindowsTerminal.exe')).toBe(true)
|
||||
expect(isTerminalOrDeveloperSurface('Kitedesk.exe')).toBe(true)
|
||||
expect(isTerminalOrDeveloperSurface('Code.exe')).toBe(true)
|
||||
expect(isTerminalOrDeveloperSurface('Agent Switchboard.exe')).toBe(true)
|
||||
expect(isTerminalOrDeveloperSurface('KakaoTalk.exe')).toBe(false)
|
||||
})
|
||||
|
||||
it('extracts active Vim insert line, command line, and normal mode from terminal screen snapshots', () => {
|
||||
const prevVim = ['hello world', '~', '~', '-- INSERT -- 1,12 All'].join(
|
||||
'\n'
|
||||
)
|
||||
const currVim = [
|
||||
'hello world dkssudgktpdy',
|
||||
'~',
|
||||
'~',
|
||||
'-- INSERT -- 1,25 All'
|
||||
].join('\n')
|
||||
|
||||
const insertCtx = extractTerminalActiveContext(prevVim, currVim)
|
||||
expect(insertCtx).toEqual({
|
||||
prefix: 'hello world dkssudgktpdy',
|
||||
caretReliable: true,
|
||||
vimMode: 'insert',
|
||||
isVimScreen: true
|
||||
})
|
||||
|
||||
const normalScreen = ['hello world', '~', '~', ' 1,11 All'].join(
|
||||
'\n'
|
||||
)
|
||||
const normalCtx = extractTerminalActiveContext(currVim, normalScreen)
|
||||
expect(normalCtx.vimMode).toBe('normal')
|
||||
expect(normalCtx.caretReliable).toBe(false)
|
||||
|
||||
const cmdScreen = ['hello world', '~', '~', ':ㅈㅂ'].join('\n')
|
||||
const cmdCtx = extractTerminalActiveContext(normalScreen, cmdScreen)
|
||||
expect(cmdCtx).toEqual({
|
||||
prefix: ':ㅈㅂ',
|
||||
caretReliable: true,
|
||||
vimMode: 'command',
|
||||
isVimScreen: true
|
||||
})
|
||||
})
|
||||
|
||||
it('composes 2-set Hangul and tracks Vim modes + trailing spaces in TerminalKeystrokeTracker', () => {
|
||||
expect(composeHangul2Set('dkssudgktpdy')).toBe('안녕하세요')
|
||||
expect(composeHangul2Set('wq')).toBe('ㅈㅂ')
|
||||
expect(composeHangul2Set('gtihubdp')).toBe('ㅎ샤ㅗㅕㅠ에')
|
||||
|
||||
const tracker = new TerminalKeystrokeTracker()
|
||||
const pressChar = (ch: string, koreanIme = false): void => {
|
||||
const upper = ch.toUpperCase()
|
||||
const vk = ch === ':' ? 0xba : ch === ' ' ? 0x20 : upper.charCodeAt(0)
|
||||
const shift = ch === ':' || (ch >= 'A' && ch <= 'Z')
|
||||
tracker.onKeyDown({
|
||||
hwnd: 101,
|
||||
vk,
|
||||
shift,
|
||||
ctrl: false,
|
||||
alt: false,
|
||||
meta: false,
|
||||
koreanIme
|
||||
})
|
||||
}
|
||||
|
||||
// Esc → Vim Normal mode (h/j/k/l ignored) → 'i' → Insert mode → 'dkssudgktpdy '
|
||||
tracker.onKeyDown({ hwnd: 101, vk: 0x1b, shift: false, ctrl: false, alt: false, meta: false })
|
||||
for (const ch of 'jjlli') pressChar(ch, false)
|
||||
expect(tracker.vimMode).toBe('insert')
|
||||
for (const ch of 'dkssudgktpdy ') pressChar(ch, false)
|
||||
expect(tracker.getSnapshot(101)).toEqual({
|
||||
prefix: 'dkssudgktpdy ',
|
||||
caretReliable: true,
|
||||
isComposing: false,
|
||||
vimMode: 'insert'
|
||||
})
|
||||
|
||||
// Windows Terminal strips trailing space from screen rows; reconcileWithScreen restores it
|
||||
const screenWithoutSpace = ['dkssudgktpdy', '~', '-- INSERT --'].join('\n')
|
||||
expect(tracker.reconcileWithScreen(screenWithoutSpace)).toEqual({
|
||||
prefix: 'dkssudgktpdy ',
|
||||
caretReliable: true,
|
||||
isComposing: false,
|
||||
vimMode: 'insert'
|
||||
})
|
||||
|
||||
// Programmatic replacement updates the tracked buffer
|
||||
tracker.applyReplacement('dkssudgktpdy '.length, '안녕하세요 ')
|
||||
expect(tracker.currentPrefix()).toBe('안녕하세요 ')
|
||||
|
||||
// Esc → ':' → 'wq' in Korean IME → ':ㅈㅂ'
|
||||
tracker.onKeyDown({ hwnd: 101, vk: 0x1b, shift: false, ctrl: false, alt: false, meta: false })
|
||||
expect(tracker.vimMode).toBe('normal')
|
||||
pressChar(':', true)
|
||||
expect(tracker.vimMode).toBe('command')
|
||||
pressChar('w', true)
|
||||
pressChar('q', true)
|
||||
expect(tracker.getSnapshot(101)).toEqual({
|
||||
prefix: ':ㅈㅂ',
|
||||
caretReliable: true,
|
||||
isComposing: true,
|
||||
vimMode: 'command'
|
||||
})
|
||||
})
|
||||
|
||||
it('reconciles IME VK_PROCESSKEY (vk=null) Hangul after : in Vim command line and shell prompts under nvim title', () => {
|
||||
const tracker = new TerminalKeystrokeTracker()
|
||||
const title = 'nvim - D3RO Terminal & Vim E2E'
|
||||
|
||||
// 1. Initial Vim normal screen
|
||||
expect(tracker.reconcileWithScreen('안녕하세요 \n~\n~\n', title)).toEqual({
|
||||
prefix: '',
|
||||
caretReliable: false,
|
||||
isComposing: false,
|
||||
vimMode: 'normal'
|
||||
})
|
||||
|
||||
// 2. ':' sent as hardware VK (0xba + Shift), followed by IME vk=null for 'ㅈ' and 'ㅂ'
|
||||
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: 0xba, shift: true, ctrl: false, alt: false, meta: false })
|
||||
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: null, shift: false, ctrl: false, alt: false, meta: false })
|
||||
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: null, shift: false, ctrl: false, alt: false, meta: false })
|
||||
|
||||
expect(tracker.reconcileWithScreen('안녕하세요 \n~\n~\n:ㅈㅂ', title)).toEqual({
|
||||
prefix: ':ㅈㅂ',
|
||||
caretReliable: true,
|
||||
isComposing: false,
|
||||
vimMode: 'command'
|
||||
})
|
||||
tracker.applyReplacement(2, 'wq')
|
||||
|
||||
// 2b. Even if a stale ':wq' snapshot was reconciled right before a new ':ㅂ!' command line,
|
||||
// the rendered ':ㅂ!' command line must win over stale ':wq:!'.
|
||||
expect(tracker.reconcileWithScreen('안녕하세요 \n~\n~\n:wq', title)).toEqual({
|
||||
prefix: ':wq',
|
||||
caretReliable: true,
|
||||
isComposing: false,
|
||||
vimMode: 'command'
|
||||
})
|
||||
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: 0xba, shift: true, ctrl: false, alt: false, meta: false })
|
||||
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: null, shift: false, ctrl: false, alt: false, meta: false })
|
||||
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: 0x31, shift: true, ctrl: false, alt: false, meta: false })
|
||||
expect(tracker.reconcileWithScreen('안녕하세요 \n~\n~\n:ㅂ!', title)).toEqual({
|
||||
prefix: ':ㅂ!',
|
||||
caretReliable: true,
|
||||
isComposing: false,
|
||||
vimMode: 'command'
|
||||
})
|
||||
|
||||
// 3. Shell prompt screen inside a window whose title still contains 'nvim'
|
||||
tracker.onPointerOrFocusChange(202)
|
||||
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: null, shift: false, ctrl: false, alt: false, meta: false })
|
||||
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: null, shift: false, ctrl: false, alt: false, meta: false })
|
||||
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: 0x20, shift: false, ctrl: false, alt: false, meta: false })
|
||||
|
||||
expect(tracker.reconcileWithScreen('Windows PowerShell\nPS D:\\workspace> 퍄ㅡ ', title)).toEqual({
|
||||
prefix: 'PS D:\\workspace> 퍄ㅡ '.replace('PS D:\\workspace> ', ''),
|
||||
caretReliable: true,
|
||||
isComposing: false,
|
||||
vimMode: null
|
||||
})
|
||||
})
|
||||
|
||||
it('reconciles xterm-helper-textarea without repeating replacements when textarea.value stays stale', () => {
|
||||
const tracker = new TerminalKeystrokeTracker()
|
||||
const hwnd = 303
|
||||
const title = 'Agent Switchboard'
|
||||
|
||||
// User types 'h','e','l','l','o',' ' while koreanIme initially reported false on keydown
|
||||
for (const vk of [0x48, 0x45, 0x4c, 0x4c, 0x4f, 0x20]) {
|
||||
tracker.onKeyDown({
|
||||
hwnd,
|
||||
windowTitle: title,
|
||||
vk,
|
||||
shift: false,
|
||||
ctrl: false,
|
||||
alt: false,
|
||||
meta: false,
|
||||
koreanIme: false
|
||||
})
|
||||
}
|
||||
|
||||
// xterm-helper-textarea receives Hangul from IME ('ㅗ디ㅣㅐ '), proving Korean IME is active
|
||||
expect(tracker.reconcileWithXtermValue('ㅗ디ㅣㅐ ', hwnd, title)).toEqual({
|
||||
prefix: 'ㅗ디ㅣㅐ ',
|
||||
caretReliable: true,
|
||||
isComposing: false,
|
||||
vimMode: null
|
||||
})
|
||||
|
||||
// TypoCorrectionService replaces 'ㅗ디ㅣㅐ ' (6 chars) with 'hello '
|
||||
tracker.applyReplacement(6, 'hello ')
|
||||
|
||||
// Next snapshot 400ms later: xterm.textarea.value is STILL 'ㅗ디ㅣㅐ ' (xterm ignores Backspace/SendInput),
|
||||
// but reconcileWithXtermValue must return 'hello ' so it never loops into 'hhhhhhhhhhhello'!
|
||||
expect(tracker.reconcileWithXtermValue('ㅗ디ㅣㅐ ', hwnd, title)).toEqual({
|
||||
prefix: 'hello ',
|
||||
caretReliable: true,
|
||||
isComposing: false,
|
||||
vimMode: null
|
||||
})
|
||||
|
||||
// User continues typing 'w','o','r','l','d',' ' while Chromium HWND still reports koreanIme: false;
|
||||
// because _imm32Supported is false, koreanIme: false does NOT override _koreanIme = true!
|
||||
for (const vk of [0x57, 0x4f, 0x52, 0x4c, 0x44, 0x20]) {
|
||||
tracker.onKeyDown({
|
||||
hwnd,
|
||||
windowTitle: title,
|
||||
vk,
|
||||
shift: false,
|
||||
ctrl: false,
|
||||
alt: false,
|
||||
meta: false,
|
||||
koreanIme: false
|
||||
})
|
||||
}
|
||||
expect(tracker.reconcileWithXtermValue('ㅗ디ㅣㅐ재깅 ', hwnd, title)).toEqual({
|
||||
prefix: 'hello 재깅 ',
|
||||
caretReliable: true,
|
||||
isComposing: false,
|
||||
vimMode: null
|
||||
})
|
||||
tracker.applyReplacement(3, 'world ')
|
||||
expect(tracker.reconcileWithXtermValue('ㅗ디ㅣㅐ재깅 ', hwnd, title)).toEqual({
|
||||
prefix: 'hello world ',
|
||||
caretReliable: true,
|
||||
isComposing: false,
|
||||
vimMode: null
|
||||
})
|
||||
|
||||
// Even if the host app clears textarea.value to '' mid-line (e.g., on Space or compositionend),
|
||||
// the active line is preserved until Enter/Ctrl+C/Esc.
|
||||
expect(tracker.reconcileWithXtermValue('', hwnd, title)).toEqual({
|
||||
prefix: 'hello world ',
|
||||
caretReliable: true,
|
||||
isComposing: false,
|
||||
vimMode: null
|
||||
})
|
||||
|
||||
// Pressing Enter (0x0D) resets the tracked line
|
||||
tracker.onKeyDown({
|
||||
hwnd,
|
||||
windowTitle: title,
|
||||
vk: 0x0d,
|
||||
shift: false,
|
||||
ctrl: false,
|
||||
alt: false,
|
||||
meta: false
|
||||
})
|
||||
expect(tracker.reconcileWithXtermValue('', hwnd, title)).toEqual({
|
||||
prefix: '',
|
||||
caretReliable: false,
|
||||
isComposing: false,
|
||||
vimMode: null
|
||||
})
|
||||
|
||||
// Pressing Ctrl+C or Esc followed by 'git' or Korean 'dd' ('ㅇㅇ') must NOT falsely enter Vim mode
|
||||
tracker.onKeyDown({
|
||||
hwnd,
|
||||
windowTitle: title,
|
||||
vk: 0x1b,
|
||||
shift: false,
|
||||
ctrl: false,
|
||||
alt: false,
|
||||
meta: false
|
||||
})
|
||||
for (const vk of [0x47, 0x49, 0x54]) {
|
||||
tracker.onKeyDown({
|
||||
hwnd,
|
||||
windowTitle: title,
|
||||
vk,
|
||||
shift: false,
|
||||
ctrl: false,
|
||||
alt: false,
|
||||
meta: false,
|
||||
koreanIme: true
|
||||
})
|
||||
}
|
||||
expect(tracker.vimMode).toBeNull()
|
||||
expect(tracker.currentPrefix()).toBe('햣')
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -78,6 +78,14 @@ describe('한영 전환 오타 판정', () => {
|
|||
expect(detectHangulTypedLatin('안녕', KO)).toBeNull()
|
||||
expect(detectHangulTypedLatin('회의', { hangul: 2, latin: 40 })).toBeNull()
|
||||
})
|
||||
|
||||
it('sometime(내ㅡㄷ샤ㅡㄷ), 연속 혼합 토큰(some샤ㅡㄷ), 영문 알파벳+조사(ㄴ가/ㄴ은)를 정확히 고친다', () => {
|
||||
expect(detectHangulTypedLatin('내ㅡㄷ샤ㅡㄷ', KO)).toBe('sometime')
|
||||
expect(detectHangulTypedLatin('some샤ㅡㄷ', KO)).toBe('sometime')
|
||||
expect(detectHangulTypedLatin('ㄴ가', KO)).toBe('s가')
|
||||
expect(detectHangulTypedLatin('ㄴ은', KO)).toBe('s은')
|
||||
expect(detectHangulTypedLatin('ㅠㅕㅎ가', KO)).toBe('bug가')
|
||||
})
|
||||
})
|
||||
|
||||
describe('늘 틀린 철자', () => {
|
||||
|
|
@ -278,3 +286,243 @@ describe('alignCorrectionToPrefix — 교정이 뜬 뒤 끝 공백만 달라져
|
|||
expect(alignCorrectionToPrefix('그ㅓ런\n', correction)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Araso 급 한/영 자동 전환 · 합성어 · 잔류 Shift · URL 런 보호', () => {
|
||||
const applyAll = (prefix: string): string => {
|
||||
const plan = planTypoReplacement(prefix, detectTypos(prefix, { includeTrailingToken: true }))
|
||||
if (!plan) return prefix
|
||||
return prefix.slice(0, prefix.length - plan.deleteCount) + plan.insertText
|
||||
}
|
||||
|
||||
it('잔류 Shift(빠른 쌍자음·복모음 뒤 대문자)를 한글로 정규화해 변환한다', () => {
|
||||
const cases: Array<[string, string]> = [
|
||||
['djEJs', '어떤'],
|
||||
['qkRNl', '바뀌'],
|
||||
['qkRNleh', '바뀌도'],
|
||||
['RNfdmf', '꿀을'],
|
||||
['EKfktj', '따라서'],
|
||||
['TkdRjvnf', '쌍꺼풀'],
|
||||
['TKdRJvnf', '쌍꺼풀'],
|
||||
['djEJfRkdy', '어떨까요'],
|
||||
['gkfRK', '할까'],
|
||||
['wlsWK', '진짜'],
|
||||
['TMfkrh', '쓰라고'],
|
||||
['qkRNjTdj', '바꿨어'],
|
||||
['ahtjflWHrdl', '모서리쪽이'],
|
||||
['RKwl', '까지'],
|
||||
['dPFmf', '예를'],
|
||||
['rOSp', '걔네'],
|
||||
['rPFks', '계란'],
|
||||
['dPDhl', '예외'],
|
||||
['dlTDj', '있어'],
|
||||
['dlTSp', '있네'],
|
||||
['qkRDp', '밖에']
|
||||
]
|
||||
for (const [keys, expected] of cases) {
|
||||
expect(detectLatinTypedHangul(keys, { hangul: 0, latin: 0 }), keys).toBe(expected)
|
||||
}
|
||||
})
|
||||
|
||||
it('잔류 Shift 로 설명되지 않는 영문 전용 대문자는 한글 문맥에서도 영문 그대로 둔다', () => {
|
||||
const words = [
|
||||
'Hello', 'API', 'TV', 'OK', 'QA', 'WE', 'QUICK', 'TEst', 'iPhone', 'GitHub', 'dHello',
|
||||
'TM', 'EU', 'RN', 'TL', 'THe', 'WHat', 'THis', 'QUery', 'tvOS', 'PCqkd', 'OAuth', 'TFxla',
|
||||
'PDF', 'WWDC'
|
||||
]
|
||||
for (const word of words) {
|
||||
expect(detectLatinTypedHangul(word, KO), word).toBeNull()
|
||||
}
|
||||
})
|
||||
|
||||
it('영단어·약어·고유명사 + 한국어 조사/어미 합성어를 분리 변환한다', () => {
|
||||
const cases: Array<[string, string]> = [
|
||||
['githubdp', 'github에'],
|
||||
['APIfmf', 'API를'],
|
||||
['commitgotj', 'commit해서'],
|
||||
['serverdptj', 'server에서'],
|
||||
['pythondmfh', 'python으로'],
|
||||
['deploygoTdj', 'deploy했어'],
|
||||
['TextEditdptj', 'TextEdit에서'],
|
||||
['Slackdptj', 'Slack에서'],
|
||||
['VSCodedptj', 'VSCode에서'],
|
||||
['GitHubdp', 'GitHub에'],
|
||||
['iPhonedptj', 'iPhone에서'],
|
||||
['TVdp', 'TV에'],
|
||||
['QAfmf', 'QA를'],
|
||||
['RNdms', 'RN은'],
|
||||
['UIrkxdmsrjs', 'UI같은건'],
|
||||
['UIdp', 'UI에'],
|
||||
['AIrk', 'AI가'],
|
||||
['githubrkxdmsep', 'github같은데'],
|
||||
['xdp', 'x에'],
|
||||
['Xfmf', 'X를']
|
||||
]
|
||||
for (const [keys, expected] of cases) {
|
||||
expect(detectLatinTypedHangul(keys, { hangul: 0, latin: 0 }), keys).toBe(expected)
|
||||
}
|
||||
})
|
||||
|
||||
it('2글자 약어의 받침 호응(TM은/TL을 vs 쓰는/씨에)을 구별한다', () => {
|
||||
for (const [keys, expected] of [
|
||||
['TMdms', 'TM은'],
|
||||
['TMdmf', 'TM을'],
|
||||
['TLdms', 'TL은'],
|
||||
['TLdmf', 'TL을'],
|
||||
['ELdl', 'EL이'],
|
||||
['ELdms', 'EL은'],
|
||||
['RJdmf', 'RJ을'],
|
||||
['RJdl', 'RJ이'],
|
||||
['TMsms', '쓰는'],
|
||||
['RNsms', '꾸는'],
|
||||
['TLdp', '씨에'],
|
||||
['Tkfdmf', '쌀을'],
|
||||
['Tlsms', '씨는']
|
||||
] as const) {
|
||||
expect(detectLatinTypedHangul(keys, { hangul: 0, latin: 0 }), keys).toBe(expected)
|
||||
}
|
||||
})
|
||||
|
||||
it('영문+한글 단어 및 한글+영문 단어 합성어를 분리 변환한다', () => {
|
||||
for (const [keys, expected] of [
|
||||
['hellodnjfem', 'hello월드'],
|
||||
['githubtjqj', 'github서버'],
|
||||
['loginghkaus', 'login화면'],
|
||||
['designvhsxm', 'design폰트'],
|
||||
['Reactzjavhsjsxm', 'React컴포넌트'],
|
||||
['VSCodetjfwjd', 'VSCode설정'],
|
||||
['PDFvkdlf', 'PDF파일'],
|
||||
['WWDCvhfja', 'WWDC포럼'],
|
||||
['OAuthdlswmd', 'OAuth인증'],
|
||||
['RPAdlswmd', 'RPA인증'],
|
||||
['TPSvkdlf', 'TPS파일'],
|
||||
['EUwjdcor', 'EU정책'],
|
||||
['TUtjqj', 'TU서버'],
|
||||
['TBvkdlf', 'TB파일'],
|
||||
['ETLwjdcor', 'ETL정책'],
|
||||
['TTLtjfwjd', 'TTL설정'],
|
||||
['PCzkxhrdptj', 'PC카톡에서'],
|
||||
['APIzkxhrdptj', 'API카톡에서'],
|
||||
['dhsmfdmsgoogledptj', '오늘은google에서']
|
||||
] as const) {
|
||||
expect(detectLatinTypedHangul(keys, { hangul: 0, latin: 0 }), keys).toBe(expected)
|
||||
}
|
||||
})
|
||||
|
||||
it('한영 키를 누르지 않고 이어 친 문장 전체를 자연스럽게 변환한다', () => {
|
||||
expect(applyAll('Stay hungry, stay foolishsms wkqtmdml akfdlek.')).toBe(
|
||||
'Stay hungry, stay foolish는 잡스의 말이다.'
|
||||
)
|
||||
expect(applyAll('dlrjs githubdp commitgkf rjdi.')).toBe('이건 github에 commit할 거야.')
|
||||
expect(applyAll('dlrjs github dp commit gkf rjdi')).toBe('이건 github 에 commit 할 거야')
|
||||
expect(applyAll('tmvmfls API qkfvy wnsql')).toBe('스프린 API 발표 준비')
|
||||
expect(applyAll("let's go")).toBe("let's go")
|
||||
expect(applyAll('dlrj go')).toBe('이거 해')
|
||||
expect(applyAll('dhsmf 3tl')).toBe('오늘 3시')
|
||||
})
|
||||
|
||||
it('한글 자판 상태에서 친 영단어·영단어+조사를 한글 문맥 안에서도 복원한다', () => {
|
||||
expect(detectHangulTypedLatin('ㅗ디ㅣㅐ', KO)).toBe('hello')
|
||||
expect(detectHangulTypedLatin('ㅎ샤ㅗㅕㅠ', KO)).toBe('github')
|
||||
expect(detectHangulTypedLatin('ㅎ샤ㅗㅕㅠ에', KO)).toBe('github에')
|
||||
expect(detectHangulTypedLatin('메ㅔ을', KO)).toBe('app을')
|
||||
expect(applyAll('오늘 ㅎ샤ㅗㅕㅠ에 올렸어요 ')).toBe('오늘 github에 올렸어요 ')
|
||||
})
|
||||
|
||||
it('URL · 경로 · 이메일 런은 보존하되 멘션·슬래시 쌍·약어 조사는 변환한다', () => {
|
||||
for (const urlText of [
|
||||
'https://example.com/dl ',
|
||||
'https://a.io/?q=dl&p=sk ',
|
||||
'cd ~/src/rk ',
|
||||
'www.ak.com/bb ',
|
||||
'/usr/lib/dl ',
|
||||
'./ak/sk ',
|
||||
'http://localhost:3000/dl ',
|
||||
'localhost:3000/dl ',
|
||||
'x@gmail.com '
|
||||
]) {
|
||||
expect(applyAll(urlText), urlText).toBe(urlText)
|
||||
}
|
||||
expect(applyAll('@dlrjs ')).toBe('@이건 ')
|
||||
expect(applyAll('ska/du ')).toBe('남/여 ')
|
||||
expect(applyAll('TV/fkeldh ')).toBe('TV/라디오 ')
|
||||
expect(applyAll('L.A.fh ')).toBe('L.A.로 ')
|
||||
expect(applyAll('1:1ansdml ')).toBe('1:1문의 ')
|
||||
expect(applyAll('/sk ')).toBe('/나 ')
|
||||
})
|
||||
|
||||
it('단어 중간에 잠시 멈춰 앞부분이 먼저 변환된 뒤 이어 친 토큰도 자연스럽게 재결합한다', () => {
|
||||
expect(detectLatinTypedHangul('안녕gktpdy', KO)).toBe('안녕하세요')
|
||||
expect(detectLatinTypedHangul('안녀d', KO)).toBe('안녕')
|
||||
expect(detectLatinTypedHangul('회의dp', KO)).toBe('회의에')
|
||||
expect(detectLatinTypedHangul('github에tj', KO)).toBe('github에서')
|
||||
expect(detectLatinTypedHangul('오늘meeting', KO)).toBeNull()
|
||||
expect(detectLatinTypedHangul('카카오API', KO)).toBeNull()
|
||||
expect(detectHangulTypedLatin('hellㅐ', KO)).toBe('hello')
|
||||
expect(detectHangulTypedLatin('githuㅠ', KO)).toBe('github')
|
||||
expect(detectHangulTypedLatin('github에', KO)).toBeNull()
|
||||
})
|
||||
|
||||
it('한글 자판 상태로 친 영문 문장 전체(2글자 단어·I·굴절형·기능어 포함)를 정확히 영문으로 복원한다', () => {
|
||||
expect(applyAll('ㅑㄹ ㅑ 쇼ㅔㄷ ㅗ디ㅣㅐ 소두 ㅑㅅ 초뭏ㄷㄴ ㅑㅜ 10 ㄴㄷ채ㅜㅇㄴ')).toBe(
|
||||
'if I type hello then it changes in 10 seconds'
|
||||
)
|
||||
expect(applyAll('ㅑㄹ ㅑ 쇼ㅔㄷ hello 소두 ㅑㅅ 초뭏ㄷㄴ ㅑㅜ 10 ㄴㄷ채ㅜㅇㄴ')).toBe(
|
||||
'if I type hello then it changes in 10 seconds'
|
||||
)
|
||||
expect(applyAll('거의 30 ㄴㄷ채ㅜㅇㄴ 걸리는 것 같음.')).toBe('거의 30 seconds 걸리는 것 같음.')
|
||||
expect(applyAll('ㅗ디ㅣㅐ 재깅 ')).toBe('hello world ')
|
||||
expect(applyAll('ㅗ디ㅣㅐ재깅 ')).toBe('hello world ')
|
||||
expect(applyAll('hello재깅 ')).toBe('hello world ')
|
||||
expect(applyAll('ㅖㅇㄹ파일 ')).toBe('PDF파일 ')
|
||||
expect(applyAll('ㅁㅔㅑ키 ')).toBe('API키 ')
|
||||
expect(
|
||||
detectTypos('ㅗ디ㅣㅐ ', {
|
||||
includeTrailingToken: true,
|
||||
ignoredWords: ['ㅗ디ㅣㅐ']
|
||||
})
|
||||
).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('터미널·Vim 명령줄(:ㅈㅂ → :wq, :ㅂ! → :q!)과 CLI 명령어(퍙 → vim, ㅣㄴ → ls, 채ㅜㄴㅅ → const)를 복원한다', () => {
|
||||
const applyTerminal = (prefix: string): { result: string; deleteCount: number } => {
|
||||
const plan = planTypoReplacement(
|
||||
prefix,
|
||||
detectTypos(prefix, { includeTrailingToken: true, layoutOnly: true, terminalMode: true })
|
||||
)
|
||||
if (!plan) return { result: prefix, deleteCount: 0 }
|
||||
return {
|
||||
result: prefix.slice(0, prefix.length - plan.deleteCount) + plan.insertText,
|
||||
deleteCount: plan.deleteCount
|
||||
}
|
||||
}
|
||||
|
||||
// ':' 는 지우지 않고 뒤의 한글 명령만 지워 영문 Ex 명령으로 바꾼다
|
||||
expect(applyTerminal(':ㅈㅂ')).toEqual({ result: ':wq', deleteCount: 2 })
|
||||
expect(applyTerminal(':ㅈㅂ!')).toEqual({ result: ':wq!', deleteCount: 3 })
|
||||
expect(applyTerminal(':ㅈ')).toEqual({ result: ':w', deleteCount: 1 })
|
||||
expect(applyTerminal(':ㅂ')).toEqual({ result: ':q', deleteCount: 1 })
|
||||
expect(applyTerminal(':ㅂ!')).toEqual({ result: ':q!', deleteCount: 2 })
|
||||
expect(applyTerminal(':ㅌ')).toEqual({ result: ':x', deleteCount: 1 })
|
||||
expect(applyTerminal(':ㅍ네')).toEqual({ result: ':vsp', deleteCount: 2 })
|
||||
expect(applyTerminal(':네')).toEqual({ result: ':sp', deleteCount: 1 })
|
||||
expect(applyTerminal(':ㅜㅐㅗ')).toEqual({ result: ':noh', deleteCount: 3 })
|
||||
|
||||
// 셸·코드 키워드 복원
|
||||
expect(applyTerminal('퍄ㅡ ').result).toBe('vim ')
|
||||
expect(applyTerminal('ㅜ퍄ㅡ ').result).toBe('nvim ')
|
||||
expect(applyTerminal('ㅣㄴ ').result).toBe('ls ')
|
||||
expect(applyTerminal('채ㅜㄴㅅ ').result).toBe('const ')
|
||||
expect(applyTerminal('ㅎ샤 commit ').result).toBe('git commit ')
|
||||
expect(applyTerminal('햣 commit ').result).toBe('git commit ')
|
||||
|
||||
// Vim 노멀 모드에서 i/a/o 를 눌러 입력 모드로 들어간 직후 친 영→한은 앞의 i/a/o 를 지우지 않는다
|
||||
expect(applyTerminal('idkssudgktpdy ')).toEqual({
|
||||
result: 'i안녕하세요 ',
|
||||
deleteCount: 'dkssudgktpdy '.length
|
||||
})
|
||||
expect(applyTerminal('adkssudgktpdy ')).toEqual({
|
||||
result: 'a안녕하세요 ',
|
||||
deleteCount: 'dkssudgktpdy '.length
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -42,6 +42,14 @@
|
|||
"types": "./src/input-intelligence.ts",
|
||||
"default": "./src/input-intelligence.ts"
|
||||
},
|
||||
"./typo-correction": {
|
||||
"types": "./src/typo-correction.ts",
|
||||
"default": "./src/typo-correction.ts"
|
||||
},
|
||||
"./araso-layout": {
|
||||
"types": "./src/araso-layout.ts",
|
||||
"default": "./src/araso-layout.ts"
|
||||
},
|
||||
"./caption-streaming": {
|
||||
"types": "./src/caption-streaming.ts",
|
||||
"default": "./src/caption-streaming.ts"
|
||||
|
|
|
|||
970
packages/core/src/araso-layout.ts
Normal file
970
packages/core/src/araso-layout.ts
Normal file
|
|
@ -0,0 +1,970 @@
|
|||
// packages/core/src/araso-layout.ts
|
||||
// Araso(알아서) 급 한/영 자동 전환 · 합성어 분리 · 잔류 Shift 정규화 · URL/경로 보호 엔진.
|
||||
//
|
||||
// 한/영 키를 누르지 않고 흐름대로 입력했을 때:
|
||||
// 1. 잔류 Shift(빠른 쌍자음·복모음 뒤 대문자: djEJs → 어떤, dlTDj → 있어, dPFmf → 예를, qkRNl → 바뀌)
|
||||
// 2. 영단어/약어/고유명사 + 한글 조사·어미(githubdp → github에, APIfmf → API를, commitgotj → commit해서)
|
||||
// 3. 받침 호응 판별(TMdms → TM은, TVsms → TV는, 반면 TMsms → 쓰는, TLdp → 씨에)
|
||||
// 4. 영문 + 한글 합성어(PDFvkdlf → PDF파일, iPhonevkdlf → iPhone파일, hellodnjfem → hello월드)
|
||||
// 5. 한글 + 영문 합성어(dhsmfdmsgoogledptj → 오늘은google에서)
|
||||
// 6. URL · 파일 경로 · 이메일 런 보호(https://..., www...., ~/..., /a/b, user@domain 은 보존하되
|
||||
// @dlrjs → @이건, ska/du → 남/여, TV/fkeldh → TV/라디오, L.A.fh → L.A.로, 1:1ansdml → 1:1문의 허용)
|
||||
|
||||
/** 두벌식에서 Shift 로만 칠 수 있는 유효 한글 자모 키 (ㅃ ㅉ ㄸ ㄲ ㅆ ㅒ ㅖ) */
|
||||
export const KOREAN_SHIFT_KEYS = new Set(['Q', 'W', 'E', 'R', 'T', 'O', 'P'])
|
||||
const DOUBLE_CONSONANT_SHIFT_KEYS = new Set(['Q', 'W', 'E', 'R', 'T'])
|
||||
const FINAL_CAPABLE_SHIFT_KEYS = new Set(['R', 'T'])
|
||||
const SHIFT_VOWEL_KEYS = new Set(['O', 'P'])
|
||||
|
||||
const VOWEL_LOWER_KEYS = new Set(['k', 'o', 'i', 'j', 'p', 'u', 'h', 'y', 'n', 'b', 'm', 'l'])
|
||||
const CONSONANT_LOWER_KEYS = new Set(['r', 's', 'e', 'f', 'a', 'q', 't', 'd', 'w', 'c', 'z', 'x', 'v', 'g'])
|
||||
|
||||
function isUpperAscii(char: string | undefined): boolean {
|
||||
if (!char || char.length !== 1) return false
|
||||
const code = char.charCodeAt(0)
|
||||
return code >= 0x41 && code <= 0x5a
|
||||
}
|
||||
|
||||
function isLowerAscii(char: string | undefined): boolean {
|
||||
if (!char || char.length !== 1) return false
|
||||
const code = char.charCodeAt(0)
|
||||
return code >= 0x61 && code <= 0x7a
|
||||
}
|
||||
|
||||
/**
|
||||
* 직전 쌍자음·복모음 Shift 가 미처 떨어지지 않아 다음 키까지 대문자로 찍힌 경우인가.
|
||||
*
|
||||
* - 쌍자음(Q W E R T) 바로 뒤 모음 키가 대문자로 눌림: djEJs(어떤), qkRNl(바뀌), wlsWK(진짜)
|
||||
* - 받침 가능한 쌍자음(R T: ㄲ ㅆ)이 모음 뒤에 오고, 다음 초성 자음이 대문자로 눌림: dlTDj(있어), qkRDp(밖에)
|
||||
* - 복모음(O P: ㅒ ㅖ)이 초성 뒤에 오고, 다음 자음이 대문자로 눌림: dPFmf(예를), rOSp(걔네), rPFks(계란)
|
||||
* - 쌍자음 뒤 모음 대문자에 이어 그다음 키까지 Shift 가 남음: TKdRJvnf(쌍꺼풀), qkRNjTdj(바꿨어)
|
||||
*/
|
||||
export function lingersAfterKoreanShift(
|
||||
prev: string | undefined,
|
||||
twoBack: string | undefined,
|
||||
current: string
|
||||
): boolean {
|
||||
if (!isUpperAscii(current) || KOREAN_SHIFT_KEYS.has(current)) return false
|
||||
const lower = current.toLowerCase()
|
||||
if (prev !== undefined && DOUBLE_CONSONANT_SHIFT_KEYS.has(prev) && VOWEL_LOWER_KEYS.has(lower)) {
|
||||
return true
|
||||
}
|
||||
if (
|
||||
prev !== undefined &&
|
||||
FINAL_CAPABLE_SHIFT_KEYS.has(prev) &&
|
||||
twoBack !== undefined &&
|
||||
VOWEL_LOWER_KEYS.has(twoBack.toLowerCase()) &&
|
||||
CONSONANT_LOWER_KEYS.has(lower)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
if (
|
||||
prev !== undefined &&
|
||||
SHIFT_VOWEL_KEYS.has(prev) &&
|
||||
twoBack !== undefined &&
|
||||
CONSONANT_LOWER_KEYS.has(lower)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
if (
|
||||
twoBack !== undefined &&
|
||||
DOUBLE_CONSONANT_SHIFT_KEYS.has(twoBack) &&
|
||||
prev !== undefined &&
|
||||
isUpperAscii(prev) &&
|
||||
!KOREAN_SHIFT_KEYS.has(prev) &&
|
||||
VOWEL_LOWER_KEYS.has(prev.toLowerCase())
|
||||
) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* 단어 안의 잔류 Shift 대문자를 소문자로 정규화한다.
|
||||
*
|
||||
* - 소문자가 하나도 없는 순수 대문자 약어(TM, API, PDF, EU, RN, TL)는 정규화하지 않고 null.
|
||||
* - 잔류 Shift 로 설명되지 않는 영문 전용 대문자(Hello, iPhone, GitHub, PCqkd, OAuth, TFxla)가 있으면 null.
|
||||
*/
|
||||
export function normalizeLingeringShift(word: string): string | null {
|
||||
if (!/[a-z]/u.test(word)) return null
|
||||
const chars = Array.from(word)
|
||||
const out: string[] = []
|
||||
for (let i = 0; i < chars.length; i += 1) {
|
||||
const curr = chars[i]
|
||||
if (!isUpperAscii(curr)) {
|
||||
out.push(curr)
|
||||
continue
|
||||
}
|
||||
const prev = i >= 1 ? chars[i - 1] : undefined
|
||||
const twoBack = i >= 2 ? chars[i - 2] : undefined
|
||||
if (KOREAN_SHIFT_KEYS.has(curr)) {
|
||||
// O/P(ㅒ/ㅖ)가 대문자 뒤에 바로 이어진 약어(RPA, TPS 등)는 한글 음절이 아니다.
|
||||
if (SHIFT_VOWEL_KEYS.has(curr) && prev !== undefined && isUpperAscii(prev)) {
|
||||
return null
|
||||
}
|
||||
out.push(curr)
|
||||
continue
|
||||
}
|
||||
if (lingersAfterKoreanShift(prev, twoBack, curr)) {
|
||||
out.push(curr.toLowerCase())
|
||||
continue
|
||||
}
|
||||
return null
|
||||
}
|
||||
return out.join('')
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 조사 · 어미 사전 및 받침 호응 (ParticleSplitter & MixedWord)
|
||||
// ============================================================
|
||||
|
||||
export type FinalSound = 'vowel' | 'consonant' | 'rieul'
|
||||
|
||||
/** 두벌식 영문 키로 친 한국어 조사 · 어미 · 하다/되다 활용형 */
|
||||
export const PARTICLE_KEYS: ReadonlySet<string> = new Set([
|
||||
// 격조사
|
||||
'dms', // 은
|
||||
'sms', // 는
|
||||
'dl', // 이
|
||||
'rk', // 가
|
||||
'fmf', // 를
|
||||
'dmf', // 을
|
||||
'dml', // 의
|
||||
'dp', // 에
|
||||
'dptj', // 에서
|
||||
'dprp', // 에게
|
||||
'dpcj', // 에다
|
||||
'fh', // 로
|
||||
'dmfh', // 으로
|
||||
'fhTj', // 로써
|
||||
'dmfhTj', // 으로써
|
||||
'fhtj', // 로서
|
||||
'dmfhtj', // 으로서
|
||||
'dhk', // 와
|
||||
'rhk', // 과
|
||||
'dlfkd', // 이랑
|
||||
'fkd', // 랑
|
||||
'dmlfh', // 의로
|
||||
|
||||
// 보조사 · 의존명사 결합
|
||||
'eh', // 도
|
||||
'aks', // 만
|
||||
'qnxj', // 부터
|
||||
'Rkwl', // 까지
|
||||
'akwk', // 마자
|
||||
'whck', // 조차
|
||||
'ekfka', // 따라
|
||||
'qhek', // 보다
|
||||
'cufrja', // 처럼
|
||||
'rkxdms', // 같은
|
||||
'rkxdmsrjs', // 같은건
|
||||
'rkxdmsrj', // 같은거
|
||||
'rkxdmsep', // 같은데
|
||||
'rkxdl', // 같이
|
||||
'dlsk', // 이나
|
||||
'sk', // 나
|
||||
'dlek', // 이다
|
||||
'dlf', // 일
|
||||
'dlswl', // 인지
|
||||
'dlsrk', // 인가
|
||||
'dlsrjd', // 인걸
|
||||
'dlsrjs', // 인건
|
||||
'dlfks', // 이란
|
||||
'fks', // 란
|
||||
'ek', // 다
|
||||
'fkrh', // 라고
|
||||
'dlfkrh', // 이라고
|
||||
'fksms', // 라는
|
||||
'dlfksms', // 이라는
|
||||
'sp', // 네
|
||||
'dy', // 요
|
||||
'dlrjs', // 이건
|
||||
'rjs', // 건
|
||||
'rj', // 거
|
||||
'rjdi', // 거야
|
||||
'rjek', // 거다
|
||||
|
||||
// 복합 조사
|
||||
'dpdms', // 에는
|
||||
'dpfmf', // 에를
|
||||
'dptjdms', // 에서는
|
||||
'dptjeh', // 에서도
|
||||
'dpdptj', // 에에서
|
||||
'dpej', // 에더
|
||||
'dpeh', // 에도
|
||||
'dpaks', // 에만
|
||||
'dlfk', // 이라
|
||||
'fk', // 라
|
||||
'dldk', // 이야
|
||||
'dk', // 야
|
||||
'dlskak', // 이나마
|
||||
'dmfhsms', // 으로는
|
||||
'fhsms', // 로는
|
||||
'dmfheh', // 으로도
|
||||
'fheh', // 로도
|
||||
'dhksms', // 와는
|
||||
'rhksms', // 과는
|
||||
'dprpsms', // 에게는
|
||||
'dprpeh', // 에게도
|
||||
'qnxjsms', // 부터는
|
||||
'Rkwlsms', // 까지는
|
||||
'Rkwleh', // 까지도
|
||||
'aksdms', // 만은
|
||||
'akseh', // 만도
|
||||
'qheksms', // 보다는
|
||||
|
||||
// 서술격 · 종결
|
||||
'dlqslek', // 입니다
|
||||
'qslek', // ㅂ니다
|
||||
'dla', // 임
|
||||
'dldyd', // 이용
|
||||
'dldpdy', // 이에요
|
||||
'dpdy', // 에요
|
||||
'dPdy', // 예요
|
||||
'dlwjs', // 이전
|
||||
'dlgn', // 이후
|
||||
|
||||
// -하다 / -되다 / -나다 결합 (commit해서, commit할, deploy했어 등)
|
||||
'gkrh', // 하고
|
||||
'gotj', // 해서
|
||||
'gkf', // 할
|
||||
'gks', // 한
|
||||
'gksms', // 하는
|
||||
'gksek', // 한다
|
||||
'go', // 해
|
||||
'gody', // 해요
|
||||
'gkrhtj', // 하고서
|
||||
'gkrjsk', // 하거나
|
||||
'gkwk', // 하자
|
||||
'gkwksk', // 하자나
|
||||
'gkwksl', // 하자니
|
||||
'gksmswl', // 하는지
|
||||
'gksrk', // 한가
|
||||
'goTek', // 했다
|
||||
'goTdms', // 했는
|
||||
'goTwl', // 했지
|
||||
'goTdj', // 했어
|
||||
'goTdjdy', // 했어요
|
||||
'gkqslek', // 합니다
|
||||
'gkfl', // 하리
|
||||
'gkaus', // 하면
|
||||
'gksrjs', // 한건
|
||||
'ehlrh', // 되고
|
||||
'ehltj', // 돼서
|
||||
'ehlf', // 될
|
||||
'ehls', // 된
|
||||
'ehlsms', // 되는
|
||||
'ehlsek', // 된다
|
||||
'ehl', // 되
|
||||
'ehldj', // 되어
|
||||
'ehldjdy', // 되어요
|
||||
'ehlqslek', // 됩니다
|
||||
'ehlaus', // 되면
|
||||
'skrh', // 나고
|
||||
'sktj', // 나서
|
||||
'sks', // 난
|
||||
'sksms' // 나는
|
||||
])
|
||||
|
||||
const PAIRED_PARTICLES: Readonly<Record<string, ReadonlySet<FinalSound>>> = {
|
||||
을: new Set<FinalSound>(['consonant', 'rieul']),
|
||||
를: new Set<FinalSound>(['vowel']),
|
||||
은: new Set<FinalSound>(['consonant', 'rieul']),
|
||||
는: new Set<FinalSound>(['vowel']),
|
||||
이: new Set<FinalSound>(['consonant', 'rieul']),
|
||||
가: new Set<FinalSound>(['vowel']),
|
||||
과: new Set<FinalSound>(['consonant', 'rieul']),
|
||||
와: new Set<FinalSound>(['vowel']),
|
||||
으로: new Set<FinalSound>(['consonant']),
|
||||
로: new Set<FinalSound>(['vowel', 'rieul']),
|
||||
으로는: new Set<FinalSound>(['consonant']),
|
||||
로는: new Set<FinalSound>(['vowel', 'rieul']),
|
||||
으로도: new Set<FinalSound>(['consonant']),
|
||||
로도: new Set<FinalSound>(['vowel', 'rieul']),
|
||||
으로써: new Set<FinalSound>(['consonant']),
|
||||
로써: new Set<FinalSound>(['vowel', 'rieul']),
|
||||
으로서: new Set<FinalSound>(['consonant']),
|
||||
로서: new Set<FinalSound>(['vowel', 'rieul']),
|
||||
이랑: new Set<FinalSound>(['consonant', 'rieul']),
|
||||
랑: new Set<FinalSound>(['vowel']),
|
||||
이나: new Set<FinalSound>(['consonant', 'rieul']),
|
||||
나: new Set<FinalSound>(['vowel']),
|
||||
이야: new Set<FinalSound>(['consonant', 'rieul']),
|
||||
야: new Set<FinalSound>(['vowel']),
|
||||
이라: new Set<FinalSound>(['consonant', 'rieul']),
|
||||
라: new Set<FinalSound>(['vowel']),
|
||||
이라고: new Set<FinalSound>(['consonant', 'rieul']),
|
||||
라고: new Set<FinalSound>(['vowel']),
|
||||
이라는: new Set<FinalSound>(['consonant', 'rieul']),
|
||||
라는: new Set<FinalSound>(['vowel']),
|
||||
이란: new Set<FinalSound>(['consonant', 'rieul']),
|
||||
란: new Set<FinalSound>(['vowel']),
|
||||
이에요: new Set<FinalSound>(['consonant', 'rieul']),
|
||||
예요: new Set<FinalSound>(['vowel']),
|
||||
과는: new Set<FinalSound>(['consonant', 'rieul']),
|
||||
와는: new Set<FinalSound>(['vowel'])
|
||||
}
|
||||
|
||||
/** 한글 음절(또는 단어 마지막 글자)의 받침 소리 분류 */
|
||||
export function finalSoundOfHangul(word: string): FinalSound | null {
|
||||
if (!word) return null
|
||||
const last = word.charCodeAt(word.length - 1)
|
||||
if (last < 0xac00 || last > 0xd7a3) return null
|
||||
const jong = (last - 0xac00) % 28
|
||||
if (jong === 0) return 'vowel'
|
||||
if (jong === 8) return 'rieul'
|
||||
return 'consonant'
|
||||
}
|
||||
|
||||
/** 대문자 약어(TM, TV, URL, API 등)를 한국어 알파벳 이름으로 읽었을 때 마지막 글자의 받침 소리 */
|
||||
export function finalSoundOfAcronym(acronym: string): FinalSound {
|
||||
const last = acronym[acronym.length - 1]?.toUpperCase() ?? ''
|
||||
if (last === 'L' || last === 'R') return 'rieul'
|
||||
if (last === 'M' || last === 'N') return 'consonant'
|
||||
return 'vowel'
|
||||
}
|
||||
|
||||
/** 일반 영단어를 읽었을 때 마지막 발음의 받침 소리 근사 */
|
||||
export function finalSoundOfEnglishWord(word: string): FinalSound {
|
||||
if (/^[A-Z][A-Z0-9]*$/u.test(word)) return finalSoundOfAcronym(word)
|
||||
let lower = word.toLowerCase()
|
||||
if (lower.length >= 3 && lower.endsWith('le') && !/[aeiouy]le$/u.test(lower)) {
|
||||
return 'rieul'
|
||||
}
|
||||
if (lower.length >= 3 && lower.endsWith('e') && !lower.endsWith('ee') && !/[aeiouy]e$/u.test(lower)) {
|
||||
lower = lower.slice(0, -1)
|
||||
}
|
||||
const last = lower[lower.length - 1] ?? ''
|
||||
if ('aeiouwy'.includes(last)) return 'vowel'
|
||||
if (last === 'l') return 'rieul'
|
||||
return 'consonant'
|
||||
}
|
||||
|
||||
/**
|
||||
* 조사가 앞말 받침 소리와 호응하는가.
|
||||
* - 호응 쌍이 있는 조사(을/를, 은/는, 이/가, 과/와, 으로/로 등)면 true/false 반환.
|
||||
* - 받침 무관 조사(에, 에서, 도, 만, 부터, 까지 등)면 null 반환.
|
||||
*/
|
||||
export function particleAgrees(particleHangul: string, final: FinalSound): boolean | null {
|
||||
const allowed = PAIRED_PARTICLES[particleHangul]
|
||||
if (!allowed) return null
|
||||
return allowed.has(final)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 잔류 Shift 약어 모양(2글자 대문자) vs 실제 한국어 첫 음절 판별
|
||||
// ============================================================
|
||||
|
||||
/**
|
||||
* EU(뗘), TU(쎠), TB(쓔)처럼 두 글자 대문자를 잔류 Shift 한글로 읽으면 한국어 어휘에 거의 쓰이지 않는
|
||||
* 첫 음절이 되는 경우를 가려낸다.
|
||||
*/
|
||||
const RARE_LINGERING_SHIFT_INITIAL_SYLLABLES = new Set([
|
||||
'뗘',
|
||||
'쎠',
|
||||
'쓔',
|
||||
'뺘',
|
||||
'뼝',
|
||||
'쮸',
|
||||
'쪠',
|
||||
'뛔',
|
||||
'뙤',
|
||||
'뀀',
|
||||
'뀁',
|
||||
'뀄'
|
||||
])
|
||||
|
||||
export function isNaturalLingeringShiftInitialSyllable(syllable: string): boolean {
|
||||
if (!syllable) return false
|
||||
return !RARE_LINGERING_SHIFT_INITIAL_SYLLABLES.has(syllable[0])
|
||||
}
|
||||
|
||||
/**
|
||||
* 두벌식으로 흔히 쓰이는 한국어 단어/어간(문맥 없이도 한영 오타로 확신할 수 있는 1~2음절 핵심 어휘).
|
||||
* 예: 안녕(dkssud), 오늘(dhsmf), 내일(sodlf), 지금(wlrma), 우리(dnfl), 진짜(wlsWk),
|
||||
* 좋아(whgdk), 맞아(akwdk), 한글(gksrmf), 날씨(skfTl), 있다(dlTek), 사랑(tkfkd),
|
||||
* 정말(wjdakf), 잘(wkf), 먹어(ajrdj), 이건(dlrjs), 어떻(djEjg), 시간(tlrks),
|
||||
* 혜택(gPxor), 닥터(ekrxj), 했죠(goTwy), 조지(whwl), 촉매(chrao), 소견(thrus), 모든(ahems),
|
||||
* 왜(dho), 거야(rjdi), 회의(ghldml), 자료(wkfyd), 공유(rhddb), 확인(ghkrdls) 등.
|
||||
*/
|
||||
export const CORE_KOREAN_WORDS: ReadonlySet<string> = new Set([
|
||||
// 1음절 핵심 단어·조사
|
||||
'잘',
|
||||
'왜',
|
||||
'뭐',
|
||||
'해',
|
||||
'네',
|
||||
'안',
|
||||
'못',
|
||||
'더',
|
||||
'덜',
|
||||
'꼭',
|
||||
'딱',
|
||||
'좀',
|
||||
'참',
|
||||
'곧',
|
||||
'늘',
|
||||
'다',
|
||||
'는',
|
||||
'은',
|
||||
'를',
|
||||
'을',
|
||||
'에',
|
||||
'의',
|
||||
'가',
|
||||
'이',
|
||||
'도',
|
||||
'만',
|
||||
'과',
|
||||
'와',
|
||||
'로',
|
||||
'할',
|
||||
'한',
|
||||
'된',
|
||||
'될',
|
||||
'건',
|
||||
'거',
|
||||
'걸',
|
||||
'것',
|
||||
'수',
|
||||
'때',
|
||||
'곳',
|
||||
'분',
|
||||
'시',
|
||||
'일',
|
||||
'월',
|
||||
'년',
|
||||
'번',
|
||||
'개',
|
||||
'명',
|
||||
'남',
|
||||
'여',
|
||||
'나',
|
||||
'너',
|
||||
// 2음절 이상 일상·업무 핵심 어휘
|
||||
'안녕',
|
||||
'한글',
|
||||
'오늘',
|
||||
'내일',
|
||||
'어제',
|
||||
'지금',
|
||||
'우리',
|
||||
'그냥',
|
||||
'진짜',
|
||||
'정말',
|
||||
'너무',
|
||||
'많이',
|
||||
'조금',
|
||||
'아주',
|
||||
'가장',
|
||||
'제일',
|
||||
'다시',
|
||||
'먼저',
|
||||
'이미',
|
||||
'아직',
|
||||
'벌써',
|
||||
'계속',
|
||||
'함께',
|
||||
'같이',
|
||||
'혼자',
|
||||
'바로',
|
||||
'직접',
|
||||
'모두',
|
||||
'모든',
|
||||
'전부',
|
||||
'각각',
|
||||
'서로',
|
||||
'혹시',
|
||||
'아마',
|
||||
'역시',
|
||||
'물론',
|
||||
'일단',
|
||||
'우선',
|
||||
'거의',
|
||||
'전혀',
|
||||
'결국',
|
||||
'마침',
|
||||
'날씨',
|
||||
'좋아',
|
||||
'좋은',
|
||||
'좋고',
|
||||
'좋네',
|
||||
'맞아',
|
||||
'맞네',
|
||||
'맞고',
|
||||
'있다',
|
||||
'있어',
|
||||
'있네',
|
||||
'있고',
|
||||
'있는',
|
||||
'없다',
|
||||
'없어',
|
||||
'없네',
|
||||
'없고',
|
||||
'없는',
|
||||
'같아',
|
||||
'같은',
|
||||
'같네',
|
||||
'사랑',
|
||||
'먹어',
|
||||
'먹고',
|
||||
'먹자',
|
||||
'이건',
|
||||
'이거',
|
||||
'그건',
|
||||
'그거',
|
||||
'저건',
|
||||
'저거',
|
||||
'어떻',
|
||||
'어떤',
|
||||
'어디',
|
||||
'언제',
|
||||
'누구',
|
||||
'무슨',
|
||||
'얼마',
|
||||
'시간',
|
||||
'사람',
|
||||
'생각',
|
||||
'마음',
|
||||
'이야기',
|
||||
'얘기',
|
||||
'혜택',
|
||||
'닥터',
|
||||
'했죠',
|
||||
'했어',
|
||||
'했다',
|
||||
'조지',
|
||||
'촉매',
|
||||
'소견',
|
||||
'거야',
|
||||
'거다',
|
||||
'할까',
|
||||
'까지',
|
||||
'부터',
|
||||
'에서',
|
||||
'에게',
|
||||
'으로',
|
||||
'바뀌',
|
||||
'바뀌도',
|
||||
'바꿨어',
|
||||
'꿀을',
|
||||
'따라서',
|
||||
'쌍꺼풀',
|
||||
'어떨까요',
|
||||
'쓰라고',
|
||||
'모서리쪽이',
|
||||
'예를',
|
||||
'걔네',
|
||||
'계란',
|
||||
'예외',
|
||||
'밖에',
|
||||
'쓰는',
|
||||
'꾸는',
|
||||
'씨에',
|
||||
'쌀을',
|
||||
'씨는',
|
||||
'꺼내다',
|
||||
'쪼개다',
|
||||
'쓰레기',
|
||||
'껴안고',
|
||||
'띠동갑',
|
||||
'뾰족한',
|
||||
'삐에로',
|
||||
'삐졌어',
|
||||
'쪄먹다',
|
||||
'쪄버렸어',
|
||||
'찔렀어',
|
||||
'쭈그리고',
|
||||
'또공룡이',
|
||||
'쓰정책',
|
||||
'씨서버',
|
||||
'현재',
|
||||
'현재는',
|
||||
'맘에',
|
||||
'곁에',
|
||||
'잘가',
|
||||
'끝에서',
|
||||
'쐈어요',
|
||||
'회의',
|
||||
'자료',
|
||||
'공유',
|
||||
'확인',
|
||||
'진행',
|
||||
'작업',
|
||||
'문제',
|
||||
'기능',
|
||||
'설정',
|
||||
'화면',
|
||||
'내용',
|
||||
'결과',
|
||||
'부분',
|
||||
'경우',
|
||||
'정도',
|
||||
'필요',
|
||||
'가능',
|
||||
'사용',
|
||||
'추가',
|
||||
'수정',
|
||||
'삭제',
|
||||
'완료',
|
||||
'시작',
|
||||
'연결',
|
||||
'선택',
|
||||
'입력',
|
||||
'출력',
|
||||
'변환',
|
||||
'자동',
|
||||
'기본',
|
||||
'지원',
|
||||
'모델',
|
||||
'음성',
|
||||
'인식',
|
||||
'번역',
|
||||
'요약',
|
||||
'기록',
|
||||
'사전',
|
||||
'서버',
|
||||
'파일',
|
||||
'카톡',
|
||||
'월드',
|
||||
'폰트',
|
||||
'인증',
|
||||
'정책',
|
||||
'포럼',
|
||||
'메시지',
|
||||
'컴포넌트',
|
||||
'발표',
|
||||
'준비',
|
||||
'스프린',
|
||||
'문의',
|
||||
'라디오',
|
||||
'고마워',
|
||||
'반갑습니다',
|
||||
'감사합니다',
|
||||
'안녕하세요',
|
||||
'그런데',
|
||||
'그래서',
|
||||
'그리고',
|
||||
'하지만',
|
||||
'그러면'
|
||||
])
|
||||
|
||||
/** 숫자 뒤에 붙는 한국어 단위 명사 (3tl → 3시, 10qns → 10분 등) */
|
||||
export const KOREAN_COUNTER_KEYS: Readonly<Record<string, string>> = {
|
||||
tl: '시',
|
||||
tlrks: '시간',
|
||||
qns: '분',
|
||||
ch: '초',
|
||||
dlf: '일',
|
||||
dnjf: '월',
|
||||
sus: '년',
|
||||
ro: '개',
|
||||
qjs: '번',
|
||||
qjsWo: '번째',
|
||||
aud: '명',
|
||||
cmd: '층',
|
||||
wkd: '장',
|
||||
wnf: '줄',
|
||||
dnjs: '원',
|
||||
gkf: '할'
|
||||
}
|
||||
|
||||
export interface MixedWordHelpers {
|
||||
latinToHangul(word: string): { text: string; complete: boolean }
|
||||
isCommonEnglishWord(lower: string): boolean
|
||||
isKnownKoreanSyllable(char: string): boolean
|
||||
isFrequentKoreanSyllable(char: string): boolean
|
||||
userVocabulary?: ReadonlyMap<string, number>
|
||||
}
|
||||
|
||||
function isAllValidSyllables(text: string, check: (char: string) => boolean): boolean {
|
||||
const chars = Array.from(text)
|
||||
return chars.length > 0 && chars.every(check)
|
||||
}
|
||||
|
||||
function isKnownEnglishOrUserWord(word: string, helpers: MixedWordHelpers): boolean {
|
||||
const lower = word.toLowerCase()
|
||||
if (helpers.isCommonEnglishWord(lower)) return true
|
||||
if (helpers.userVocabulary && (helpers.userVocabulary.get(lower) ?? 0) >= 1) return true
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* 영문+한글 또는 한글+영문 합성어를 분리·변환한다.
|
||||
*
|
||||
* 해당하지 않으면 null.
|
||||
*/
|
||||
export function splitMixedWord(word: string, helpers: MixedWordHelpers): string | null {
|
||||
if (word.length < 3 || !/^[A-Za-z0-9]+$/u.test(word)) return null
|
||||
|
||||
// 0. 숫자 + 한글 단어(1ansdml → 1문의 in 1:1ansdml)
|
||||
const digitPrefixMatch = word.match(/^(\d+)([A-Za-z]+)$/u)
|
||||
if (digitPrefixMatch) {
|
||||
const [, digits, letters] = digitPrefixMatch
|
||||
if (letters.length >= 4) {
|
||||
const converted = helpers.latinToHangul(letters)
|
||||
if (
|
||||
converted.complete &&
|
||||
Array.from(converted.text).length >= 2 &&
|
||||
isAllValidSyllables(converted.text, helpers.isFrequentKoreanSyllable)
|
||||
) {
|
||||
return `${digits}${converted.text}`
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
if (!/^[A-Za-z]+$/u.test(word)) return null
|
||||
const lower = word.toLowerCase()
|
||||
|
||||
// 전체가 이미 잘 알려진 영단어면 절대 쪼개지 않는다 (work, park, hello, thanks, cartman 등)
|
||||
if (isKnownEnglishOrUserWord(lower, helpers)) return null
|
||||
|
||||
// 잔류 Shift 정규화 가능 여부 확인
|
||||
const lingered = normalizeLingeringShift(word)
|
||||
const directHangul = helpers.latinToHangul(lingered ?? word)
|
||||
const isWholeWordNaturalKorean =
|
||||
(lingered !== null || word === lower || /^[QWERTOP][a-z]+$/u.test(word)) &&
|
||||
directHangul.complete &&
|
||||
(CORE_KOREAN_WORDS.has(directHangul.text) ||
|
||||
isAllValidSyllables(directHangul.text, helpers.isFrequentKoreanSyllable))
|
||||
|
||||
// 1. 2글자 대문자 약어 + 조사 (TMdms → TM은 vs TMsms → 쓰는, TLdp → 씨에)
|
||||
const twoUpperParticleMatch = word.match(/^([A-Z]{2})([a-z]+)$/u)
|
||||
if (twoUpperParticleMatch) {
|
||||
const [, upper, tail] = twoUpperParticleMatch
|
||||
if (PARTICLE_KEYS.has(tail)) {
|
||||
const particleConv = helpers.latinToHangul(tail)
|
||||
if (particleConv.complete) {
|
||||
if (lingered !== null) {
|
||||
// TM(쓰), TL(씨), EL(띠), RJ(꺼), RN(꾸)처럼 잔류 Shift 로도 읽히는 2글자 대문자:
|
||||
// 한글 열린 음절('vowel') 뒤에 붙을 수 없는 받침 조사(은/을/이/과 등)가 오면 약어+조사로 분리한다.
|
||||
const agreesKoreanOpen = particleAgrees(particleConv.text, 'vowel')
|
||||
if (agreesKoreanOpen === false) {
|
||||
return `${upper}${particleConv.text}`
|
||||
}
|
||||
return null
|
||||
}
|
||||
const agrees = particleAgrees(particleConv.text, finalSoundOfAcronym(upper))
|
||||
if (agrees !== false) {
|
||||
return `${upper}${particleConv.text}`
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 잔류 Shift 로 자연스러운 순수 한국어가 되는 단어(RNfdmf → 꿀을, qkRNleh → 바뀌도, TkdRjvnfdms → 쌍꺼풀은 등)는
|
||||
// 대문자 이름으로 오인해 쪼개지 않는다.
|
||||
if (lingered !== null && directHangul.complete && isAllValidSyllables(directHangul.text, helpers.isKnownKoreanSyllable)) {
|
||||
const firstSyl = directHangul.text[0] ?? ''
|
||||
if (isNaturalLingeringShiftInitialSyllable(firstSyl)) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// 순수 소문자(또는 첫 글자만 한글 Shift 키)이면서 핵심 한국어 어휘/자연스러운 한국어 단어면 먼저 보호하되,
|
||||
// 앞부분이 명확한 영단어이고 뒷부분이 조사인 경우(githubdp, commitgotj, foolishsms 등)는 아래에서 분리한다.
|
||||
|
||||
// 2. 대문자 약어(2글자 이상) + 소문자 꼬리(조사 또는 한국어 단어):
|
||||
// 경계는 항상 대문자 약어 바로 뒤다 (PDFvkdlf → PDF + 파일, PCzkxhrdptj → PC + 카톡에서; PDFvk + 일 로 쪼개지 않는다).
|
||||
const acronymAndLowerMatch = word.match(/^([A-Z]{2,})([a-z]+)$/u)
|
||||
if (acronymAndLowerMatch) {
|
||||
const [, acronym, lowerTail] = acronymAndLowerMatch
|
||||
if (PARTICLE_KEYS.has(lowerTail)) {
|
||||
const particleConv = helpers.latinToHangul(lowerTail)
|
||||
if (particleConv.complete && particleAgrees(particleConv.text, finalSoundOfAcronym(acronym)) !== false) {
|
||||
return `${acronym}${particleConv.text}`
|
||||
}
|
||||
}
|
||||
if (lowerTail.length >= 3) {
|
||||
const korConv = helpers.latinToHangul(lowerTail)
|
||||
if (
|
||||
korConv.complete &&
|
||||
Array.from(korConv.text).length >= 2 &&
|
||||
isAllValidSyllables(korConv.text, helpers.isKnownKoreanSyllable)
|
||||
) {
|
||||
return `${acronym}${korConv.text}`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2b. 영단어 / 카멜케이스 고유명사 + 한국어 조사·어미
|
||||
for (let i = Math.min(word.length - 2, 24); i >= 2; i -= 1) {
|
||||
const stem = word.slice(0, i)
|
||||
const korPart = word.slice(i)
|
||||
if (!PARTICLE_KEYS.has(korPart)) continue
|
||||
|
||||
const particleConv = helpers.latinToHangul(korPart)
|
||||
if (!particleConv.complete) continue
|
||||
|
||||
const isKnownEngStem = isKnownEnglishOrUserWord(stem, helpers)
|
||||
const isCamelOrCapitalizedName =
|
||||
stem.length >= 3 &&
|
||||
/[A-Z]/u.test(stem) &&
|
||||
(lingered === null || !directHangul.complete) &&
|
||||
isKnownEngStem
|
||||
|
||||
if (!isCamelOrCapitalizedName && !isKnownEngStem) continue
|
||||
|
||||
// 만약 단어 전체가 핵심 한국어 단어(예: 현재=guswo, 현재는=guswosms, 맘에=akadp, 잘가=wkfrk)면 분리하지 않는다.
|
||||
if (
|
||||
word === lower &&
|
||||
directHangul.complete &&
|
||||
(CORE_KOREAN_WORDS.has(directHangul.text) ||
|
||||
(stem.length <= 3 && isAllValidSyllables(directHangul.text, helpers.isFrequentKoreanSyllable)))
|
||||
) {
|
||||
continue
|
||||
}
|
||||
|
||||
return `${stem}${particleConv.text}`
|
||||
}
|
||||
|
||||
// 3. 영문 한 글자 + 한국어 조사 (xdp → x에, Xfmf → X를)
|
||||
if (word.length >= 3 && word.length <= 7) {
|
||||
const first = word[0]
|
||||
const korPart = word.slice(1)
|
||||
if (
|
||||
PARTICLE_KEYS.has(korPart) &&
|
||||
!directHangul.complete &&
|
||||
!(isLowerAscii(first) && (korPart === 'eh' || korPart === 'sk'))
|
||||
) {
|
||||
const particleConv = helpers.latinToHangul(korPart)
|
||||
if (particleConv.complete && particleAgrees(particleConv.text, finalSoundOfAcronym(first)) !== false) {
|
||||
return `${first}${particleConv.text}`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4a. 대문자 약어(2글자 이상) + 한국어 단어 (PDFvkdlf → PDF파일, EUwjdcor → EU정책, PCzkxhrdptj → PC카톡에서)
|
||||
const acronymPrefixMatch = word.match(/^([A-Z]{2,})([a-z]{3,})$/u)
|
||||
if (acronymPrefixMatch) {
|
||||
const [, acronym, korKeys] = acronymPrefixMatch
|
||||
const korConv = helpers.latinToHangul(korKeys)
|
||||
if (
|
||||
korConv.complete &&
|
||||
Array.from(korConv.text).length >= 2 &&
|
||||
isAllValidSyllables(korConv.text, helpers.isKnownKoreanSyllable)
|
||||
) {
|
||||
return `${acronym}${korConv.text}`
|
||||
}
|
||||
}
|
||||
|
||||
// 4b. 카멜케이스/대문자 고유명사 + 한국어 단어 (iPhonevkdlf → iPhone파일, OAuthdlswmd → OAuth인증, Reactzjavhsjsxm → React컴포넌트)
|
||||
if (/[A-Z]/u.test(word) && (lingered === null || !directHangul.complete)) {
|
||||
for (let i = word.length - 4; i >= 3; i -= 1) {
|
||||
const engPart = word.slice(0, i)
|
||||
const korKeys = word.slice(i)
|
||||
if (!/^[a-z]{4,}$/u.test(korKeys)) continue
|
||||
const isRecognizedName =
|
||||
isKnownEnglishOrUserWord(engPart, helpers) ||
|
||||
/^[A-Z][a-z]+[A-Z][A-Za-z]*$/u.test(engPart) ||
|
||||
/^[a-z]+[A-Z][A-Za-z]*$/u.test(engPart)
|
||||
if (!isRecognizedName) continue
|
||||
const korConv = helpers.latinToHangul(korKeys)
|
||||
if (
|
||||
korConv.complete &&
|
||||
Array.from(korConv.text).length >= 2 &&
|
||||
isAllValidSyllables(korConv.text, helpers.isKnownKoreanSyllable)
|
||||
) {
|
||||
return `${engPart}${korConv.text}`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4c. 소문자 영단어 + 한국어 단어 (hellodnjfem → hello월드, githubtjqj → github서버, loginghkaus → login화면)
|
||||
if (word === lower && !isWholeWordNaturalKorean) {
|
||||
for (let i = word.length - 4; i >= 4; i -= 1) {
|
||||
const engPart = word.slice(0, i)
|
||||
const korKeys = word.slice(i)
|
||||
if (!isKnownEnglishOrUserWord(engPart, helpers)) continue
|
||||
const korConv = helpers.latinToHangul(korKeys)
|
||||
if (
|
||||
korConv.complete &&
|
||||
Array.from(korConv.text).length >= 2 &&
|
||||
(CORE_KOREAN_WORDS.has(korConv.text) ||
|
||||
isAllValidSyllables(korConv.text, helpers.isFrequentKoreanSyllable))
|
||||
) {
|
||||
return `${engPart}${korConv.text}`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 한국어 단어 + 영단어 (+ 선택적 한국어 조사) (dhsmfdmsgoogledptj → 오늘은google에서)
|
||||
if (word === lower && !isWholeWordNaturalKorean && word.length >= 8) {
|
||||
for (let i = 4; i <= word.length - 4; i += 1) {
|
||||
const korPrefixKeys = word.slice(0, i)
|
||||
const korPrefixConv = helpers.latinToHangul(korPrefixKeys)
|
||||
if (
|
||||
!korPrefixConv.complete ||
|
||||
Array.from(korPrefixConv.text).length < 2 ||
|
||||
!isAllValidSyllables(korPrefixConv.text, helpers.isFrequentKoreanSyllable)
|
||||
) {
|
||||
continue
|
||||
}
|
||||
const rest = word.slice(i)
|
||||
if (rest.length >= 4 && isKnownEnglishOrUserWord(rest, helpers)) {
|
||||
return `${korPrefixConv.text}${rest}`
|
||||
}
|
||||
// rest 가 영단어 + 조사인 경우 (예: googledptj → google에서)
|
||||
for (let j = rest.length - 2; j >= 4; j -= 1) {
|
||||
const engMid = rest.slice(0, j)
|
||||
const korTail = rest.slice(j)
|
||||
if (!isKnownEnglishOrUserWord(engMid, helpers) || !PARTICLE_KEYS.has(korTail)) continue
|
||||
const tailConv = helpers.latinToHangul(korTail)
|
||||
if (tailConv.complete && particleAgrees(tailConv.text, finalSoundOfEnglishWord(engMid)) !== false) {
|
||||
return `${korPrefixConv.text}${engMid}${tailConv.text}`
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// URL · 파일 경로 · 이메일 런 판별 (araso/docs/url-run.md)
|
||||
// ============================================================
|
||||
|
||||
/**
|
||||
* 토큰이 속한 비공백 런(run)이 URL · 파일 경로 · 이메일 · 코드 식별자인지 판별한다.
|
||||
*
|
||||
* - URL/경로/이메일 마커(`://`, `www.`, `~/`, `./`, `../`, 2개 이상 `/`, `domain.tld/`, `localhost:`, `user@domain`)가
|
||||
* 포함된 비공백 런 안의 토큰은 변환하지 않는다.
|
||||
* - 반면 단독 `@멘션`(@dlrjs → @이건), 단독 슬래시(`ska/du` → `남/여`, `TV/fkeldh` → `TV/라디오`),
|
||||
* 약어 뒤 조사(`L.A.fh` → `L.A.로`), 비율 표기(`1:1ansdml` → `1:1문의`)는 변환을 허용한다.
|
||||
*/
|
||||
export function isUrlOrPathRun(prefix: string, tokenStart: number, tokenEnd: number): boolean {
|
||||
let runStart = tokenStart
|
||||
while (runStart > 0 && !/\s/u.test(prefix[runStart - 1] ?? '')) {
|
||||
runStart -= 1
|
||||
}
|
||||
let runEnd = tokenEnd
|
||||
while (runEnd < prefix.length && !/\s/u.test(prefix[runEnd] ?? '')) {
|
||||
runEnd += 1
|
||||
}
|
||||
const run = prefix.slice(runStart, runEnd)
|
||||
|
||||
if (run.includes('://')) return true
|
||||
if (/^(?:www\.|~\/|\.\/|\.\.\/|localhost:)/iu.test(run)) return true
|
||||
if ((run.match(/\//gu)?.length ?? 0) >= 2) return true
|
||||
if (/[A-Za-z0-9]\.[A-Za-z]{2,}\//u.test(run)) return true
|
||||
if (/[A-Za-z0-9._+-]@[A-Za-z0-9]/u.test(run)) return true
|
||||
if (/[\\_$#`<>{}=]/u.test(run)) return true
|
||||
|
||||
// 토큰 바로 앞이나 뒤가 도메인 점(example.com)인 경우 (단, L.A.fh 처럼 대문자 약어 뒤 조사는 허용)
|
||||
const before = prefix[tokenStart - 1] ?? ''
|
||||
const after = prefix[tokenEnd] ?? ''
|
||||
if (after === '.' && /[A-Za-z]/u.test(prefix[tokenEnd + 1] ?? '')) return true
|
||||
if (before === '.') {
|
||||
const beforeDot = prefix.slice(runStart, tokenStart)
|
||||
const tokenText = prefix.slice(tokenStart, tokenEnd)
|
||||
const isAbbrevWithParticle = /^(?:[A-Z]\.){2,}$/u.test(beforeDot) && PARTICLE_KEYS.has(tokenText)
|
||||
if (!isAbbrevWithParticle) return true
|
||||
}
|
||||
if (before === ':' || after === ':') {
|
||||
const beforeColon = prefix.slice(runStart, tokenStart)
|
||||
if (!/^\d+:\d*$/u.test(beforeColon)) return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
|
@ -215,6 +215,8 @@ export enum ErrorCode {
|
|||
ExternalOpenFailed = 940,
|
||||
SoundPlayFailed = 950,
|
||||
AppAlreadyRunning = 960,
|
||||
/** 앱 업데이트 확인·다운로드·설치 요청 실패 */
|
||||
AppUpdateFailed = 990,
|
||||
UnknownError = 999
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -53,7 +53,18 @@ export type {
|
|||
LocalSuggestionHints,
|
||||
SuggestionJoint
|
||||
} from './suggestion-text'
|
||||
export { extractTerminalPromptPrefix } from './terminal-prompt'
|
||||
export {
|
||||
TerminalKeystrokeTracker,
|
||||
composeHangul2Set,
|
||||
extractTerminalActiveContext,
|
||||
extractTerminalPromptPrefix,
|
||||
vkToPrintableChar
|
||||
} from './terminal-prompt'
|
||||
export type {
|
||||
TerminalActiveContext,
|
||||
TerminalKeyInput,
|
||||
TerminalVimMode
|
||||
} from './terminal-prompt'
|
||||
|
||||
// ============================================================
|
||||
// 기하 — 정본은 popup-placement.ts (좌표 공간 · 배치 정책). 기존 import 경로를 유지한다.
|
||||
|
|
@ -203,10 +214,11 @@ export const PASTE_INSERTION_THRESHOLD_CHARS = 200
|
|||
* 끝에서 쓰거나 지운 것이다. 같으면(편집 없음) true.
|
||||
*/
|
||||
export function isEditAtTextEnd(prevRaw: string, nextRaw: string): boolean {
|
||||
// RichEdit 계열(카카오톡 등)은 값 끝에 줄끝 문자(\r)를 붙여 돌려준다. 그대로 비교하면 모든 편집이
|
||||
// "뒤에 기존 글이 남은 중간 편집" 이 되어 caret-unknown 으로 막혔다(실측 2026-10-03, 카톡 79회).
|
||||
const prevText = prevRaw.replace(/[\r\n\u200b\ufeff]+$/u, '')
|
||||
const nextText = nextRaw.replace(/[\r\n\u200b\ufeff]+$/u, '')
|
||||
// RichEdit 계열(카카오톡 등)은 값 끝에 줄끝 문자(\r)를 붙여 돌려주고, 한영 자동 전환 직후에는
|
||||
// 교체 전후 텍스트가 모두 공백("dkssud " → "안녕 ")으로 끝난다. 끝 공백·줄끝 문자를 그대로 비교하면
|
||||
// 마지막 글자(' ')가 같아 중간 편집으로 오인하고 caret-unknown 으로 막힌다(실측 2026-10-03·2026-10-26).
|
||||
const prevText = prevRaw.replace(/[\s\u200b\ufeff]+$/u, '')
|
||||
const nextText = nextRaw.replace(/[\s\u200b\ufeff]+$/u, '')
|
||||
if (prevText === nextText) return true
|
||||
let prefix = 0
|
||||
const maxPrefix = Math.min(prevText.length, nextText.length)
|
||||
|
|
@ -434,6 +446,8 @@ export type SuggestionSkipReason =
|
|||
* 접두가 "문서 끝" 이라 실제 커서 위치와 무관하다 — 수락하면 문서 중간에 엉뚱한 문장이 붙는다.
|
||||
*/
|
||||
| 'caret-unknown'
|
||||
/** 주소·경로·쿼리를 치는 중 — 문장을 이어 쓸 자리가 아니다 */
|
||||
| 'address-input'
|
||||
|
||||
export type SuggestionDecision =
|
||||
| { action: 'request'; prefix: string }
|
||||
|
|
@ -480,6 +494,21 @@ export interface SuggestionPolicyInput {
|
|||
* 순서가 중요하다: 비활성·보안(비밀번호)·IME 조합은 다른 어떤 조건보다 먼저 차단한다.
|
||||
* `clear` 는 "오버레이를 지워야 한다"는 뜻이고, `skip` 은 "이번엔 넘어간다"이다.
|
||||
*/
|
||||
/**
|
||||
* 커서 앞 마지막 덩어리(공백 없는 토큰)가 주소·경로·쿼리인가.
|
||||
* "https://…", "www.…", "example.com/…", "D:/work/…", "?utm_source=…" 처럼 생겼으면 그렇다.
|
||||
* 한글 문장 속 "1/2" 같은 짧은 것은 아니다(점·슬래시 구조가 있어야 한다).
|
||||
*/
|
||||
export function isAddressInput(prefix: string): boolean {
|
||||
if (/\s$/u.test(prefix)) return false
|
||||
const token = prefix.split(/\s+/u).pop() ?? ''
|
||||
if (token.length < 4) return false
|
||||
if (/^(https?:\/\/|www\.|file:)/iu.test(token) || token.includes('://')) return true
|
||||
if (/^[a-z0-9-]+(\.[a-z0-9-]+)+(\/|$|\?|#|:)/iu.test(token) && /\.[a-z]{2,}/iu.test(token)) return true
|
||||
if (/^[a-z]:[\\/]/iu.test(token) || /^\.{0,2}\//u.test(token)) return true
|
||||
return /[?&][\w.-]+=/u.test(token)
|
||||
}
|
||||
|
||||
export function decideSuggestion(input: SuggestionPolicyInput): SuggestionDecision {
|
||||
if (!input.enabled) return { action: 'clear', reason: 'disabled' }
|
||||
if (input.isPassword) return { action: 'clear', reason: 'password-field' }
|
||||
|
|
@ -508,6 +537,8 @@ export function decideSuggestion(input: SuggestionPolicyInput): SuggestionDecisi
|
|||
|
||||
const prefix = normalizeRequestPrefix(input.prefix)
|
||||
if (!prefix) return { action: 'clear', reason: 'empty-prefix' }
|
||||
// 주소창·경로 입력 중에는 문장을 제안하지 않는다(실측: "haramlog.app/ja/beta" 에 고객센터식 문장 12개).
|
||||
if (isAddressInput(input.prefix)) return { action: 'clear', reason: 'address-input' }
|
||||
// 문장이 끝났다고 막지 않는다.
|
||||
//
|
||||
// 이 기능은 "다음 문장 제안" 이다 — 마침표/물음표 뒤야말로 다음 문장이 필요한
|
||||
|
|
@ -755,7 +786,16 @@ export const TERMINAL_APPS: readonly string[] = Object.freeze([
|
|||
'pwsh',
|
||||
'mintty',
|
||||
'alacritty',
|
||||
'wezterm',
|
||||
'wezterm-gui',
|
||||
'kitty',
|
||||
'ghostty',
|
||||
'putty',
|
||||
'MobaXterm',
|
||||
'Kitedesk',
|
||||
'nvim-qt',
|
||||
'neovide',
|
||||
'gvim',
|
||||
'Hyper',
|
||||
'Tabby',
|
||||
'Warp'
|
||||
|
|
@ -788,10 +828,23 @@ export const LEARNING_EXCLUDED_APPS: readonly string[] = Object.freeze([
|
|||
'clion64',
|
||||
'goland64',
|
||||
'studio64',
|
||||
'sublime_text',
|
||||
'Agent Switchboard'
|
||||
'sublime_text'
|
||||
])
|
||||
|
||||
/**
|
||||
* 그 앱 안에서만 배우는 앱 — 표본(typing_samples)에만 앱 이름과 함께 저장하고, 공용 문구·그래프에는 넣지 않는다.
|
||||
* 제안할 때는 같은 앱의 표본에서만 이어 쓴 글을 찾는다.
|
||||
*
|
||||
* Agent Switchboard 는 사용자가 가장 많이 타이핑하는 곳인데(2026-10-25), 2026-09-24 에 학습 제외였다 — 개발 지시가
|
||||
* 카카오톡 제안으로 번졌기 때문. 앱 안으로 가두면 번지지 않으면서 그 앱의 제안에는 재료가 생긴다.
|
||||
*/
|
||||
export const APP_SCOPED_LEARNING_APPS: readonly string[] = Object.freeze(['Agent Switchboard'])
|
||||
|
||||
/** 이 앱의 글은 그 앱 안에서만 쓰는가 (공용 문구·그래프 금지). */
|
||||
export function isAppScopedLearning(appName: string | null | undefined): boolean {
|
||||
return !!appName && isAppExcluded(appName, APP_SCOPED_LEARNING_APPS)
|
||||
}
|
||||
|
||||
/**
|
||||
* 제안 이력에 입력 문맥(접두) 원문을 남겨도 되는가.
|
||||
*
|
||||
|
|
@ -817,6 +870,36 @@ export function shouldLearnFromApp(appName: string | null | undefined): boolean
|
|||
return !(appName && isAppExcluded(appName, LEARNING_EXCLUDED_APPS))
|
||||
}
|
||||
|
||||
/**
|
||||
* 터미널·코드 에디터·에이전트 허브(예: Integrated Terminal 이나 캔버스 터미널이 들어 있는 개발 도구)인가.
|
||||
*
|
||||
* 이 표면에서는:
|
||||
* 1) 일반 철자·모델 오타 교정은 끄고 한영 자판 전환(layoutOnly)만 수행하며,
|
||||
* 2) UIA 가 텍스트를 돌려주지 않는 캔버스 영역(xterm.js, Kitedesk 등)에서도 키스트로크 추적으로
|
||||
* 한영 자판 자동 전환과 Vim 모드 전환을 지원한다.
|
||||
*/
|
||||
export function isTerminalOrDeveloperSurface(appName: string | null | undefined): boolean {
|
||||
if (!appName) return false
|
||||
return isTerminalApp(appName) || !shouldLearnFromApp(appName) || isAppScopedLearning(appName)
|
||||
}
|
||||
|
||||
/**
|
||||
* xterm.js 기반 임베디드 터미널(Agent Switchboard, VS Code, Cursor, Hyper, Tabby 등)의 숨은 입력창인가.
|
||||
*
|
||||
* `<textarea class="xterm-helper-textarea" aria-label="Terminal input">` 는 UIA 에서 편집 가능한
|
||||
* ValuePattern 컨트롤로 잡히지만, xterm.js 가 Backspace·Space·영문 키를 `preventDefault()` 로 가로채
|
||||
* PTY 로만 보내고 `<textarea>.value` 는 Enter/Ctrl+C 전까지 비우지 않는다.
|
||||
* 따라서 `<textarea>.value` 를 일반 입력칸 텍스트로 쓰면 교정 후에도 옛 한글이 그대로 남아 무한 재교정이 일어난다.
|
||||
*/
|
||||
export function isXtermHelperControl(
|
||||
snapshot: Pick<FocusSnapshot, 'className' | 'controlName'>
|
||||
): boolean {
|
||||
const cls = snapshot.className?.trim().toLowerCase() ?? ''
|
||||
if (cls.includes('xterm-helper-textarea')) return true
|
||||
const name = snapshot.controlName?.trim().toLowerCase() ?? ''
|
||||
return name === 'terminal input'
|
||||
}
|
||||
|
||||
/** 공백을 뺀 글자 중 문자(모든 언어)가 이 비율 이상이어야 문장으로 본다. */
|
||||
const MIN_LETTER_RATIO = 0.6
|
||||
|
||||
|
|
@ -1210,6 +1293,8 @@ export interface SuggestionCandidate {
|
|||
rank: number
|
||||
/** 접두와의 이음새 — 생략하면 'separate' (joinSuggestion 참고) */
|
||||
joint?: SuggestionJoint
|
||||
/** 'personal' = 모델을 기다리지 않고 먼저 띄운 내 기록(개인 n-gram) 후보. 생략하면 모델 후보 */
|
||||
source?: 'personal'
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -1268,6 +1353,11 @@ export interface SuggestionState {
|
|||
minPrefixChars: number
|
||||
/** 응답 제한 (ms) — 넘기면 이번 요청을 버린다 (모델이 느린 하드웨어 보호) */
|
||||
requestTimeoutMs: number
|
||||
/**
|
||||
* 후보 없이 끝났음을 잠깐 알린다 — "생성 중" 이 떴다가 말없이 사라지면 고장처럼 보였다(2026-10-25 사용자 요청).
|
||||
* 'no-suggestion' 이면 오버레이가 "제안 사항 없음" 을 1초 보여 주고 닫힌다.
|
||||
*/
|
||||
notice: 'no-suggestion' | null
|
||||
/** 연속 실패로 잠시 쉬는 중인가 */
|
||||
coolingDown: boolean
|
||||
/** 학습 동의 상태 요약 (UI 표시) */
|
||||
|
|
|
|||
|
|
@ -580,6 +580,16 @@ export const IPC_CHANNELS = {
|
|||
ACCEPTED: 'suggestionPopup:accepted',
|
||||
DISMISSED: 'suggestionPopup:dismissed',
|
||||
},
|
||||
|
||||
// ── App Update (UpdateService) ──
|
||||
APP_UPDATE: {
|
||||
GET_STATUS: 'appUpdate:getStatus',
|
||||
CHECK: 'appUpdate:check',
|
||||
DOWNLOAD: 'appUpdate:download',
|
||||
INSTALL: 'appUpdate:install',
|
||||
// Main → Renderer events
|
||||
STATUS_CHANGED: 'appUpdate:statusChanged',
|
||||
},
|
||||
} as const
|
||||
|
||||
// 타입 유틸리티: 채널명 유니온 추출
|
||||
|
|
|
|||
|
|
@ -678,6 +678,7 @@ export type KeyBindingActionId =
|
|||
| 'history-popup'
|
||||
| 'command-popup'
|
||||
| 'suggestion-accept'
|
||||
| 'suggestion-accept-word'
|
||||
| 'suggestion-next'
|
||||
| 'suggestion-prev'
|
||||
| 'suggestion-dismiss'
|
||||
|
|
@ -788,6 +789,16 @@ export const KEYBINDING_ACTIONS: readonly KeyBindingActionSpec[] = Object.freeze
|
|||
// 좌우 화살표는 쓰지 않는다 — Intel 그래픽 드라이버의 화면 회전 단축키와 겹친다.
|
||||
defaultBindings: [kb(VK.Enter, { ctrl: true, alt: true })]
|
||||
},
|
||||
{
|
||||
id: 'suggestion-accept-word',
|
||||
group: 'input',
|
||||
labelKey: 'keybinding.action.suggestionAcceptWord',
|
||||
descriptionKey: 'keybinding.action.suggestionAcceptWord.desc',
|
||||
holdMode: false,
|
||||
doublePress: false,
|
||||
// 제안의 첫 단어만 받는다 — 앞은 맞고 뒤에서 갈라지는 제안이 많다(2026-10-25 실데이터). 나머지는 창에 남는다.
|
||||
defaultBindings: [kb(VK.Space, { ctrl: true, alt: true })]
|
||||
},
|
||||
{
|
||||
id: 'suggestion-next',
|
||||
group: 'input',
|
||||
|
|
|
|||
192
packages/core/src/personal-ngram.ts
Normal file
192
packages/core/src/personal-ngram.ts
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
// packages/core/src/personal-ngram.ts
|
||||
//
|
||||
// 개인 n-gram 예측기 — 사용자가 직접 쓴 문장만으로 다음 어절(과 짧은 구)을 맞힌다.
|
||||
//
|
||||
// 왜 LLM 앞에 두는가 (재생 평가 2026-10-24, docs/evidence/2026-10-24-suggestion-accuracy-research.md):
|
||||
// 같은 120건에서 gemma4:e4b 첫 어절 적중은 3~5%, 이 방식은 정확 14% · 단어 앞부분 일치 24% 였고
|
||||
// 지연은 0 이다. Gmail Smart Compose 도 사용자별 n-gram 을 섞어 정확 일치를 +10% 올렸다(KDD 2019).
|
||||
//
|
||||
// 규칙
|
||||
// - 문장을 넘지 않는다: 문장 경계(.!?… 줄바꿈)에서 끊어 센다. 새 문장의 첫 어절은 예측하지 않는다.
|
||||
// - 단어를 끝냈으면(끝이 공백) 다음 어절을, 단어 중간이면 그 어절의 나머지를 낸다.
|
||||
// - 지지(같은 문맥에서 나온 횟수)와 비율(문맥 전체 중 그 어절의 몫)이 기준을 넘을 때만 낸다.
|
||||
// - 확신이 이어지면 최대 maxWords 어절까지 구로 늘린다(트라이그램 → 바이그램 순).
|
||||
|
||||
export interface PersonalNgramOptions {
|
||||
/** 같은 문맥 뒤에 이 어절이 나온 최소 횟수 */
|
||||
minSupport?: number
|
||||
/** 문맥 뒤에 나온 어절 중 이 어절의 최소 비율 */
|
||||
minConfidence?: number
|
||||
/** 한 번에 내는 최대 어절 수 */
|
||||
maxWords?: number
|
||||
/** 두 번째 어절부터 늘릴 때의 최소 비율 — 첫 어절보다 깐깐하게 둘 수 있다(기본: minConfidence) */
|
||||
extendConfidence?: number
|
||||
}
|
||||
|
||||
export interface PersonalNgramPrediction {
|
||||
/** 삽입할 글 — joint 가 'attach' 면 커서 앞 글자에 바로 붙는다(단어 중간) */
|
||||
text: string
|
||||
joint: 'attach' | 'separate'
|
||||
/** 첫 어절의 지지 횟수 */
|
||||
support: number
|
||||
/** 첫 어절의 비율 (0~1) */
|
||||
confidence: number
|
||||
}
|
||||
|
||||
const DEFAULTS: Required<Omit<PersonalNgramOptions, 'extendConfidence'>> = { minSupport: 2, minConfidence: 0.25, maxWords: 3 }
|
||||
|
||||
/**
|
||||
* 앱 기준값 — 재생 평가 격자 탐색(2026-10-24, 120건)에서 골랐다. 앱과 평가가 같은 값을 쓴다.
|
||||
* - 단어 중간: 쓰던 어절을 늘이는 것은 쉽다 → 넉넉하게 (노출 53%, 첫 어절 34%, 통째로 맞음 26%)
|
||||
* - 단어 끝: 처음엔 비율 0.5 로 깐깐하게 뒀다가(노출 14%) 실사용에서 "그리고만 쳐도 단어 하나는 나와야 한다"는
|
||||
* 지적을 받았다(2026-10-24). 가장 흔한 다음 어절 하나는 낮은 비율로도 내고, 둘째 어절은 확신할 때만 붙인다.
|
||||
* 2차 실사용(2026-10-25)에서 지지 1·비율 0.1 로 풀었더니 근거 약한 어절("구글로 로그인해서", 비율 0.14)이 떠
|
||||
* "상관없는 아무말" 이 됐다. 확실한 것만 남긴다 — 단어 끝은 지지 2·비율 0.5 (평가: 노출 14%, 적중 29%).
|
||||
*/
|
||||
export const PERSONAL_NGRAM_SETTINGS = {
|
||||
midWord: { minSupport: 1, minConfidence: 0.25, maxWords: 2, extendConfidence: 0.5 },
|
||||
wordEnd: { minSupport: 2, minConfidence: 0.5, maxWords: 2, extendConfidence: 0.5 }
|
||||
} as const satisfies Record<string, Required<PersonalNgramOptions>>
|
||||
|
||||
/**
|
||||
* 앱이 쓰는 예측.
|
||||
* - 끝이 공백: 다음 어절.
|
||||
* - 끝이 글자: 먼저 그 어절의 나머지를 찾고, 없으면 그 어절을 이미 다 쓴 것으로 보고 다음 어절을 낸다.
|
||||
* 한글은 멈춰도 마지막 음절이 조합 중이라 공백이 늦게 온다 — "그리고" 에서 멈추면 다음 어절이 필요하다.
|
||||
*/
|
||||
export function predictPersonalContinuation(model: PersonalNgramModel, prefix: string): PersonalNgramPrediction | null {
|
||||
if (/\s$/u.test(prefix)) return model.predict(prefix, PERSONAL_NGRAM_SETTINGS.wordEnd)
|
||||
return model.predict(prefix, PERSONAL_NGRAM_SETTINGS.midWord) ?? model.predict(`${prefix} `, PERSONAL_NGRAM_SETTINGS.wordEnd)
|
||||
}
|
||||
const SENTENCE_SPLIT = /[.!?。!?…\n]+/u
|
||||
const EDGE_PUNCTUATION = /^["'“‘([]+|["'”’)\],;:~]+$/gu
|
||||
|
||||
/** 비교용 어절 — 앞뒤 따옴표·괄호·쉼표를 떼고 소문자로 */
|
||||
function key(word: string): string {
|
||||
return word.replace(EDGE_PUNCTUATION, '').toLowerCase()
|
||||
}
|
||||
|
||||
function tokenize(sentence: string): string[] {
|
||||
return sentence
|
||||
.split(/\s+/u)
|
||||
.map(key)
|
||||
.filter((word) => word.length > 0)
|
||||
}
|
||||
|
||||
function increment(table: Map<string, Map<string, number>>, context: string, word: string): void {
|
||||
let followers = table.get(context)
|
||||
if (!followers) {
|
||||
followers = new Map()
|
||||
table.set(context, followers)
|
||||
}
|
||||
followers.set(word, (followers.get(word) ?? 0) + 1)
|
||||
}
|
||||
|
||||
interface Pick {
|
||||
word: string
|
||||
support: number
|
||||
confidence: number
|
||||
}
|
||||
|
||||
function best(followers: Map<string, number> | undefined, accept: (word: string) => boolean): Pick | null {
|
||||
if (!followers) return null
|
||||
let total = 0
|
||||
let top: { word: string; support: number } | null = null
|
||||
for (const [word, count] of followers) {
|
||||
if (!accept(word)) continue
|
||||
total += count
|
||||
// 동률이면 먼저 센 어절(삽입 순서)을 둔다 — 결과가 실행마다 같아야 한다.
|
||||
if (!top || count > top.support) top = { word, support: count }
|
||||
}
|
||||
return top ? { ...top, confidence: top.support / total } : null
|
||||
}
|
||||
|
||||
export class PersonalNgramModel {
|
||||
private readonly _bigram = new Map<string, Map<string, number>>()
|
||||
private readonly _trigram = new Map<string, Map<string, number>>()
|
||||
/** 단어 중간 완성용 — 문맥 없이 어절 빈도 */
|
||||
private readonly _unigram = new Map<string, number>()
|
||||
private _texts = 0
|
||||
|
||||
get textCount(): number {
|
||||
return this._texts
|
||||
}
|
||||
|
||||
addText(text: string): void {
|
||||
this._texts += 1
|
||||
for (const sentence of text.split(SENTENCE_SPLIT)) {
|
||||
const words = tokenize(sentence)
|
||||
for (let index = 0; index < words.length; index += 1) {
|
||||
const word = words[index]
|
||||
this._unigram.set(word, (this._unigram.get(word) ?? 0) + 1)
|
||||
if (index >= 1) increment(this._bigram, words[index - 1], word)
|
||||
if (index >= 2) increment(this._trigram, `${words[index - 2]} ${words[index - 1]}`, word)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 커서 앞 글(prefix)에 이어질 어절을 낸다. 확신이 없으면 null.
|
||||
* prefix 끝이 공백이면 다음 어절, 아니면 지금 어절의 나머지부터.
|
||||
*/
|
||||
predict(prefix: string, options: PersonalNgramOptions = {}): PersonalNgramPrediction | null {
|
||||
const settings = { ...DEFAULTS, ...options }
|
||||
const extendConfidence = Math.max(settings.minConfidence, options.extendConfidence ?? settings.minConfidence)
|
||||
const sentences = prefix.split(SENTENCE_SPLIT)
|
||||
const current = sentences[sentences.length - 1] ?? ''
|
||||
const wordFinished = /\s$/u.test(current)
|
||||
const words = tokenize(current)
|
||||
if (words.length === 0) return null
|
||||
|
||||
const passes = (pick: Pick | null): pick is Pick =>
|
||||
pick !== null && pick.support >= settings.minSupport && pick.confidence >= settings.minConfidence
|
||||
|
||||
let context = words
|
||||
let first: Pick | null
|
||||
let joint: 'attach' | 'separate' = 'separate'
|
||||
let partial = ''
|
||||
|
||||
if (wordFinished) {
|
||||
first = this._next(context, () => true, passes)
|
||||
} else {
|
||||
// 단어 중간 — 쓰던 어절을 늘인 어절만 후보다. 앞 어절이 없으면 어절 빈도로.
|
||||
partial = words[words.length - 1]
|
||||
context = words.slice(0, -1)
|
||||
const extends_ = (word: string) => word.length > partial.length && word.startsWith(partial)
|
||||
first = context.length > 0 ? this._next(context, extends_, passes) : null
|
||||
if (!first) {
|
||||
const unigram = new Map([...this._unigram].filter(([word]) => extends_(word)))
|
||||
const pick = best(unigram, () => true)
|
||||
first = passes(pick) ? pick : null
|
||||
}
|
||||
joint = 'attach'
|
||||
}
|
||||
if (!first) return null
|
||||
|
||||
const output = [joint === 'attach' ? first.word.slice(partial.length) : first.word]
|
||||
const chain = [...context, first.word]
|
||||
// 둘째 어절부터는 한 번 쓴 것만으로는 붙이지 않는다 — 근거 1회짜리 구가 길게 붙으면 대부분 틀린다.
|
||||
const extendPasses = (pick: Pick | null): pick is Pick =>
|
||||
passes(pick) && pick.confidence >= extendConfidence && pick.support >= Math.max(2, settings.minSupport)
|
||||
while (output.length < settings.maxWords) {
|
||||
const next = this._next(chain, () => true, extendPasses)
|
||||
if (!next) break
|
||||
output.push(next.word)
|
||||
chain.push(next.word)
|
||||
}
|
||||
|
||||
return { text: output.join(' '), joint, support: first.support, confidence: first.confidence }
|
||||
}
|
||||
|
||||
private _next(context: string[], accept: (word: string) => boolean, passes: (pick: Pick | null) => pick is Pick): Pick | null {
|
||||
if (context.length >= 2) {
|
||||
const tri = best(this._trigram.get(`${context[context.length - 2]} ${context[context.length - 1]}`), accept)
|
||||
if (passes(tri)) return tri
|
||||
}
|
||||
if (context.length >= 1) {
|
||||
const bi = best(this._bigram.get(context[context.length - 1]), accept)
|
||||
if (passes(bi)) return bi
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
72
packages/core/src/suggestion-confidence.ts
Normal file
72
packages/core/src/suggestion-confidence.ts
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
// packages/core/src/suggestion-confidence.ts
|
||||
//
|
||||
// 모델 제안을 토큰 로그 확률로 거르고 자른다 (Gmail Smart Compose 의 신뢰도 게이팅과 같은 생각).
|
||||
//
|
||||
// 재생 평가(2026-10-24, gemma4:e4b, 120건): 그대로 보여 주면 첫 어절 적중이 3% 였다. 첫 어절 확률이
|
||||
// 낮은 후보를 숨기고, 확률이 꺾이는 토큰에서 자르면 노출은 4~6% 로 줄지만 적중은 20~29% 로 오른다.
|
||||
// 틀린 제안은 맞는 제안보다 읽는 비용이 5배 이상 크다(arXiv 2403.15502) — 덜 보여 주는 편이 낫다.
|
||||
|
||||
export interface TokenLogprob {
|
||||
token: string
|
||||
logprob: number
|
||||
}
|
||||
|
||||
export interface ConfidenceSettings {
|
||||
/** 첫 어절을 이루는 토큰 로그 확률 합의 하한 — 못 넘으면 후보를 버린다 */
|
||||
firstWordMin: number
|
||||
/** 토큰 하나의 로그 확률 하한 — 처음 못 넘는 토큰 앞에서 자른다 */
|
||||
tokenMin: number
|
||||
}
|
||||
|
||||
// 첫 어절 −0.5 로 시작했다가 실사용(2026-10-25)에서 거의 안 떠 −1.0 으로 풀었다(시뮬레이션: 노출 ~15%, 적중 ~11%).
|
||||
export const SUGGESTION_CONFIDENCE: ConfidenceSettings = { firstWordMin: -1.0, tokenMin: -1.0 }
|
||||
|
||||
/**
|
||||
* 후보가 화면·앞 글에 이미 있는 글을 그대로 베꼈는가.
|
||||
* 베낀 글은 모델이 높은 확률을 주므로 확신 검사로 걸러지지 않는다(실측 2026-10-25: 앞 대화의 문장이 그대로 제안됨).
|
||||
* 후보 앞 12자(짧으면 전체, 8자 이상일 때만)가 문맥에 그대로 있으면 베낀 것으로 본다.
|
||||
*/
|
||||
export function copiesContext(candidate: string, context: string): boolean {
|
||||
const squash = (text: string) => text.replace(/\s+/gu, ' ').trim()
|
||||
const text = squash(candidate)
|
||||
if (text.length < 8) return false
|
||||
return squash(context).includes(text.slice(0, 12))
|
||||
}
|
||||
|
||||
export interface ConfidenceCut {
|
||||
/** 원문(토큰을 이은 글)에서 남길 글자 수 */
|
||||
keepChars: number
|
||||
firstWordLogprob: number
|
||||
}
|
||||
|
||||
const SENTENCE_END = /[.!?。!?…\n]/u
|
||||
|
||||
/**
|
||||
* 남길 길이를 정한다. 첫 어절이 자신 없거나 남는 글이 없으면 null.
|
||||
* 어절 중간에서 끊기면 그 어절은 통째로 뺀다 — 반쪽 단어를 제안하지 않는다.
|
||||
*/
|
||||
export function cutByConfidence(
|
||||
tokens: TokenLogprob[],
|
||||
settings: ConfidenceSettings = SUGGESTION_CONFIDENCE
|
||||
): ConfidenceCut | null {
|
||||
let text = ''
|
||||
let firstWordLogprob = 0
|
||||
let firstWordDone = false
|
||||
for (const { token, logprob } of tokens) {
|
||||
const startsWord = /^\s/u.test(token)
|
||||
if (text.trim().length > 0 && startsWord) firstWordDone = true
|
||||
if (logprob < settings.tokenMin) {
|
||||
if (!startsWord && !/\s$/u.test(text)) {
|
||||
// 어절 중간에서 멈췄다 — 그 어절을 뺀다(첫 어절이었다면 남는 게 없다).
|
||||
const lastSpace = text.trimEnd().search(/\s\S*$/u)
|
||||
text = lastSpace >= 0 ? text.slice(0, lastSpace) : ''
|
||||
}
|
||||
break
|
||||
}
|
||||
text += token
|
||||
if (!firstWordDone && text.trim().length > 0) firstWordLogprob += logprob
|
||||
if (SENTENCE_END.test(token)) break
|
||||
}
|
||||
if (text.trim().length === 0 || firstWordLogprob < settings.firstWordMin) return null
|
||||
return { keepChars: text.length, firstWordLogprob }
|
||||
}
|
||||
|
|
@ -68,8 +68,9 @@ export function normalizeSessionPrefix(prefix: string): string {
|
|||
*/
|
||||
const LIST_MARKER_PATTERN = /^(?:[-*•]+[.)\]]?|\d{1,3}[.)\]])\s+/u
|
||||
const WRAPPING_QUOTES_PATTERN = /^["'“”‘’`]+|["'“”‘’`]+$/gu
|
||||
/** 모델이 지시문을 되풀이한 경우 (llm-prompts 회귀와 같은 부류) */
|
||||
const INSTRUCTION_ECHO_PATTERN = /^(suggestion|completion|candidate|output|answer|다음 문장)\s*[::]/iu
|
||||
/** 모델이 지시문·섹션 헤더를 되풀이한 경우 (llm-prompts 지시문 누출 차단) */
|
||||
const INSTRUCTION_ECHO_PATTERN =
|
||||
/^(?:(?:suggestion|completion|candidate|output|answer|다음 문장|입력)\s*[::]|\[(?:이어 쓰기 지시|지금 쓰는 문장|직전 문장|앞 문맥|현재 앱|글의 첫머리|글에 나온 사실)\])|(?:검색어입니다\.?|검색어 키워드 몇 개로만|짧게 이어 쓰세요|나머지 부분만 쓰세요|새 문장 하나를 쓰세요|바로 뒤부터 이어 쓰세요|겹치지 않는 다른 문장을 쓰세요)/iu
|
||||
const TEMPLATE_ECHO_PATTERN = /^\{\{.*\}\}$/u
|
||||
|
||||
/**
|
||||
|
|
@ -326,6 +327,17 @@ function firstCodePoint(text: string): string {
|
|||
* - 앞 글자가 여는 괄호/따옴표·경로 기호가 아니고, 후보가 닫는 구두점으로 시작하지 않는다.
|
||||
* - 이음새 양쪽 어느 쪽도 띄어 쓰지 않는 문자 체계(중·일·태 등, CJK 구두점)가 아니다.
|
||||
*/
|
||||
/**
|
||||
* 후보를 첫 어절과 나머지로 나눈다 (단어 단위 수락). 어절 뒤 문장부호는 그 어절에 붙인다.
|
||||
* 나머지가 없으면 rest 는 빈 문자열 — 호출자는 통째로 수락한다.
|
||||
*/
|
||||
export function splitFirstWord(candidate: string): { word: string; rest: string } {
|
||||
const text = candidate.replace(/^\s+/u, '')
|
||||
const match = /^\S+/u.exec(text)
|
||||
if (!match) return { word: text, rest: '' }
|
||||
return { word: match[0], rest: text.slice(match[0].length).replace(/^\s+/u, '') }
|
||||
}
|
||||
|
||||
export function joinSuggestion(rawPrefix: string, candidate: string, joint: SuggestionJoint = 'separate'): string {
|
||||
if (!candidate) return candidate
|
||||
// 단어 중간 이어 쓰기는 공백 없이 붙인다. 원문이 이미 공백으로 끝났으면 이어 붙일 단어가 없다
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
// packages/core — 터미널 화면에서 "지금 치고 있는 입력 줄" 을 뽑는다.
|
||||
// packages/core — 터미널 화면 및 키스트로크 스트림에서 "지금 치고 있는 입력 줄" 과 Vim 모드를 뽑는다.
|
||||
//
|
||||
// 터미널은 화면 버퍼 전체가 입력창으로 읽힌다(상태줄·명령·출력 포함). 제안은 입력 줄만
|
||||
// 접두로 써야 하므로 그 파싱을 한곳에 둔다. 순수 함수만 둔다 — 다른 core 모듈을
|
||||
// import 하지 않는다 (input-intelligence 가 이 모듈을 다시 export 한다).
|
||||
// 터미널은 화면 버퍼 전체가 입력창으로 읽히거나(Windows Terminal 등: 상태줄·명령·출력 포함),
|
||||
// 캔버스/레거시 표면(Kitedesk, WezTerm, Alacritty, xterm.js 등: UIA 텍스트 길이 0)으로 노출된다.
|
||||
// 또한 터미널 내부에서 Vim/Neovim 을 쓸 때는 화면 중간 줄을 편집하면서 하단 상태줄(-- INSERT --,
|
||||
// -- NORMAL --, :wq 등)이 함께 바뀐다.
|
||||
// 순수 함수와 순수 상태 머신만 둔다 — 다른 core 모듈을 import 하지 않는다
|
||||
// (input-intelligence 가 이 모듈을 다시 export 한다).
|
||||
|
||||
/** 상자·블록·도형·기타 기호·딩뱃 — 터미널 UI/상태줄의 지문이다. */
|
||||
export const NON_PROSE_GLYPH_PATTERN = /[←-⇿─-➿⬀-⯿]/u
|
||||
|
|
@ -18,6 +21,25 @@ const TERMINAL_BORDER_PATTERN = /^[\s─━═┄┈╌╍╭╮╰╯┌┐└
|
|||
const TERMINAL_EDGE_PATTERN = /^[\s│┃║]+|[\s│┃║]+$/gu
|
||||
const TERMINAL_SCAN_LINES = 40
|
||||
|
||||
export type TerminalVimMode = 'insert' | 'normal' | 'command' | null
|
||||
|
||||
export interface TerminalActiveContext {
|
||||
prefix: string
|
||||
caretReliable: boolean
|
||||
vimMode: TerminalVimMode
|
||||
isVimScreen: boolean
|
||||
}
|
||||
|
||||
const VIM_INSERT_LINE_PATTERN =
|
||||
/(?:--\s*(?:INSERT|REPLACE|끼워넣기|바꾸기|\(insert\))\s*--|\b(?:INSERT|REPLACE)\b.*(?:\d+,\d+|\d+%|Top|Bot|All))/iu
|
||||
const VIM_NORMAL_LINE_PATTERN =
|
||||
/(?:--\s*(?:NORMAL|VISUAL|SELECT|비주얼|선택)(?:\s+LINE|\s+BLOCK)?\s*--|\b(?:NORMAL|VISUAL)\b.*(?:\d+,\d+|\d+%|Top|Bot|All))/iu
|
||||
const VIM_RULER_LINE_PATTERN = /\s{2,}\d+,\d+(?:-\d+)?\s+(?:All|Top|Bot|\d+%)\s*$/u
|
||||
const VIM_TILDE_LINE_PATTERN = /^\s*~\s*$/u
|
||||
const VIM_COMMAND_LINE_PATTERN = /^:([ㄱ-ㅎㅏ-ㅣ가-힣A-Za-z0-9!%\s_.-]{1,60})$/u
|
||||
const VIM_SHELL_LAUNCH_PATTERN = /^(?:sudo\s+)?(?:vim|nvim|vi|vimdiff|view|gvim|neovide)(?:\s|$)/u
|
||||
const VIM_WINDOW_TITLE_PATTERN = /(?:^|[\s\-—–\\/])(?:n?vim|vi|gvim|neovide)(?:$|[\s\-—–.])/iu
|
||||
|
||||
/**
|
||||
* 터미널 화면 텍스트에서 "지금 치고 있는 입력" 을 뽑는다.
|
||||
*
|
||||
|
|
@ -31,10 +53,13 @@ export function extractTerminalPromptPrefix(screen: string | null | undefined):
|
|||
const lines = screen.replace(/\r/g, '').split('\n')
|
||||
const start = Math.max(0, lines.length - TERMINAL_SCAN_LINES)
|
||||
for (let i = lines.length - 1; i >= start; i--) {
|
||||
const line = lines[i].replace(TERMINAL_EDGE_PATTERN, '')
|
||||
const rawLine = lines[i]
|
||||
const hasSingleTrailingSpace = !/[│┃║]\s*$/u.test(rawLine) && /\S $/u.test(rawLine)
|
||||
const line = rawLine.replace(TERMINAL_EDGE_PATTERN, '')
|
||||
const match = TERMINAL_PROMPT_PATTERN.exec(line)
|
||||
if (!match) continue
|
||||
const parts = [match[1].trimEnd()]
|
||||
let lastIdx = i
|
||||
for (let j = i + 1; j < lines.length; j++) {
|
||||
const raw = lines[j]
|
||||
if (TERMINAL_BORDER_PATTERN.test(raw)) break
|
||||
|
|
@ -42,8 +67,856 @@ export function extractTerminalPromptPrefix(screen: string | null | undefined):
|
|||
// 상태줄 기호(◑ ▕░ 등)가 섞인 줄은 입력이 아니다.
|
||||
if (!continuation || NON_PROSE_GLYPH_PATTERN.test(continuation)) break
|
||||
parts.push(continuation)
|
||||
lastIdx = j
|
||||
}
|
||||
return parts.join(' ').replace(/\s+/gu, ' ').trimStart()
|
||||
const joined = parts.join(' ').replace(/\s+/gu, ' ').trimStart()
|
||||
const tailHasSpace =
|
||||
lastIdx === i
|
||||
? hasSingleTrailingSpace
|
||||
: !/[│┃║]\s*$/u.test(lines[lastIdx]) && /\S $/u.test(lines[lastIdx])
|
||||
return joined && tailHasSpace ? `${joined} ` : joined
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function isTerminalStatusOrNoiseLine(rawLine: string): boolean {
|
||||
const line = rawLine.replace(TERMINAL_EDGE_PATTERN, '')
|
||||
if (!line.trim()) return true
|
||||
if (TERMINAL_BORDER_PATTERN.test(rawLine)) return true
|
||||
if (NON_PROSE_GLYPH_PATTERN.test(line)) return true
|
||||
if (VIM_TILDE_LINE_PATTERN.test(line)) return true
|
||||
if (VIM_INSERT_LINE_PATTERN.test(line) || VIM_NORMAL_LINE_PATTERN.test(line)) return true
|
||||
if (VIM_RULER_LINE_PATTERN.test(line)) return true
|
||||
return false
|
||||
}
|
||||
|
||||
function trimGridPadding(rawLine: string): string {
|
||||
if (!/[│┃║]\s*$/u.test(rawLine) && /\S $/u.test(rawLine)) {
|
||||
return `${rawLine.trimEnd()} `
|
||||
}
|
||||
return rawLine.trimEnd()
|
||||
}
|
||||
|
||||
function stripPromptFromLine(line: string): string {
|
||||
const hasSingleSpace = !/[│┃║]\s*$/u.test(line) && /\S $/u.test(line)
|
||||
const cleaned = line.replace(TERMINAL_EDGE_PATTERN, '')
|
||||
const match = TERMINAL_PROMPT_PATTERN.exec(cleaned)
|
||||
if (match) {
|
||||
const body = match[1].trimEnd()
|
||||
return body && hasSingleSpace ? `${body} ` : body
|
||||
}
|
||||
// Vim 줄 번호 표시(" 12 dkssudgktpdy")가 앞에 있으면 걷어낸다.
|
||||
const lineNumMatch = /^\s*\d+\s+(.*)$/u.exec(cleaned)
|
||||
if (lineNumMatch) {
|
||||
const body = lineNumMatch[1].trimEnd()
|
||||
return body && hasSingleSpace ? `${body} ` : body
|
||||
}
|
||||
return cleaned && hasSingleSpace ? `${cleaned} ` : cleaned
|
||||
}
|
||||
|
||||
function commonSuffixLength(a: string, b: string): number {
|
||||
const max = Math.min(a.length, b.length)
|
||||
let count = 0
|
||||
while (count < max && a[a.length - 1 - count] === b[b.length - 1 - count]) {
|
||||
count += 1
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
/**
|
||||
* 터미널 화면 스냅샷(직전/현재)에서 Vim 모드와 현재 편집 중인 활성 줄 접두를 추출한다.
|
||||
*/
|
||||
export function extractTerminalActiveContext(
|
||||
prevScreen: string | null | undefined,
|
||||
currScreen: string | null | undefined,
|
||||
lastActivePrefix?: string | null,
|
||||
windowTitle?: string | null,
|
||||
trackerVimMode?: TerminalVimMode
|
||||
): TerminalActiveContext {
|
||||
if (!currScreen) {
|
||||
return { prefix: '', caretReliable: false, vimMode: null, isVimScreen: false }
|
||||
}
|
||||
|
||||
const currLines = currScreen.replace(/\r/g, '').split('\n')
|
||||
const nonEmptyBottom: string[] = []
|
||||
for (let i = currLines.length - 1; i >= 0 && nonEmptyBottom.length < 5; i -= 1) {
|
||||
const cleaned = currLines[i].replace(TERMINAL_EDGE_PATTERN, '').trimEnd()
|
||||
if (cleaned.trim().length > 0) {
|
||||
nonEmptyBottom.push(cleaned)
|
||||
}
|
||||
}
|
||||
|
||||
const tildeCount = currLines.filter((line) => VIM_TILDE_LINE_PATTERN.test(line)).length
|
||||
const hasInsertIndicator = nonEmptyBottom.some((line) => VIM_INSERT_LINE_PATTERN.test(line))
|
||||
const hasNormalIndicator = nonEmptyBottom.some((line) => VIM_NORMAL_LINE_PATTERN.test(line))
|
||||
const hasRulerIndicator = nonEmptyBottom.some((line) => VIM_RULER_LINE_PATTERN.test(line))
|
||||
const titleLooksLikeVim = !!windowTitle && VIM_WINDOW_TITLE_PATTERN.test(windowTitle)
|
||||
const hasVimBufferChrome =
|
||||
tildeCount >= 2 || hasInsertIndicator || hasNormalIndicator || hasRulerIndicator
|
||||
|
||||
// 1. Vim 명령줄 모드 (:ㅈㅂ, :wq, :q! 등)
|
||||
for (let i = 0; i < Math.min(2, nonEmptyBottom.length); i += 1) {
|
||||
const candidate = nonEmptyBottom[i].replace(/\s+\d+,\d+.*$/u, '').trimEnd()
|
||||
if (VIM_COMMAND_LINE_PATTERN.test(candidate)) {
|
||||
return {
|
||||
prefix: candidate,
|
||||
caretReliable: true,
|
||||
vimMode: 'command',
|
||||
isVimScreen: true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 화면에 Vim 상태줄·물결표(~)·룰러가 전혀 없고 셸 프롬프트(PS ...>, $ 등)가 있으면
|
||||
// 창 제목에 vim/nvim 이 남아 있더라도 일반 셸 입력 줄로 처리한다.
|
||||
if (!hasVimBufferChrome) {
|
||||
const promptPrefix = extractTerminalPromptPrefix(currScreen)
|
||||
if (promptPrefix !== null) {
|
||||
return {
|
||||
prefix: promptPrefix,
|
||||
caretReliable: true,
|
||||
vimMode: null,
|
||||
isVimScreen: false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const isVimScreen = hasVimBufferChrome || titleLooksLikeVim
|
||||
|
||||
let vimMode: TerminalVimMode = null
|
||||
if (hasInsertIndicator) {
|
||||
vimMode = 'insert'
|
||||
} else if (hasNormalIndicator) {
|
||||
vimMode = 'normal'
|
||||
} else if (isVimScreen) {
|
||||
vimMode = trackerVimMode === 'insert' ? 'insert' : 'normal'
|
||||
}
|
||||
|
||||
// 3. Vim 노멀/비주얼 모드에서는 일반 텍스트 교정을 막는다.
|
||||
if (vimMode === 'normal') {
|
||||
return {
|
||||
prefix: '',
|
||||
caretReliable: false,
|
||||
vimMode: 'normal',
|
||||
isVimScreen: true
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 직전 스냅샷과 현재 스냅샷을 줄 단위로 비교해 실제 타이핑이 일어난 내용 줄을 찾는다.
|
||||
if (prevScreen && prevScreen !== currScreen) {
|
||||
const prevLines = prevScreen.replace(/\r/g, '').split('\n')
|
||||
const scanStart = Math.max(0, currLines.length - TERMINAL_SCAN_LINES)
|
||||
for (let i = currLines.length - 1; i >= scanStart; i -= 1) {
|
||||
const currRaw = currLines[i]
|
||||
if (isTerminalStatusOrNoiseLine(currRaw)) continue
|
||||
const prevRaw = prevLines[i] ?? ''
|
||||
const currClean = trimGridPadding(currRaw)
|
||||
const prevClean = trimGridPadding(prevRaw)
|
||||
if (currClean === prevClean) continue
|
||||
|
||||
const suffixLen = commonSuffixLength(prevClean, currClean)
|
||||
const editEnd = Math.max(0, currClean.length - suffixLen)
|
||||
const editedSlice = editEnd > 0 ? currClean.slice(0, editEnd) : currClean
|
||||
const prefix = stripPromptFromLine(editedSlice)
|
||||
if (prefix.trim().length > 0) {
|
||||
return {
|
||||
prefix,
|
||||
caretReliable: true,
|
||||
vimMode,
|
||||
isVimScreen
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 화면이 직전 스냅샷과 같고(예: 멈춤 뒤 settle 타이머) 마지막 활성 줄이 여전히 화면에 있으면 유지한다.
|
||||
if (lastActivePrefix && lastActivePrefix.trim().length > 0) {
|
||||
const trimmedLast = lastActivePrefix.trimEnd()
|
||||
if (currScreen.includes(trimmedLast)) {
|
||||
const keepTrailingSpace = !lastActivePrefix.endsWith(' ') && currScreen.includes(`${trimmedLast} `)
|
||||
return {
|
||||
prefix: keepTrailingSpace ? `${trimmedLast} ` : lastActivePrefix,
|
||||
caretReliable: true,
|
||||
vimMode,
|
||||
isVimScreen
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 셸 프롬프트 줄 폴백
|
||||
const promptPrefix = extractTerminalPromptPrefix(currScreen)
|
||||
if (promptPrefix !== null) {
|
||||
return {
|
||||
prefix: promptPrefix,
|
||||
caretReliable: true,
|
||||
vimMode,
|
||||
isVimScreen
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Vim INSERT 모드인데 직전 화면이 없으면 가장 아래쪽 일반 내용 줄을 사용한다.
|
||||
if (vimMode === 'insert') {
|
||||
for (let i = currLines.length - 1; i >= 0; i -= 1) {
|
||||
if (isTerminalStatusOrNoiseLine(currLines[i])) continue
|
||||
const prefix = stripPromptFromLine(trimGridPadding(currLines[i]))
|
||||
if (prefix.trim().length > 0) {
|
||||
return {
|
||||
prefix,
|
||||
caretReliable: true,
|
||||
vimMode: 'insert',
|
||||
isVimScreen: true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { prefix: '', caretReliable: false, vimMode, isVimScreen }
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 두벌식 키 스트림 조합기 + 터미널/Vim 키스트로크 추적기
|
||||
// ============================================================
|
||||
|
||||
const CHO = [
|
||||
'ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ',
|
||||
'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ'
|
||||
] as const
|
||||
|
||||
const JUNG = [
|
||||
'ㅏ', 'ㅐ', 'ㅑ', 'ㅒ', 'ㅓ', 'ㅔ', 'ㅕ', 'ㅖ', 'ㅗ', 'ㅘ',
|
||||
'ㅙ', 'ㅚ', 'ㅛ', 'ㅜ', 'ㅝ', 'ㅞ', 'ㅟ', 'ㅠ', 'ㅡ', 'ㅢ', 'ㅣ'
|
||||
] as const
|
||||
|
||||
const JONG = [
|
||||
'', 'ㄱ', 'ㄲ', 'ㄳ', 'ㄴ', 'ㄵ', 'ㄶ', 'ㄷ', 'ㄹ', 'ㄺ',
|
||||
'ㄻ', 'ㄼ', 'ㄽ', 'ㄾ', 'ㄿ', 'ㅀ', 'ㅁ', 'ㅂ', 'ㅄ', 'ㅅ',
|
||||
'ㅆ', 'ㅇ', 'ㅈ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ'
|
||||
] as const
|
||||
|
||||
const KEY_TO_JAMO: Readonly<Record<string, string>> = {
|
||||
q: 'ㅂ', Q: 'ㅃ', w: 'ㅈ', W: 'ㅉ', e: 'ㄷ', E: 'ㄸ', r: 'ㄱ', R: 'ㄲ', t: 'ㅅ', T: 'ㅆ',
|
||||
y: 'ㅛ', u: 'ㅕ', i: 'ㅑ', o: 'ㅐ', O: 'ㅒ', p: 'ㅔ', P: 'ㅖ',
|
||||
a: 'ㅁ', s: 'ㄴ', d: 'ㅇ', f: 'ㄹ', g: 'ㅎ', h: 'ㅗ', j: 'ㅓ', k: 'ㅏ', l: 'ㅣ',
|
||||
z: 'ㅋ', x: 'ㅌ', c: 'ㅊ', v: 'ㅍ', b: 'ㅠ', n: 'ㅜ', m: 'ㅡ'
|
||||
}
|
||||
|
||||
const COMPOUND_VOWEL: Readonly<Record<string, string>> = {
|
||||
'ㅗㅏ': 'ㅘ', 'ㅗㅐ': 'ㅙ', 'ㅗㅣ': 'ㅚ',
|
||||
'ㅜㅓ': 'ㅝ', 'ㅜㅔ': 'ㅞ', 'ㅜㅣ': 'ㅟ',
|
||||
'ㅡㅣ': 'ㅢ'
|
||||
}
|
||||
|
||||
const COMPOUND_JONG: Readonly<Record<string, string>> = {
|
||||
'ㄱㅅ': 'ㄳ', 'ㄴㅈ': 'ㄵ', 'ㄴㅎ': 'ㄶ',
|
||||
'ㄹㄱ': 'ㄺ', 'ㄹㅁ': 'ㄻ', 'ㄹㅂ': 'ㄼ', 'ㄹㅅ': 'ㄽ', 'ㄹㅌ': 'ㄾ', 'ㄹㅍ': 'ㄿ', 'ㄹㅎ': 'ㅀ',
|
||||
'ㅂㅅ': 'ㅄ'
|
||||
}
|
||||
|
||||
/**
|
||||
* 영문 두벌식 키열을 Windows 한국어 IME 와 동일하게 조합한다.
|
||||
*/
|
||||
export function composeHangul2Set(keys: string): string {
|
||||
const jamos: string[] = []
|
||||
for (const ch of keys) {
|
||||
const mapped = KEY_TO_JAMO[ch] ?? KEY_TO_JAMO[ch.toLowerCase()]
|
||||
if (!mapped) {
|
||||
jamos.push(ch)
|
||||
} else {
|
||||
jamos.push(mapped)
|
||||
}
|
||||
}
|
||||
|
||||
let out = ''
|
||||
let i = 0
|
||||
const isConsonant = (j: string): boolean => CHO.includes(j as (typeof CHO)[number])
|
||||
const isVowel = (j: string): boolean => JUNG.includes(j as (typeof JUNG)[number])
|
||||
|
||||
while (i < jamos.length) {
|
||||
const curr = jamos[i]
|
||||
// 자음 + 모음 → 음절 시작
|
||||
if (isConsonant(curr) && i + 1 < jamos.length && isVowel(jamos[i + 1])) {
|
||||
const choIdx = CHO.indexOf(curr as (typeof CHO)[number])
|
||||
let v = jamos[i + 1]
|
||||
i += 2
|
||||
if (i < jamos.length && isVowel(jamos[i]) && COMPOUND_VOWEL[v + jamos[i]]) {
|
||||
v = COMPOUND_VOWEL[v + jamos[i]]
|
||||
i += 1
|
||||
}
|
||||
const jungIdx = JUNG.indexOf(v as (typeof JUNG)[number])
|
||||
let jong = ''
|
||||
// 받침 확인 (다음 자음이 모음과 결합해 연음되면 받침으로 쓰지 않는다)
|
||||
if (i < jamos.length && isConsonant(jamos[i])) {
|
||||
const c1 = jamos[i]
|
||||
const nextIsVowel = i + 1 < jamos.length && isVowel(jamos[i + 1])
|
||||
if (!nextIsVowel && JONG.includes(c1 as (typeof JONG)[number])) {
|
||||
jong = c1
|
||||
i += 1
|
||||
if (i < jamos.length && isConsonant(jamos[i])) {
|
||||
const c2 = jamos[i]
|
||||
const afterC2IsVowel = i + 1 < jamos.length && isVowel(jamos[i + 1])
|
||||
const compound = COMPOUND_JONG[c1 + c2]
|
||||
if (!afterC2IsVowel && compound) {
|
||||
jong = compound
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const jongIdx = JONG.indexOf(jong as (typeof JONG)[number])
|
||||
out += String.fromCharCode(0xac00 + (choIdx * 21 + jungIdx) * 28 + Math.max(0, jongIdx))
|
||||
continue
|
||||
}
|
||||
// 단독 모음 합성 (ㅗ + ㅏ = ㅘ 등)
|
||||
if (isVowel(curr) && i + 1 < jamos.length && isVowel(jamos[i + 1]) && COMPOUND_VOWEL[curr + jamos[i + 1]]) {
|
||||
out += COMPOUND_VOWEL[curr + jamos[i + 1]]
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
out += curr
|
||||
i += 1
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const SHIFTED_DIGITS = ')!@#$%^&*('
|
||||
|
||||
export function vkToPrintableChar(vk: number, shift: boolean): string | null {
|
||||
if (vk >= 0x41 && vk <= 0x5a) {
|
||||
return shift ? String.fromCharCode(vk) : String.fromCharCode(vk + 32)
|
||||
}
|
||||
if (vk >= 0x30 && vk <= 0x39) {
|
||||
return shift ? (SHIFTED_DIGITS[vk - 0x30] ?? null) : String.fromCharCode(vk)
|
||||
}
|
||||
if (vk >= 0x60 && vk <= 0x69) {
|
||||
return String.fromCharCode(vk - 0x30)
|
||||
}
|
||||
switch (vk) {
|
||||
case 0xba:
|
||||
return shift ? ':' : ';'
|
||||
case 0xbb:
|
||||
return shift ? '+' : '='
|
||||
case 0xbc:
|
||||
return shift ? '<' : ','
|
||||
case 0xbd:
|
||||
return shift ? '_' : '-'
|
||||
case 0xbe:
|
||||
return shift ? '>' : '.'
|
||||
case 0xbf:
|
||||
return shift ? '?' : '/'
|
||||
case 0xc0:
|
||||
return shift ? '~' : '`'
|
||||
case 0xdb:
|
||||
return shift ? '{' : '['
|
||||
case 0xdc:
|
||||
return shift ? '|' : '\\'
|
||||
case 0xdd:
|
||||
return shift ? '}' : ']'
|
||||
case 0xde:
|
||||
return shift ? '"' : "'"
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export interface TerminalKeyInput {
|
||||
hwnd: number | null
|
||||
windowTitle?: string | null
|
||||
vk: number | null
|
||||
rawKeycode?: number
|
||||
shift: boolean
|
||||
ctrl: boolean
|
||||
alt: boolean
|
||||
meta: boolean
|
||||
koreanIme?: boolean | null
|
||||
now?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 터미널 및 Vim 키스트로크 추적기.
|
||||
*
|
||||
* UIA 가 터미널 줄 끝 공백을 잘라 버리거나(Windows Terminal), 캔버스/원격 터미널(Kitedesk,
|
||||
* WezTerm, Alacritty, xterm.js 등)에서 텍스트를 전혀 돌려주지 않을 때(len=0), 그리고 Vim 의
|
||||
* 노멀/입력/명령줄 모드를 오갈 때 정확한 현재 줄 접두와 조합 상태를 복원한다.
|
||||
*/
|
||||
export class TerminalKeystrokeTracker {
|
||||
private _hwnd: number | null = null
|
||||
private _committed = ''
|
||||
private _composingKeys = ''
|
||||
private _koreanIme = false
|
||||
private _imm32Supported = false
|
||||
private _lastImeToggleAt = 0
|
||||
private _vimSession = false
|
||||
private _vimMode: TerminalVimMode = null
|
||||
private _pendingVimOperator = ''
|
||||
private _afterEscape = false
|
||||
private _lastKeyWasSpace = false
|
||||
private _shellPromptScreen = false
|
||||
private _prevScreen: string | null = null
|
||||
private _lastScreenPrefix: string | null = null
|
||||
private _unreplacedStart = 0
|
||||
private _lastXtermValue = ''
|
||||
|
||||
reset(): void {
|
||||
this._committed = ''
|
||||
this._composingKeys = ''
|
||||
this._pendingVimOperator = ''
|
||||
this._afterEscape = false
|
||||
this._lastKeyWasSpace = false
|
||||
this._lastScreenPrefix = null
|
||||
this._unreplacedStart = 0
|
||||
}
|
||||
|
||||
onPointerOrFocusChange(hwnd?: number | null): void {
|
||||
if (hwnd !== undefined && hwnd !== this._hwnd) {
|
||||
this._hwnd = hwnd
|
||||
this._imm32Supported = false
|
||||
this._vimSession = false
|
||||
this._vimMode = null
|
||||
this._shellPromptScreen = false
|
||||
this._prevScreen = null
|
||||
this._lastXtermValue = ''
|
||||
}
|
||||
this.reset()
|
||||
}
|
||||
|
||||
onKeyDown(input: TerminalKeyInput): void {
|
||||
const now = input.now ?? Date.now()
|
||||
if (input.hwnd !== null && input.hwnd !== this._hwnd) {
|
||||
this._hwnd = input.hwnd
|
||||
this._imm32Supported = false
|
||||
this._vimSession = false
|
||||
this._vimMode = null
|
||||
this._shellPromptScreen = false
|
||||
this._prevScreen = null
|
||||
this._lastXtermValue = ''
|
||||
this.reset()
|
||||
}
|
||||
if (!this._shellPromptScreen && input.windowTitle && VIM_WINDOW_TITLE_PATTERN.test(input.windowTitle)) {
|
||||
this._vimSession = true
|
||||
if (this._vimMode === null) this._vimMode = 'normal'
|
||||
}
|
||||
|
||||
// 한/영 전환 키 (VK_HANGUL = 0x15, uiohook keycode = 112)
|
||||
if (input.rawKeycode === 112 || input.vk === 0x15) {
|
||||
this._flushComposing()
|
||||
// Vim 노멀 모드(또는 Esc 직후)에서 i/a/o 를 눌러 입력 모드로 들어간 직후 한/영 키를 눌렀다면
|
||||
// 앞에 찍힌 i/a/o 는 Vim 명령이므로 버퍼에서 비운다.
|
||||
if (
|
||||
(this._afterEscape || this._vimSession) &&
|
||||
/^[hjklwbe0$dugG]*[iIaAoOsSCR]$/u.test(this._committed)
|
||||
) {
|
||||
this._committed = ''
|
||||
this._vimSession = true
|
||||
this._vimMode = 'insert'
|
||||
this._afterEscape = false
|
||||
}
|
||||
this._koreanIme = !this._koreanIme
|
||||
this._lastImeToggleAt = now
|
||||
return
|
||||
}
|
||||
|
||||
// Chromium/Electron(Agent Switchboard, VS Code 등)은 TSF IME 를 사용해 최상위 HWND 의
|
||||
// ImmGetDefaultIMEWnd(IMC_GETCONVERSIONMODE)가 한글 상태에서도 항상 false(0)를 돌려준다.
|
||||
// 따라서 해당 창에서 한 번이라도 true 가 관측된 경우(_imm32Supported)에만 false 로의 하향 동기화를 허용한다.
|
||||
if (typeof input.koreanIme === 'boolean') {
|
||||
if (input.koreanIme) {
|
||||
this._imm32Supported = true
|
||||
}
|
||||
if ((input.koreanIme || this._imm32Supported) && now - this._lastImeToggleAt > 250) {
|
||||
if (this._koreanIme && !input.koreanIme) {
|
||||
this._flushComposing()
|
||||
}
|
||||
this._koreanIme = input.koreanIme
|
||||
}
|
||||
}
|
||||
|
||||
const { vk, shift, ctrl, alt, meta } = input
|
||||
|
||||
// Escape 또는 Ctrl+[ / Ctrl+C → 현재 줄 초기화 (실제 Esc/Ctrl+[ 만 _afterEscape 설정)
|
||||
const isRealEscape = vk === 0x1b || (ctrl && !alt && !meta && vk === 0xdb)
|
||||
const isCtrlC = ctrl && !alt && !meta && vk === 0x43
|
||||
if (isRealEscape || isCtrlC) {
|
||||
this.reset()
|
||||
if (isRealEscape) {
|
||||
this._afterEscape = true
|
||||
}
|
||||
if (this._vimSession) {
|
||||
this._vimMode = 'normal'
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 기타 단축키(Ctrl/Alt/Meta 조합)는 버퍼를 비운다.
|
||||
if (ctrl || alt || meta) {
|
||||
this.reset()
|
||||
return
|
||||
}
|
||||
|
||||
if (vk === null) {
|
||||
this._lastKeyWasSpace = false
|
||||
return
|
||||
}
|
||||
|
||||
// Enter (0x0D)
|
||||
if (vk === 0x0d) {
|
||||
this._lastKeyWasSpace = false
|
||||
const fullLine = this.currentPrefix().trim()
|
||||
if (VIM_SHELL_LAUNCH_PATTERN.test(fullLine)) {
|
||||
this._vimSession = true
|
||||
this._vimMode = 'normal'
|
||||
} else if (this._vimMode === 'command') {
|
||||
const cmd = fullLine.replace(/^:/u, '').trim()
|
||||
if (/^(?:q|qa|wq|wqa|x|xa)!?$/u.test(cmd)) {
|
||||
this._vimSession = false
|
||||
this._vimMode = null
|
||||
} else {
|
||||
this._vimMode = 'normal'
|
||||
}
|
||||
}
|
||||
this.reset()
|
||||
return
|
||||
}
|
||||
|
||||
// Tab (0x09), 화살표(0x25..0x28), Home/End/PgUp/PgDn/Delete(0x21..0x24, 0x2E)
|
||||
if (vk === 0x09 || (vk >= 0x21 && vk <= 0x28) || vk === 0x2e) {
|
||||
this.reset()
|
||||
return
|
||||
}
|
||||
|
||||
// Backspace (0x08)
|
||||
if (vk === 0x08) {
|
||||
this._lastKeyWasSpace = false
|
||||
if (this._composingKeys.length > 0) {
|
||||
this._composingKeys = this._composingKeys.slice(0, -1)
|
||||
return
|
||||
}
|
||||
if (this._committed.length > 0) {
|
||||
this._committed = this._committed.slice(0, -1)
|
||||
this._unreplacedStart = Math.min(this._unreplacedStart, this._committed.length)
|
||||
if (this._vimMode === 'command' && this._committed.length === 0) {
|
||||
this._vimMode = 'normal'
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Space (0x20)
|
||||
if (vk === 0x20) {
|
||||
if (this._vimMode === 'normal') {
|
||||
this._pendingVimOperator = ''
|
||||
this._lastKeyWasSpace = false
|
||||
return
|
||||
}
|
||||
this._flushComposing()
|
||||
this._committed += ' '
|
||||
this._lastKeyWasSpace = true
|
||||
return
|
||||
}
|
||||
|
||||
this._lastKeyWasSpace = false
|
||||
const ch = vkToPrintableChar(vk, shift)
|
||||
if (!ch) return
|
||||
|
||||
// Vim 노멀 모드에서의 키 처리
|
||||
if (this._vimMode === 'normal') {
|
||||
this._handleVimNormalChar(ch)
|
||||
return
|
||||
}
|
||||
|
||||
// 아직 vimSession 이 확정되지 않았더라도 Esc 직후나 줄 맨 앞에서 ':' 를 치면 즉시 Vim 명령줄 모드로 본다.
|
||||
if (ch === ':' && (this._afterEscape || (this._committed.length === 0 && this._composingKeys.length === 0))) {
|
||||
this._flushComposing()
|
||||
this._vimSession = true
|
||||
this._vimMode = 'command'
|
||||
this._afterEscape = false
|
||||
this._committed = ':'
|
||||
return
|
||||
}
|
||||
|
||||
// 알파벳 키 (A..Z)
|
||||
if (vk >= 0x41 && vk <= 0x5a) {
|
||||
// Esc 직후 영문 상태에서 노멀 모드 이동키(h/j/k/l 2회 이상 또는 기존 vimSession) 뒤에 i/a/o/s 를 친 경우
|
||||
if (
|
||||
this._afterEscape &&
|
||||
!this._koreanIme &&
|
||||
/^[iIaAoOsSCR]$/u.test(ch) &&
|
||||
/^[hjklwbe0$dugG]*$/u.test(this._committed) &&
|
||||
(this._vimSession || /[hjkl]{2,}/u.test(this._committed))
|
||||
) {
|
||||
this._vimSession = true
|
||||
this._vimMode = 'insert'
|
||||
this._afterEscape = false
|
||||
this._committed = ''
|
||||
this._composingKeys = ''
|
||||
return
|
||||
}
|
||||
|
||||
if (this._koreanIme) {
|
||||
const normKey = /^[QWERTPO]$/u.test(ch) ? ch : ch.toLowerCase()
|
||||
this._composingKeys += normKey
|
||||
this._commitOverflowSyllables()
|
||||
} else {
|
||||
this._flushComposing()
|
||||
this._committed += ch
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 숫자 및 문장부호: 한글 조합을 먼저 확정하고 문자를 추가한다.
|
||||
this._flushComposing()
|
||||
this._committed += ch
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로그램(오타 교정)이 커서 앞 deleteCount 글자를 지우고 insertText 를 넣었을 때 버퍼를 동기화한다.
|
||||
* 비동기 치환 도중 사용자가 추가로 친 글자(baseLength 이후)가 있으면 유실하지 않고 뒤에 보존한다.
|
||||
*/
|
||||
applyReplacement(deleteCount: number, insertText: string, baseLength?: number): void {
|
||||
const full = this.currentPrefix()
|
||||
const targetEnd =
|
||||
baseLength !== undefined && baseLength >= 0 ? Math.min(baseLength, full.length) : full.length
|
||||
const keepLen = Math.max(0, targetEnd - Math.max(0, deleteCount))
|
||||
const typedAfterStart = full.slice(targetEnd)
|
||||
this._committed = full.slice(0, keepLen) + insertText + typedAfterStart
|
||||
this._composingKeys = ''
|
||||
this._lastKeyWasSpace = this._committed.endsWith(' ')
|
||||
this._lastScreenPrefix = this._committed
|
||||
this._unreplacedStart = keepLen + insertText.length
|
||||
}
|
||||
|
||||
currentPrefix(): string {
|
||||
return this._committed + (this._composingKeys ? composeHangul2Set(this._composingKeys) : '')
|
||||
}
|
||||
|
||||
get isComposing(): boolean {
|
||||
return this._composingKeys.length > 0
|
||||
}
|
||||
|
||||
get vimMode(): TerminalVimMode {
|
||||
return this._vimMode
|
||||
}
|
||||
|
||||
/**
|
||||
* UIA 텍스트가 없는 터미널(Kitedesk, 캔버스 터미널 등)에서 현재 키스트로크 문맥을 돌려준다.
|
||||
*/
|
||||
getSnapshot(
|
||||
hwnd: number | null,
|
||||
windowTitle?: string | null
|
||||
): { prefix: string; caretReliable: boolean; isComposing: boolean; vimMode: TerminalVimMode } {
|
||||
if (hwnd !== null && this._hwnd !== null && hwnd !== this._hwnd) {
|
||||
return { prefix: '', caretReliable: false, isComposing: false, vimMode: null }
|
||||
}
|
||||
if (windowTitle && VIM_WINDOW_TITLE_PATTERN.test(windowTitle)) {
|
||||
this._vimSession = true
|
||||
}
|
||||
if (this._vimMode === 'normal') {
|
||||
return { prefix: '', caretReliable: false, isComposing: false, vimMode: 'normal' }
|
||||
}
|
||||
const prefix = this.currentPrefix()
|
||||
return {
|
||||
prefix,
|
||||
caretReliable: prefix.length > 0,
|
||||
isComposing: this.isComposing,
|
||||
vimMode: this._vimMode
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* UIA 화면 버퍼가 있는 터미널(Windows Terminal, pwsh, cmd 등)에서 화면 파싱과 키스트로크 버퍼를 결합한다.
|
||||
*/
|
||||
reconcileWithScreen(
|
||||
currScreen: string | null | undefined,
|
||||
windowTitle?: string | null
|
||||
): { prefix: string; caretReliable: boolean; isComposing: boolean; vimMode: TerminalVimMode } {
|
||||
const screenCtx = extractTerminalActiveContext(
|
||||
this._prevScreen,
|
||||
currScreen,
|
||||
this._lastScreenPrefix,
|
||||
windowTitle,
|
||||
this._vimMode
|
||||
)
|
||||
this._prevScreen = currScreen ?? null
|
||||
|
||||
if (screenCtx.isVimScreen) {
|
||||
this._shellPromptScreen = false
|
||||
this._vimSession = true
|
||||
if (screenCtx.vimMode !== null) {
|
||||
if (screenCtx.vimMode === 'normal' && this._vimMode !== 'normal') {
|
||||
this.reset()
|
||||
}
|
||||
this._vimMode = screenCtx.vimMode
|
||||
}
|
||||
} else if (screenCtx.prefix.length > 0) {
|
||||
this._shellPromptScreen = true
|
||||
this._vimSession = false
|
||||
this._vimMode = null
|
||||
}
|
||||
|
||||
if (this._vimMode === 'normal' || screenCtx.vimMode === 'normal') {
|
||||
return { prefix: '', caretReliable: false, isComposing: false, vimMode: 'normal' }
|
||||
}
|
||||
|
||||
const tracked = this.currentPrefix()
|
||||
|
||||
// Vim 명령줄(:ㅈㅂ 등)은 화면에 실제 ':...' 줄이 보이면 그 줄을 정본으로 삼고,
|
||||
// 아직 화면에 반영되지 않은 방금 친 키가 있을 때만(tracked 가 screenCtx.prefix 로 시작할 때) tracked 를 쓴다.
|
||||
if (screenCtx.vimMode === 'command' || this._vimMode === 'command') {
|
||||
let cmdPrefix: string
|
||||
if (screenCtx.prefix.startsWith(':')) {
|
||||
cmdPrefix =
|
||||
tracked.startsWith(screenCtx.prefix) && tracked.length > screenCtx.prefix.length
|
||||
? tracked
|
||||
: screenCtx.prefix
|
||||
} else if (tracked.startsWith(':')) {
|
||||
cmdPrefix = tracked
|
||||
} else {
|
||||
cmdPrefix = screenCtx.prefix || tracked
|
||||
}
|
||||
this._committed = cmdPrefix
|
||||
this._composingKeys = ''
|
||||
this._lastScreenPrefix = cmdPrefix
|
||||
return {
|
||||
prefix: cmdPrefix,
|
||||
caretReliable: cmdPrefix.length > 1,
|
||||
isComposing: this.isComposing,
|
||||
vimMode: 'command'
|
||||
}
|
||||
}
|
||||
|
||||
// Windows Terminal 등 그리드 터미널은 줄 끝 공백을 UIA 텍스트에서 잘라 버린다.
|
||||
// 방금 Space 키를 쳤다면(또는 키 버퍼 끝에 공백이 있다면) 화면 줄 끝에 공백을 복원한다.
|
||||
let resolved = screenCtx.prefix
|
||||
if (!resolved.trim() && tracked.length > 0) {
|
||||
resolved = tracked
|
||||
} else if (resolved.trim().length > 0 && !resolved.endsWith(' ') && this._lastKeyWasSpace) {
|
||||
resolved = resolved.trimEnd() + ' '
|
||||
}
|
||||
|
||||
this._lastScreenPrefix = resolved
|
||||
return {
|
||||
prefix: resolved,
|
||||
caretReliable: resolved.trim().length > 0,
|
||||
isComposing: this.isComposing,
|
||||
vimMode: this._vimMode ?? screenCtx.vimMode
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* xterm.js(`xterm-helper-textarea`)의 `.value` 와 키스트로크 버퍼를 결합한다.
|
||||
*
|
||||
* xterm.js 는 Backspace·Space·영문 키를 `preventDefault()` 로 가로채 PTY 로만 보내고
|
||||
* `<textarea>.value` 는 Enter/Ctrl+C 전까지 비우지 않는다. 따라서 실제 편집 문맥은
|
||||
* 키스트로크 버퍼(`currentPrefix()`)를 정본으로 삼되, `.value` 에 새 한글이 들어오면
|
||||
* 한글 IME 활성 신호로 삼아 아직 치환되지 않은 영문 키들을 두벌식 한글로 복원한다.
|
||||
*/
|
||||
reconcileWithXtermValue(
|
||||
xtermValue: string | null | undefined,
|
||||
hwnd: number | null,
|
||||
windowTitle?: string | null
|
||||
): { prefix: string; caretReliable: boolean; isComposing: boolean; vimMode: TerminalVimMode } {
|
||||
const raw = xtermValue ?? ''
|
||||
if (hwnd !== null && this._hwnd !== null && hwnd !== this._hwnd) {
|
||||
this._hwnd = hwnd
|
||||
this._imm32Supported = false
|
||||
this._vimSession = false
|
||||
this._vimMode = null
|
||||
this._shellPromptScreen = false
|
||||
this._prevScreen = null
|
||||
this._lastXtermValue = raw
|
||||
this.reset()
|
||||
} else if (raw !== this._lastXtermValue) {
|
||||
const hasNewHangul =
|
||||
/[가-힣ㄱ-ㆎ]\s*$/u.test(raw) && raw.trimEnd() !== this._lastXtermValue.trimEnd()
|
||||
if (hasNewHangul) {
|
||||
this._koreanIme = true
|
||||
const unreplacedTail = this._committed.slice(this._unreplacedStart)
|
||||
if (/[A-Za-z]/u.test(unreplacedTail) && !/[가-힣ㄱ-ㆎ]/u.test(unreplacedTail)) {
|
||||
const convertedTail = unreplacedTail.replace(/[A-Za-z]+/gu, (word) => {
|
||||
const norm = word.replace(/[A-Z]/gu, (c) => (/^[QWERTPO]$/u.test(c) ? c : c.toLowerCase()))
|
||||
return composeHangul2Set(norm)
|
||||
})
|
||||
this._committed = this._committed.slice(0, this._unreplacedStart) + convertedTail
|
||||
} else if (
|
||||
this._unreplacedStart === 0 &&
|
||||
raw.startsWith(this.currentPrefix()) &&
|
||||
raw.length > this.currentPrefix().length
|
||||
) {
|
||||
this._committed = raw
|
||||
this._composingKeys = ''
|
||||
}
|
||||
}
|
||||
this._lastXtermValue = raw
|
||||
}
|
||||
return this.getSnapshot(hwnd, windowTitle)
|
||||
}
|
||||
|
||||
private _handleVimNormalChar(ch: string): void {
|
||||
if (this._pendingVimOperator === 'c') {
|
||||
if (ch === 'i' || ch === 'a' || ch === 'f' || ch === 'F' || ch === 't' || ch === 'T') {
|
||||
this._pendingVimOperator = `c${ch}`
|
||||
return
|
||||
}
|
||||
if (/^[wWeEbBc$0^]$/u.test(ch)) {
|
||||
this._enterVimInsertMode()
|
||||
return
|
||||
}
|
||||
this._pendingVimOperator = ''
|
||||
return
|
||||
}
|
||||
if (this._pendingVimOperator.length === 2) {
|
||||
this._enterVimInsertMode()
|
||||
return
|
||||
}
|
||||
if (ch === 'c') {
|
||||
this._pendingVimOperator = 'c'
|
||||
return
|
||||
}
|
||||
if (/^[iIaAoOsSCR]$/u.test(ch)) {
|
||||
this._enterVimInsertMode()
|
||||
return
|
||||
}
|
||||
if (ch === ':') {
|
||||
this._vimMode = 'command'
|
||||
this._pendingVimOperator = ''
|
||||
this._afterEscape = false
|
||||
this._committed = ':'
|
||||
this._composingKeys = ''
|
||||
}
|
||||
}
|
||||
|
||||
private _enterVimInsertMode(): void {
|
||||
this._vimSession = true
|
||||
this._vimMode = 'insert'
|
||||
this._pendingVimOperator = ''
|
||||
this._afterEscape = false
|
||||
this._committed = ''
|
||||
this._composingKeys = ''
|
||||
}
|
||||
|
||||
private _flushComposing(): void {
|
||||
if (this._composingKeys.length === 0) return
|
||||
this._committed += composeHangul2Set(this._composingKeys)
|
||||
this._composingKeys = ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Windows 한국어 두벌식 IME 와 동일하게, 현재 조합 중인 마지막 1글자만 _composingKeys 에 남기고
|
||||
* 이미 완성된 앞 글자들은 _committed 로 넘긴다.
|
||||
*/
|
||||
private _commitOverflowSyllables(): void {
|
||||
const full = composeHangul2Set(this._composingKeys)
|
||||
if (full.length < 2) return
|
||||
const targetPrefix = full.slice(0, -1)
|
||||
const targetLast = full.slice(-1)
|
||||
for (let i = 1; i < this._composingKeys.length; i += 1) {
|
||||
if (
|
||||
composeHangul2Set(this._composingKeys.slice(0, i)) === targetPrefix &&
|
||||
composeHangul2Set(this._composingKeys.slice(i)) === targetLast
|
||||
) {
|
||||
this._committed += targetPrefix
|
||||
this._composingKeys = this._composingKeys.slice(i)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -414,6 +414,32 @@ export interface SetEnabledParams {
|
|||
// Config (설정)
|
||||
// ============================================================
|
||||
|
||||
/** 앱 업데이트 진행 단계 (UpdateService → 설정 정보 탭·타이틀바 칩) */
|
||||
export type AppUpdatePhase =
|
||||
| 'disabled'
|
||||
| 'idle'
|
||||
| 'checking'
|
||||
| 'up-to-date'
|
||||
| 'available'
|
||||
| 'downloading'
|
||||
| 'downloaded'
|
||||
| 'error'
|
||||
|
||||
export interface AppUpdateStatus {
|
||||
phase: AppUpdatePhase
|
||||
currentVersion: string
|
||||
channel: 'latest' | 'beta' | 'alpha'
|
||||
/** 제안·다운로드·설치 대기 중인 버전 */
|
||||
version: string | null
|
||||
/** 필수(강제) 업데이트 — 연기·건너뛰기 불가 */
|
||||
isMandatory: boolean
|
||||
/** 사용자가 건너뛴 버전이다 (수동으로는 받을 수 있다) */
|
||||
skipped: boolean
|
||||
progress: { percent: number; transferred: number; total: number; bytesPerSecond: number } | null
|
||||
lastCheckedAt: number | null
|
||||
error: string | null
|
||||
}
|
||||
|
||||
export interface AppConfig {
|
||||
theme: ThemeMode
|
||||
language: string
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue