All files / app building.tsx

76.78% Statements 172/224
66.01% Branches 101/153
63.15% Functions 24/38
78.15% Lines 161/206

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435                                                                                                                                        20x             20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 44x         20x     20x     3x 3x 9x 9x       3x   20x   62x 62x 94x 94x 94x 94x     94x         96x       20x     288x 288x 288x   4x 2x 2x   2x 2x         288x 288x 40x   288x 288x 288x   43x     22x               288x 64x 31x 31x   33x 33x 33x   33x 33x       33x 33x   33x 33x 33x 33x   288x   288x 50x 1x 1x 1x 1x 1x 1x 1x   49x 49x 49x     49x 49x 9x       50x   288x 104x 104x 96x 96x 174x 174x   96x 8x 8x       104x   288x 288x 102x 2x 2x 2x   100x 62x 62x 62x 62x   38x 38x                                   38x                                 38x                     38x 6x 6x 6x 14x 14x 7x 7x 7x 7x           6x     32x       32x 32x 18x 18x 9x 9x   9x           32x 32x 32x             32x                           32x   14x 14x 14x 2x   12x 12x 10x 8x             12x 2x               12x 8x 4x 2x     14x 12x           18x       32x   38x 38x   288x 288x 42x 42x   288x 1x   1x 1x 1x 1x 1x 1x 1x     288x                                                        
import {type ReactNode, createContext, useEffect, useReducer, useState, useContext, useCallback} from 'react'
import {type Settings, loadSettings} from './settingsMenu'
import {moveInHistory} from './history'
import {
  type Dict,
  type DictEntry,
  loadDictionary,
  loadHistory,
  removeStorage,
  setStorage,
  deleteDictionary,
  loadSenseMap,
  saveDictionary,
} from './storage'
import {SenseMapSetter} from './resources'
 
export type NumberObject = {[index: string]: number}
export type TermTypes = 'fixed' | 'glob' | 'regex'
export type DictionaryStorageAction =
  | {type: 'set'; name: string}
  | {type: 'add' | 'save'; name: string; dict: Dict; password?: string}
  | {type: 'delete'; name: string}
export type DictionaryActions =
  | {type: 'change_dict'; name: string; dict: Dict}
  | {type: 'history_bulk'; dict: Dict}
  | {type: 'remove'; term_id: string}
  | {type: 'remove_category'; name: string}
  | {type: 'rename_category'; name: string; newName: string}
  | {type: 'add_category'; name: string; weights: NumberObject}
  | {type: 'reweight_category'; name: string; weights: NumberObject}
  | {
      type: 'add' | 'update'
      term_id?: string
      term: string | RegExp
      term_type: TermTypes
      categories?: NumberObject
      sense?: string
      added?: number
    }
  | {
      type: 'replace'
      term_id: string
      term: string | RegExp
      term_type: TermTypes
      originalTerm: string | RegExp
      categories?: NumberObject
      sense?: string
      added?: number
    }
type CategoryActions = {type: 'collect'; dictionary: Dict; reset?: boolean} | {type: 'add' | 'remove'; cat: string}
type TermCategoryEdit = {category: string; from: number; to: number}
type HistoryTermEdit =
  | {field: 'type' | 'sense'; new: string; original: string}
  | {field: 'categories'; edits: TermCategoryEdit[]}
export type HistoryEntry = {time?: number; name: string} & (
  | {type: 'add_category' | 'remove_category'; weights: NumberObject}
  | {type: 'reweight_category'; weights: NumberObject; originalWeights: NumberObject}
  | {type: 'rename_category'; originalName: string}
  | {type: 'add_term' | 'remove_term'; value: DictEntry}
  | {type: 'replace_term'; value: DictEntry; originalName: string; originalValue: DictEntry}
  | {type: 'edit_term'; value: HistoryTermEdit}
)
export type HistoryContainer = {edits: HistoryEntry[]; position: number}
export type EditHistoryAction =
  | {type: 'add' | 'remove'; entry: HistoryEntry}
  | {type: 'replace'; history: HistoryContainer}
  | {type: 'clear'}
