All files / app termEditor.tsx

58.82% Statements 20/34
33.33% Branches 8/24
44.44% Functions 4/9
62.5% Lines 20/32

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                                            20x 20x                               20x 20x 20x 20x 20x 20x 20x 8x                                     20x 20x 20x 20x             20x 20x 8x 4x   20x                           1x                                                                                                                                        
import {
  Box,
  Button,
  Card,
  CardContent,
  CardHeader,
  FormControlLabel,
  IconButton,
  Stack,
  Switch,
  Typography,
} from '@mui/material'
import {Close} from '@mui/icons-material'
import {type FixedTerm, type FuzzyTerm, TermLink, TermSenseEdit} from './term'
import {type KeyboardEvent, useState, useContext, createContext, useMemo} from 'react'
import {DataGrid, type GridCellParams, type GridColDef} from '@mui/x-data-grid'
import {BuildContext, BuildEditContext} from './building'
import {getProcessedTerm} from './processTerms'
import {ResourceContext} from './resources'
import type {DictEntry} from './storage'
import type {GridCell, GridRow} from './table'
 
export const EditorTerm = createContext('')
export const EditorTermSetter = createContext((term: string, fromGraph?: boolean) => {
  console.warn({
    term,
    fromGraph,
  })
})
 
export function TermEditor({
  categories,
  editor,
  width,
}: {
  categories: string[]
  editor: (value: string | number, row: GridCell) => void
  width: number
}) {
  const data = useContext(ResourceContext)
  const dict = useContext(BuildContext)
  const id = useContext(EditorTerm)
  const setTerm = useContext(EditorTermSetter)
  const editDictionary = useContext(BuildEditContext)
  const [showEmptyCategories, setShowEmptyCategories] = useState(false)
  const cols: GridColDef[] = useMemo(
    () => [
      {field: 'id', headerName: 'Name', width: 108},
      {
        field: 'from_term_editor',
        headerName: 'Weight',
        width: 65,
        editable: true,
        hideable: false,
        valueParser: (value: string | number, row: GridRow, params) => {
          const parsed = +value || ''
          if (params) {
            editor(parsed, {...row, field: params.field})
          }
          return parsed
        },
      },
    ],
    [editor],
  )
  Iif (!id || !(id in dict)) return <></>
  const processed = getProcessedTerm(id, data, dict)
  const dictEntry = dict[id]
  const weights = dictEntry.categories
  const rows: {
    id: string
    term_id: string
    from_term_editor: string | number
    dictEntry: DictEntry
    processed: FixedTerm | FuzzyTerm
  }[] = []
  categories.forEach(cat => {
    if (showEmptyCategories || cat in weights)
      rows.push({id: cat, term_id: id, from_term_editor: weights[cat] || '', dictEntry, processed})
  })
  return (
    <Box
      sx={{
        position: 'absolute',
        top: 0,
        right: '-' + width + 'px',
        height: '100%',
        width: width + 'px',
      }}
    >
      <Card sx={{height: '100%', pb: '1em'}} elevation={1}>
        <CardHeader
          sx={{p: 0.5}}
          action={
            <IconButton aria-label="Close term editor" onClick={() => setTerm('')} className="close-button">
              <Close />
            </IconButton>
          }
          title={
            <Typography sx={{whiteSpace: 'nowrap', '& .MuiButtonBase-root': {fontWeight: 'bold', fontSize: '1.1em'}}}>
              <TermLink term={processed.term} />
            </Typography>
          }
        />
        <CardContent sx={{p: 0.5, height: '100%'}}>
          <Stack direction="column" sx={{pb: 1, pt: 1, height: '100%', overflowY: 'auto'}} spacing={2}>
            <TermSenseEdit label="Sense" id={id} field="" processed={processed} />
            <Stack direction="column" spacing={1} sx={{height: '100%'}}>
              <Typography fontWeight="bold">Category Weights</Typography>
              <FormControlLabel
                control={
                  <Switch
                    size="small"
                    checked={showEmptyCategories}
                    onChange={() => setShowEmptyCategories(!showEmptyCategories)}
                  ></Switch>
                }
                label={<Typography variant="caption">Show Empty</Typography>}
                labelPlacement="start"
              />
              <DataGrid
                sx={{minHeight: '140px'}}
                className="bottom-search datagrid-vertical"
                rows={rows}
                columns={cols}
                disableRowSelectionOnClick
                disableDensitySelector
                disableColumnMenu
                pageSizeOptions={[100]}
                density="compact"
                onCellKeyDown={(params: GridCellParams, e: KeyboardEvent) => {
                  if (e.key === 'Delete' || e.key === 'Backspace') {
                    const stringValue = '' + params.value
                    const newValue = params.cellMode === 'view' ? 0 : +stringValue.substring(0, stringValue.length - 1)
                    editor(newValue, {...params.row, field: params.field})
                    if (!newValue) e.preventDefault()
                  }
                }}
              />
              <Button
                fullWidth
                variant="contained"
                onClick={() => {
                  editDictionary({
                    type: 'add',
                    term: dictEntry.term || id,
                    term_type: dictEntry.type,
                    sense: dictEntry.sense,
                    categories: {...dictEntry.categories},
                    added: dictEntry.added,
                  })
                }}
              >
                Duplicate
              </Button>
            </Stack>
          </Stack>
        </CardContent>
      </Card>
    </Box>
  )
}