Skip to content

Commit

Permalink
feat: add import button to load yaml file
Browse files Browse the repository at this point in the history
  • Loading branch information
rafgugi committed Aug 5, 2023
1 parent 1154036 commit 87e2c0d
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions src/components/App.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Button, Container, Form, FormGroup, Input, Label } from 'reactstrap';
import { useMemo, useState } from 'react';
import { stringify } from 'yaml';
import { parse, stringify } from 'yaml';
import { saveAs } from 'file-saver';
import { Person } from '../family.interface';
import AppContext from './AppContext';
Expand Down Expand Up @@ -80,6 +80,28 @@ function App(props: AppProps) {
}
};

const handleLoad = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
const reader = new FileReader();
reader.onload = () => {
try {
const treeYaml = reader.result as string;
// assert valid treeYaml
const rawFamilyData = parse(treeYaml);
const trees = enrichTreeData(rawFamilyData?.trees, rawFamilyData?.people);

const unrichedTrees = unrichTreeData(trees);
setTreeYaml(stringify(unrichedTrees as {}));
setShowModalEditYaml(true);
} catch (error) {
console.error('Error loading YAML file:', error);
}
};
reader.readAsText(file);
}
};

const treeMap = useMemo(() => treesToRecord(trees), [trees]);

const upsertPerson = (person: Person) => {
Expand Down Expand Up @@ -164,8 +186,17 @@ function App(props: AppProps) {
</Button>
</FormGroup>
<FormGroup>
<Button size="sm" tag="label">
Import
<Input
type="file"
className="d-none"
accept=".yaml, .yml"
onChange={handleLoad}
/>
</Button>{' '}
<Button size="sm" onClick={handleSave}>
Save
Export
</Button>
</FormGroup>
</Form>
Expand Down

0 comments on commit 87e2c0d

Please sign in to comment.