export type DictionaryEditor = (action: DictionaryActions) => void
export const SettingsContext = createContext<Settings>({
  selected: 'default',
  dictionary_names: ['default'],
  info_drawer_height: 30,
  term_editor_width: 200,
  use_db: true,
})
export const SettingEditor = createContext<(settings: Settings) => void>(() => {})
export const ManageDictionaries = createContext<(action: DictionaryStorageAction) => void>(() => {})
export const BuildContext = createContext<Dict>({})
export const BuildEditContext = createContext<(action: DictionaryActions) => void>(() => {})
export const AllCategories = createContext<string[]>([])
export const CategoryEditContext = createContext<(action: CategoryActions) => void>(() => {})
export const EditHistory = createContext<HistoryContainer>({edits: [], position: -1})
export const EditHistoryEditor = createContext<(action: EditHistoryAction) => void>(() => {})
export const HistoryStepper = createContext<(direction: number) => void>(() => {})
export const PasswordEnterer = createContext('')
const defaultRequester = () => async (password: string) => {
  console.warn(password.length)
  return
}
export type PasswordRequestCallback = () => (password: string) => Promise<void>
export const PasswordPrompter = createContext<(name: string, resolve?: PasswordRequestCallback) => void>(() => {
  return
})
export const PasswordResolve = createContext<(password: string) => Promise<void>>(async () => {})
 
export function termsByCategory(categories: string[], dict: Dict) {
  const terms: {[index: string]: DictEntry} = {}
  Object.keys(dict).forEach(id => {
    const entry = dict[id]
    categories.forEach(category => {
      if (category in entry.categories) terms[id] = entry
    })
  })
  return terms
}
let termMap: {[index: string]: Set<string>} = {}
function mapTerms(dict: Dict) {
  termMap = {}
  Object.keys(dict).forEach(id => {
    const entry = dict[id]
    const term = entry.term || id
    entry.term = term
    Iif (term in termMap) {
      if (id !== term) termMap[term].add(id)
    } else {
      termMap[term] = new Set()
    }
  })
}
export function isInDict(term: string) {
  return term in termMap
}
 
