All files / app senseMapEdit.tsx

96.61% Statements 171/177
65.51% Branches 57/87
96.77% Functions 60/62
97.18% Lines 138/142

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                                                                              786x 786x   786x 786x   786x 1046x 1046x   1046x 1046x   410x 410x 410x   410x 410x   260x 200x 836x   836x 200x   786x   836x   266x 56x 266x 56x       788x 200x 788x 788x   1088x   894x 894x     395x 1060x       5540x 5554x 5554x 5540x       2546x 7040x 7040x 2546x                                             3x 3x 3x 3x 3x 3x   1x 1x 1x 4x 1x 1x         1x               102x 102x           136x 37x 37x 34x   37x   37x 103x 103x 102x 49x 109x   103x 103x     118x 138x       190x 190x   190x 156x 156x 156x 198x 240x 50x 42x 198x 10x 156x 50x   92x 92x 66x 130x 66x   468x   42x 18x     18x 18x       174x           50x 50x       30x       18x 18x 18x 18x   18x   54x       12x 12x 50x 50x   50x   50x           30x                     4x             156x 78x 60x 60x 264x 264x 246x 246x 246x     42x 264x 18x 18x 328x 142x 82x 82x 142x   156x                 174x   42x                     45x                     157x     224x                                                                          
import {Close, RemoveCircleOutline} from '@mui/icons-material'
import {
  Autocomplete,
  Button,
  Chip,
  Dialog,
  DialogContent,
  DialogTitle,
  FormControlLabel,
  IconButton,
  MenuItem,
  Stack,
  Switch,
  TextField,
  Tooltip,
  Typography,
} from '@mui/material'
import {
  DataGrid,
  type GridColDef,
  type GridRenderEditCellParams,
  type GridEditCellValueParams,
  QuickFilter,
  QuickFilterControl,
} from '@mui/x-data-grid'
import {type KeyboardEvent, useContext, useMemo, useState} from 'react'
import {type CoarseSenseMap, ResourceContext, SenseMapSetter, type Synset, type SenseMapSetterFun} from './resources'
import {AddSenseMapPair} from './senseMapAddPair'
import {extractMatches} from './processTerms'
import {globToRegex, special, wildcards} from './lib/utils'
 
export function SenseSelector({
  selected,
  setSelected,
  multi,
  useNLTK,
  editCell,
  params,
}: {
  selected: string[]
  setSelected: (values: string[]) => void
  multi: boolean
  useNLTK: boolean
  editCell?: (params: GridEditCellValueParams) => void
  params?: GridRenderEditCellParams
}) {
  const {synsetInfo, SenseLookup, collapsedSenses, NLTKLookup, collapsedNLTK} = useContext(ResourceContext)
  const [suggested, setSuggested] = useState<string[]>([])
 
  const [input, setInput] = useState('')
  const lookup = useNLTK ? NLTKLookup : SenseLookup
 
  return synsetInfo ? (
    <Autocomplete
      coEmponentsProps={{popper: {className: 'synset-select'}}}
      multiple={multi}
      autoSelect
      options={suggested}
      onKeyUp={(e: KeyboardEvent<HTMLDivElement>) => {
        const inputValue = ('value' in e.target ? (e.target.value as string) : '').toLowerCase()
        const suggestions: string[] = []
        Eif (inputValue) {
          let ex: RegExp | undefined
          try {
          E  ex = new RegExp(wildcards.test(inputValue) ? globToRegex(inputValue) : ';' + inputValue + '[^;]*;', 'g')
          } catch {
            ex = new RegExp(';' + inputValue.replace(special, '\\%&') + ';', 'g')
          }
          extractMatches('', ex, {all: useNLTK ? collapsedNLTK : collapsedSenses}, suggestions, 100)
        }
        Eselected.forEach(term => {
          Eif (!suggestions.includes(term)) suggestions.push(term)
        })
        setSuggested(suggestions)
      }}
      value={multi ? selected : selected[0]}
      onChange={(_, value) => {
        Eif (value) {
          const newValue = 'string' === typeof value ? [value] : [...value]
          if (editCell && params) editCell({...params, value: newValue})
          setSelected(newValue)
        }
      }}
      renderTags={(value: readonly string[], getTagProps) => {
        return value.map((option: string, index: number) => (
          <Chip label={option} {...getTagProps({index})} key={option} />
        ))
      }}
      renderEInput={params => (
        <TextField
          {...params}
          size="small"
          label="Fine Senses"
        E  value={input}
          onChange={e => {
            Eif (!selected.includes(e.target.value)) setInput(e.target.value)
          }}
        ></TextField>
      )}
      renderOption={(props, key) => {
        Eif (key in lookup) {
          delete props.key
          const {definition} = synsetInfo[(useNLTK ? NLTKLookup : SenseLookup)[key]]
          return (
            <MenuItem {...props} value={key} key={key}>
              <Tooltip title={definition} placement="right">
                <Typography sx={{width: '100%'}}>{key}</Typography>
              </Tooltip>
            </MenuItem>
          )
        }
      }}
      noOptionsText="No matches"
      filterSelectedOptions
      selectOnFocus
      clearOnBlur
      clearOnEscape
      handleHomeEndKeys
      fullWidth
    ></Autocomplete>
  ) : (
    <></>
  )
}
 
