All files / app export.tsx

92.22% Statements 166/180
87.28% Branches 103/118
95.65% Functions 44/46
92.45% Lines 98/106

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                                                        6x 24x 26x 14x 26x 14x 26x 8x     18x 76x 82x 82x 82x 42x 60x 66x 82x 82x 82x 42x               36x 60x 60x 60x 60x 60x 54x 36x 54x       84x 84x 84x 84x 56x 94x 94x 94x 94x 94x 94x 94x 94x 94x 82x   84x 54x   46x 46x         80x 34x 80x 34x 40x 40x 50x 40x 40x 40x 40x 40x     80x 34x 78x 26x 26x 78x 26x 76x       19x 69x       118x 584x 584x 584x 588x 584x 584x 584x 584x 702x 702x 584x 352x   118x 584x                                                   584x 118x                                                           584x 118x                               586x 126x                               586x 126x                                     585x 122x                           584x 118x           118x                      
import {Close} from '@mui/icons-material'
import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  FormControlLabel,
  FormLabel,
  IconButton,
  InputLabel,
  MenuItem,
  Select,
  Stack,
  Switch,
  TextField,
  Typography,
  useTheme,
} from '@mui/material'
import {type ChangeEvent, useContext, useMemo, useState} from 'react'
import {BuildContext, SettingsContext, type NumberObject} from './building'
import {Dict} from './storage'
 
type Formats = 'tabular' | 'json' | 'dic'
type DelTypes = 'csv' | 'tsv' | 'dat'
type JSONTypes = 'weighted' | 'unweighted' | 'full'
function getSepChar(type: DelTypes) {
  switch (type) {
    case 'csv':
      return ','
    case 'tsv':
      return '\t'
    default:
      return '  '
  }
}
function exportDict(dict: Dict, format: Formats, delType: DelTypes, jsonType: JSONTypes, includeSenses: boolean) {
  switch (format) {
    case 'tabular':
      const sep = getSepChar(delType)
      const categories: Set<string> = new Set()
      Object.values(dict).forEach(entry => {
        const cats = entry.categories
        if (cats) Object.keys(cats).forEach(cat => categories.add(cat))
      })
      const catArray = Array.from(categories)
      const catMap = new Map(catArray.map((cat, index) => [index, cat]))
      return (
        '"term"' +
        sep +
        '"' +
        (includeSenses ? 'term_sense"' + sep + '"' : '') +
        catArray.join('"' + sep + '"') +
        '"\n' +
        Object.keys(dict)
          .map(id => {
            const entry = dict[id]
            const cats = entry.categories
            let row = '"' + (entry.term || id) + '"'
            if (includeSenses) row += sep + entry.sense
            catMap.forEach(cat => {
              row += sep + (cat in cats ? cats[cat] : '')
            })
            return row
          })
          .join('\n')
      )
    case 'dic':
      const allCats: NumberObject = {}
      let nCats = 0
      let body = ''
      Object.keys(dict).forEach(id => {
        const entry = dict[id]
        const cats = entry.categories
        if (cats) {
          const line: (string | number)[] = [entry.term || id]
          if (includeSenses && entry.sense) line[0] += '@' + entry.sense
          Object.keys(cats).forEach(cat => {
            if (!(cat in allCats)) allCats[cat] = ++nCats
            line.push(allCats[cat])
          })
          body += '\n' + line.join('\t')
        }
      })
      return (
        '%\n' +
        Object.keys(allCats)
          .map(cat => allCats[cat] + '\t' + cat)
          .join('\n') +
        '\n%' +
        body
      )
    case 'json':
      if (jsonType === 'full') return JSON.stringify(dict, void 0, 2)
      const temp: {[index: string]: {[index: string]: number}} = {}
      Object.keys(dict).forEach(id => {
        const entry = dict[id]
        const cats = entry.categories
        if (cats) {
          let term = entry.term || id
          if (includeSenses && entry.sense) term += '@' + entry.sense
          Object.keys(cats).forEach(cat => {
            if (!(cat in temp)) temp[cat] = {}
            temp[cat][term] = cats[cat]
          })
        }
      })
      if (jsonType === 'weighted') return JSON.stringify(temp, void 0, 2)
      const unweighted: {[index: string]: string[]} = {}
      Object.keys(temp).forEach(cat => {
        unweighted[cat] = Object.keys(temp[cat])
      })
      return JSON.stringify(unweighted, void 0, 2)
    default:
      return ''
  }
}
 