function byLowerAlphabet(a: string, b: string) {
  return a.toLowerCase() > b.toLowerCase() ? 1 : -1
}
export function Building({children}: {children: ReactNode}) {
  const [promptPassword, setPromptPassword] = useState('')
  const [requester, setRequester] = useState(defaultRequester)
  const passwordRequester = useCallback(
    (name: string, resolve?: PasswordRequestCallback) => {
      if (resolve) {
        setPromptPassword(name)
        setRequester(resolve)
      } else {
        setPromptPassword('')
        setRequester(defaultRequester)
      }
    },
    [setPromptPassword, setRequester],
  )
  const senseMapSetter = useContext(SenseMapSetter)
  useEffect(() => {
    loadSenseMap(senseMapSetter, passwordRequester)
  }, [senseMapSetter, passwordRequester])
  const [settings, updateSettings] = useState(loadSettings())
  const use_db = !!settings.use_db
  const changeDictionary = useCallback(
    (name: string) => {
      loadDictionary(
        name,
        dict => {
          dictionaryAction({type: 'change_dict', name, dict})
        },
        passwordRequester,
        !!settings.use_db,
      )
    },
    [settings.use_db, passwordRequester],
  )
  const editHistory = (action: EditHistoryAction) => {
    if (action.type === 'replace') {
      setHistory(action.history)
      return
    }
    const newHistory = action.type === 'clear' ? [] : [...history.edits]
    let position = action.type === 'clear' ? -1 : history.position
    Iif (action.type === 'remove') {
      newHistory.pop()
    } else Eif (action.type !== 'clear') {
      Iif (position > -1) {
        newHistory.splice(0, position + 1)
        position = -1
      }
      Eif (!action.entry.time) action.entry.time = Date.now()
      newHistory.splice(0, 0, action.entry)
    }
    Iif (newHistory.length > 1000) newHistory.splice(1000, newHistory.length - 999)
    Eif (!settings.disable_storage)
      setStorage(settings.selected, 'dict_history_', {edits: newHistory, position: position}, use_db)
    setHistory({edits: newHistory, position: position})
  }
  const [history, setHistory] = useState<{edits: HistoryEntry[]; position: number}>({edits: [], position: -1})
 
  const manageDictionaries = (action: DictionaryStorageAction) => {
    if (action.type === 'delete') {
      Eif (action.name !== 'default') settings.dictionary_names.splice(settings.dictionary_names.indexOf(action.name), 1)
      settings.selected = 'default'
      updateSettings({...settings})
      removeStorage(action.name, 'dict_')
      removeStorage(action.name, 'dict_history_')
      deleteDictionary(action.name)
      changeDictionary('default')
    } else {
      if (!settings.dictionary_names.includes(action.name)) settings.dictionary_names.push(action.name)
      settings.selected = action.name
      Iif (action.type === 'set') {
        changeDictionary(action.name)
      } else {
        Eif (!settings.disable_storage) saveDictionary(action.name, action.dict, use_db, action.password)
        if (action.type === 'add') {
          dictionaryAction({type: 'change_dict', name: action.name, dict: action.dict})
        }
      }
    }
    localStorage.setItem('dictionary_builder_settings', JSON.stringify(settings))
  }
  const editCategories = (state: string[], action: CategoryActions) => {
    let newState = state
    if (action.type === 'collect') {
      const cats: Set<string> = new Set(action.reset ? [] : state)
      Object.keys(action.dictionary).forEach(id => {
        const entry = action.dictionary[id]
        Eif (entry && entry.categories) Object.keys(entry.categories).forEach(cat => cats.add(cat))
      })
      newState = Array.from(cats).sort(byLowerAlphabet)
    } else if (action.type === 'add') {
      Eif (!state.includes(action.cat)) newState = [...state, action.cat].sort(byLowerAlphabet)
    } else E{
      newState = state.filter(cat => cat !== action.cat)
    }
    return state.length !== newState.length || state.join('') !== newState.join('') ? newState : state
  }
  const [categories, categoryAction] = useReducer(editCategories, [])
  const editDictionary = (state: Dict, action: DictionaryActions) => {
    if (action.type === 'history_bulk') {
      categoryAction({type: 'collect', dictionary: action.dict, reset: true})
      manageDictionaries({type: 'save', name: settings.selected, dict: action.dict})
      return action.dict
    }
    if (action.type === 'change_dict') {
      mapTerms(action.dict)
      loadHistory(action.name, history => editHistory({type: 'replace', history}), passwordRequester, use_db)
      categoryAction({type: 'collect', dictionary: action.dict, reset: true})
      return action.dict
    }
    const newState = {...state} as Dict
    Iif (action.type === 'rename_category') {
      let nTerms = 0
      Object.keys(newState).forEach(id => {
        const entry = newState[id]
        if (action.name in entry.categories) {
          nTerms++
          if (entry.categories[action.name]) entry.categories[action.newName] = entry.categories[action.name]
          delete entry.categories[action.name]
        }
      })
      categoryAction({type: 'remove', cat: action.name})
      categoryAction({type: 'add', cat: action.newName})
      if (nTerms) {
        editHistory({
          type: 'add',
          entry: {type: 'rename_category', name: action.newName, originalName: action.name},
        })
      }
    } else Iif (action.type === 'remove_category') {
      const edited_terms: NumberObject = {}
      let nTerms = 0
      Object.keys(newState).forEach(id => {
        const entry = newState[id]
        if (action.name in entry.categories) {
          nTerms++
          if (entry.categories[action.name]) edited_terms[id] = entry.categories[action.name]
          delete entry.categories[action.name]
        }
      })
      if (nTerms) {
        editHistory({
          type: 'add',
          entry: {type: 'remove_category', name: action.name, weights: edited_terms},
        })
      }
    } else Iif (action.type === 'add_category') {
      Object.keys(action.weights).forEach(id => {
        if (id in newState) {
          if (action.weights[id]) {
            newState[id].categories[action.name] = action.weights[id]
          } else {
            delete newState[id].categories[action.name]
          }
        }
      })
      editHistory({type: 'add', entry: action})
    } else if (action.type === 'reweight_category') {
      const originalWeights: NumberObject = {}
      let nChanged = 0
      Object.keys(newState).forEach(id => {
        const entry = newState[id]
        if (entry.categories[action.name] !== action.weights[id]) {
          nChanged++
          originalWeights[id] = entry.categories[action.name] || 0
          if (action.weights[id]) {
            entry.categories[action.name] = action.weights[id]
          } else E{
            delete entry.categories[action.name]
          }
        }
      })
      if (nChanged) editHistory({type: 'add', entry: {...action, originalWeights}})
    } else {
      // single term actions
      Iif (action.type === 'remove') {
        delete newState[action.term_id]
        editHistory({type: 'add', entry: {type: 'remove_term', name: action.term_id, value: state[action.term_id]}})
      } else {
        const term = 'string' === typeof action.term ? action.term : action.term.source
        if (!action.term_id) {
          if (action.type === 'add') {
            if (term in termMap) {
              action.term_id = term + (termMap[term].size + 1)
              termMap[term].add(action.term_id)
            } else {
              termMap[term] = new Set()
            }
          } else E{
            action.term_id = term
          }
        }
        const id = action.term_id || term
        const existing = newState[id] || {}
        newState[id] = {
          term,
          added: existing.added || action.added || Date.now(),
          type: action.term_type || existing.type || 'fixed',
          categories: {...(action.categories || existing.categories || {})},
          sense: 'sense' in action ? action.sense || '' : existing.sense || '',
        }
        Iif (action.type === 'replace') {
          const original = 'string' === typeof action.originalTerm ? action.originalTerm : action.originalTerm.source
          delete newState[original]
          editHistory({
            type: 'add',
            entry: {
              type: 'replace_term',
              name: id,
              value: newState[id],
              originalName: original,
              originalValue: state[original],
            },
          })
        } else {
          if (id in state) {
            let change: HistoryTermEdit | undefined
            const original = state[id]
            const newEntry = newState[id]
            if (original.sense && newEntry.sense !== original.sense) {
              change = {field: 'sense', new: newEntry.sense, original: original.sense}
            } else {
              const catChanges: TermCategoryEdit[] = []
              Object.keys(newEntry.categories).forEach(cat => {
                if (newEntry.categories[cat] !== original.categories[cat]) {
                  catChanges.push({
                    category: cat,
                    from: original.categories[cat] || 0,
                    to: newEntry.categories[cat] || 0,
                  })
                }
              })
              Object.keys(original.categories).forEach(cat => {
                Iif (!(cat in newEntry.categories)) {
                  catChanges.push({
                    category: cat,
                    from: original.categories[cat],
                    to: 0,
                  })
                }
              })
              if (catChanges.length) {
                change = {field: 'categories', edits: catChanges}
              } else if (newEntry.sense !== original.sense) {
                change = {field: 'sense', new: newEntry.sense, original: original.sense}
              }
            }
            if (change) {
              editHistory({
                type: 'add',
                entry: {type: 'edit_term', name: id, value: change},
              })
            }
          } else {
            editHistory({type: 'add', entry: {type: 'add_term', name: id, value: newState[id]}})
          }
        }
      }
      categoryAction({type: 'collect', dictionary: newState})
    }
    manageDictionaries({type: 'save', name: settings.selected, dict: newState})
    return newState
  }
  const [dictionary, dictionaryAction] = useReducer(editDictionary, {})
  useEffect(() => {
    Iif (!settings.dictionary_names.includes(settings.selected)) settings.selected = 'default'
    changeDictionary(settings.selected)
  }, [changeDictionary, settings])
  const historyStep = (direction: number) => {
    const to = Math.min(Math.max(-1, history.position + direction), history.edits.length - 1)
 
    Eif (to !== history.position) {
      const newDict = {...dictionary}
      const newHistory = {...history}
      moveInHistory(to, newHistory, newDict)
      editHistory({type: 'replace', history: newHistory})
      Eif (!settings.disable_storage) setStorage(settings.selected, 'dict_history_', newHistory, use_db)
      dictionaryAction({type: 'history_bulk', dict: newDict})
    }
  }
  return (
    <SettingsContext.Provider value={settings}>
      <SettingEditor.Provider value={updateSettings}>
        <PasswordEnterer.Provider value={promptPassword}>
          <PasswordPrompter.Provider value={passwordRequester}>
            <PasswordResolve.Provider value={requester}>
              <EditHistory.Provider value={history}>
                <EditHistoryEditor.Provider value={editHistory}>
                  <ManageDictionaries.Provider value={manageDictionaries}>
                    <BuildContext.Provider value={dictionary}>
                      <AllCategories.Provider value={categories}>
                        <BuildEditContext.Provider value={dictionaryAction}>
                          <CategoryEditContext.Provider value={categoryAction}>
                            <HistoryStepper.Provider value={historyStep}>{children}</HistoryStepper.Provider>
                          </CategoryEditContext.Provider>
                        </BuildEditContext.Provider>
                      </AllCategories.Provider>
                    </BuildContext.Provider>
                  </ManageDictionaries.Provider>
                </EditHistoryEditor.Provider>
              </EditHistory.Provider>
            </PasswordResolve.Provider>
          </PasswordPrompter.Provider>
        </PasswordEnterer.Provider>
      </SettingEditor.Provider>
    </SettingsContext.Provider>
  )
}