type rowSpec = {
  id: string
  fine: string
  coarse: string
  definition: string
  info: Synset
}
function EparseMapId(id: string, map: CoarseSenseMap) {
  const idParts = id.split('||')
  const fine = idParts[0]
  const newMap = {...map}
  const coarses = newMap[fine]
  if (coarses.length === 1) {
    delete newMap[fine]
  } else E{
    coarses.splice(+idParts[2], 1)
    newMap[fine] = [...coarses]
  }
  return {newMap, fine: idParts[0], coarse: idParts[1], index: idParts[2]}
}
function CoarseLabelEdit({
  params,
  labels,
  senseMap,
  senseMapStore,
  updateSenseMap,
}: {
  params: GridRenderEditCellParams
  labels: readonly string[]
  senseMap: CoarseSenseMap
  senseMapStore: boolean
  updateSenseMap: SenseMapSetterFun
}) {
  const [newValue, setNewValue] = useState('')
  return (
    <AutIocomplete
      componentsProps={{popper: {className: 'synset-select'}}}
      disableCloseOnSelect
      options={labels}
      value={params.value}
      onChange={(_, value) => {
        const {newMap, fine} = parseMapId(params.id as string, senseMap)
        Iif (fine in newMap) {
          newMap[fine].push(value)
        } else {
          newMap[fine] = [value]
        }
        updateSenseMap(newMap, {store: senseMapStore})
        params.api.setEditCellValue({...params, value})
      }}
      inputValue={newValue}
      onInputChange={(_, value) => setNewValue(value)}
      renderInput={params => <TextField {...params} size="small" label="Coarse Senses"></TextField>}
      filterSelectedOptions
      selectOnFocus
      clearOnEscape
      handleHomeEndKeys
      fullWidth
      freeSolo
    ></Autocomplete>
  )
}
export function EditSenseMap() {
  const [menuOpen, setMenuOpen] = useState(false)
  const toggleMenu = () => setMenuOpen(!menuOpen)
 
  const {senseMap, senseMapOptions, synsetInfo, SenseLookup} = useContext(ResourceContext)
  const mapOptions = useMemo(() => {
    return {
      store: senseMapOptions.store,
    }
  }, [senseMapOptions])
  const setSenseMap = useContext(SenseMapSetter)
  const coarseLabels = useMemo(() => {
    const out: Set<string> = new Set()
    Object.values(senseMap).forEach(coarses => coarses.forEach(l => l && out.add(l)))
    return Object.freeze(Array.from(out))
  }, [senseMap])
  const [useNLTK, setUseNLTK] = useState(false)
 
  const cols: GridColDef[] = useMemo(() => {
    return [
      {
        field: 'remove',
        headerName: '',
        width: 1,
        sortable: false,
        disableColumnMenu: true,
        renderCell: (params: GridRenderEditCellParams) => {
          return (
            <IconButton
              sx={{opacity: 0.4, cursor: 'not-allowed'}}
              size="small"
              aria-label="remove term"
              onClick={() => {
                const {newMap} = parseMapId(params.id as string, senseMap)
                setSenseMap(newMap, mapOptions)
              }}
            >
              <RemoveCircleOutline sx={{fontSize: '.9em'}} />
            </IconButton>
          )
        },
      },
      {
        field: 'fine',
        headerName: 'Fine',
        width: 180,
        hideable: false,
        editable: true,
        renderEditCell: (params: GridRenderEditCellParams) => {
          return (
            <SenseSelector
              selected={[params.value]}
              setSelected={selected => {
                const {newMap, coarse} = parseMapId(params.id as string, senseMap)
                const newFine = selected[0]
                if (newFine in newMap) {
                  newMap[newFine].push(coarse)
                } else {
                  newMap[newFine] = [coarse]
                }
                setSenseMap(newMap, mapOptions)
              }}
              multi={false}
              useNLTK={useNLTK}
              editCell={params.api.setEditCellValue}
              params={params}
            />
          )
        },
      },
      {
        field: 'coarse',
        headerName: 'Coarse',
        width: 125,
        hideable: false,
        editable: true,
        renderEditCell: (params: GridRenderEditCellParams) => {
          return (
            <CoarseLabelEdit
              params={params}
              labels={coarseLabels}
              senseMap={senseMap}
              senseMapStore={senseMapOptions.store}
              updateSenseMap={setSenseMap}
            />
          )
    E    },
      },
      {
        field: 'definition',
        EheaderName: 'Fine Definition',
        width: 210,
      },
    ]
  }, [senseMap, coarseLabels, senseMapOptions.store, setSenseMap, useNLTK, mapOptions])
  const rows = useMemo(() => {
    const out: rowSpec[] = []
    Eif (synsetInfo) {
      Object.keys(senseMap).forEach((fine, index) => {
        const coarses = senseMap[fine]
        const info = synsetInfo[SenseLookup[fine]]
        Eif (info) {
          coarses.forEach(coarse => {
            out.push({
              id: fine + '||' + coarse + '||' + index,
              fine: useNLTK ? info.nltk_id : fine,
              definition: info.definition,
              coarse,
              info,
            })
          })
        }
      })
    }
    return out
  }, [senseMap, synsetInfo, useNLTK, SenseLookup])
  return (
    <>
      <Button variant="outlined" aria-label="edit coarse sense map" onClick={toggleMenu}>
        Edit
      </Button>
      <Dialog open={menuOpen} onClose={toggleMenu}>
        <DialogTitle>Sense Map Editor</DialogTitle>
        <IconButton
          aria-label="close sense map editor"
          onClick={toggleMenu}
          sx={{
            position: 'absolute',
            right: 8,
            top: 12,
          }}
          className="close-button"
        >
          <Close />
        </IconButton>
        <DialogContent sx={{p: 1}}>
          <Stack sx={{height: '500px'}} spacing={1}>
            <FormControlLabel
              control={<Switch size="small" checked={useNLTK} onChange={() => setUseNLTK(!useNLTK)}></Switch>}
              label={<Typography variant="caption">NLTK-Style Labels</Typography>}
              labelPlacement="start"
            />
            <DataGrid
              className="datagrid-vertical"
              rows={rows}
              columns={cols}
              disableRowSelectionOnClick
              disableDensitySelector
              disableColumnSelector
              pageSizeOptions={[100]}
              density="compact"
              editMode="row"
              slots={{
                toolbar: () => (
                  <QuickFilter>
                    <QuickFilterControl
                      render={({ref, ...controlProps}) => (
                        <TextField
                          sx={{position: 'absolute', bottom: 6, left: 5, zIndex: 1, width: 150}}
                          {...controlProps}
                          inputRef={ref}
                          aria-label="Search"
                          placeholder="Filter..."
                          size="small"
                        />
                      )}
                    />
                  </QuickFilter>
                ),
              }}
            />
            <AddSenseMapPair coarseLabels={coarseLabels} useNLTK={useNLTK} />
          </Stack>
        </DialogContent>
      </Dialog>
    </>
  )
}