const extension = /\.\w{3,4}$/i
function exportName(name: string, format: string, delType: string) {
  return name.replace(extension, '') + '.' + (format === 'tabular' ? delType : format)
}
export function ExportMenu() {
  const theme = useTheme()
  const settings = useContext(SettingsContext)
  const dict = useContext(BuildContext)
  const [menuOpen, setMenuOpen] = useState(false)
  const toggleMenu = () => setMenuOpen(!menuOpen)
  const [format, setFormat] = useState<Formats>('dic')
  const [delType, setDelType] = useState<DelTypes>('csv')
  const [name, setName] = useState(settings.selected)
  const [jsonType, setJsonType] = useState<JSONTypes>('unweighted')
  const [includeSenses, setIncludeSenses] = useState(false)
  const content = useMemo(
    () => (menuOpen ? exportDict(dict, format, delType, jsonType, includeSenses) : ''),
    [menuOpen, dict, format, delType, jsonType, includeSenses]
  )
  return (
    <>
      <Button variant="outlined" onClick={toggleMenu}>
        Export
      </Button>
      {menuOpen && (
        <Dialog open={menuOpen} onClose={toggleMenu}>
          <DialogTitle>Export Dictionary</DialogTitle>
          <IconButton
            aria-label="close export menu"
            onClick={toggleMenu}
            sx={{
              position: 'absolute',
              right: 8,
              top: 12,
            }}
            className="close-button"
          >
            <Close />
          </IconButton>
          <DialogContent sx={{p: 1}}>
            <Stack spacing={1}>
              <TextField
                size="small"
                label="Filename"
                value={name}
                onChange={(e: ChangeEvent<HTMLInputElement>) => {
                  setName(e.target.value)
                }}
              />
              <FormControl>
                <FormLabel sx={{fontSize: '.8em'}} htmlFor="export_content">
                  Export Content
                </FormLabel>
                <textarea
                  id="export_content"
                  style={{
                    backgroundColor: theme.palette.background.default,
                    color: theme.palette.text.primary,
                    whiteSpace: 'pre',
                    minWidth: '35em',
                    minHeight: '20em',
                  }}
                  value={content}
                  readOnly
                ></textarea>
              </FormControl>
            </Stack>
          </DialogContent>
          <DialogActions sx={{justifyContent: 'space-between'}}>
            <Stack direction="row" spacing={1}>
              {format !== 'json' || jsonType !== 'full' ? (
                <FormControlLabel
                  sx={{transform: 'translate(0, -10px)'}}
                  control={
                    <Switch
                      size="small"
                      checked={includeSenses}
                      onChange={() => setIncludeSenses(!includeSenses)}
                    ></Switch>
                  }
                  label={<Typography variant="caption">Senses</Typography>}
                  labelPlacement="top"
                />
              ) : (
                <></>
              )}
              <FormControl>
                <InputLabel id="export_format">Format</InputLabel>
                <Select
                  labelId="export_format"
                  label="Format"
                  size="small"
                  value={format as ''}
                  onChange={e => {
                    setFormat(e.target.value as Formats)
                  }}
                >
                  <MenuItem value="dic">DIC</MenuItem>
                  <MenuItem value="json">JSON</MenuItem>
                  <MenuItem value="tabular">Tabular</MenuItem>
                </Select>
              </FormControl>
              {format === 'tabular' ? (
                <FormControl>
                  <InputLabel id="export_separator">Type</InputLabel>
                  <Select
                    labelId="export_separator"
                    label="Type"
                    size="small"
                    value={delType as ''}
                    onChange={e => {
                      setDelType(e.target.value as DelTypes)
                    }}
                  >
                    <MenuItem value="csv">CSV</MenuItem>
                    <MenuItem value="tsv">TSV</MenuItem>
                    <MenuItem value="dat">DAT</MenuItem>
                  </Select>
                </FormControl>
              ) : (
                <></>
              )}{' '}
              {format === 'json' ? (
                <FormControl>
                  <InputLabel id="export_json_type">Type</InputLabel>
                  <Select
                    labelId="export_json_type"
                    label="Type"
                    size="small"
                    value={jsonType as ''}
                    onChange={e => {
                      setJsonType(e.target.value as JSONTypes)
                    }}
                  >
                    <MenuItem value="weighted">Weighted</MenuItem>
                    <MenuItem value="unweighted">Unweighted</MenuItem>
                    <MenuItem value="full">Full</MenuItem>
                  </Select>
                </FormControl>
              ) : (
                <></>
              )}
            </Stack>
            <Button
              variant="contained"
              onClick={() => {
                if (name && content) {
                  const a = document.createElement('a')
                  a.setAttribute('href', URL.createObjectURL(new Blob([content], {type: 'text/plain'})))
                  a.setAttribute('download', exportName(name, format, delType))
                  document.body.appendChild(a)
                  a.click()
                  document.body.removeChild(a)
                }
              }}
            >
              Download
            </Button>
          </DialogActions>
        </Dialog>
      )}
    </>
  )
}