Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add csv sample and editor #21

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
228 changes: 228 additions & 0 deletions src/components/CSVTableEditor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
import React, {
ChangeEvent,
MouseEvent as RMouseEvent,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import styles from '../css/RMLMappingEditor.module.scss';

interface CSVTableEditorProps {
content: string;
onContentChange: (newContent: string) => void;
}

function CSVTableEditor({ content, onContentChange }: CSVTableEditorProps) {
const table = useMemo(() => stringToTable(content), [content]);

const [editingCell, setEditingCell] = useState<
[number, number] | undefined
>();
const [activeInput, setActiveInput] = useState<null | HTMLInputElement>(null);

const tableRef = useRef<HTMLTableElement | null>(null);

const handleClickOutside = useCallback(
(e: MouseEvent) => {
const tableDims = tableRef.current?.getBoundingClientRect();
if (
tableDims &&
(e.clientX > tableDims.x + tableDims.width ||
e.clientY > tableDims.y + tableDims.height)
) {
setEditingCell(undefined);
}
},
[setEditingCell]
);

useEffect(() => {
if (activeInput) activeInput.focus();
}, [activeInput]);

useEffect(() => {
onContentChange(table.map((row) => row.join(',')).join('\n'));
}, [onContentChange, table]);

useEffect(() => {
document.body.addEventListener('click', handleClickOutside);
return () => {
document.body.removeEventListener('click', handleClickOutside);
};
}, [handleClickOutside]);

const handleTdClick = useCallback(
(e: RMouseEvent<HTMLTableCellElement>) => {
const [row, col] = [
parseInt(e.currentTarget.dataset.rowIndex ?? '', 10),
parseInt(e.currentTarget.dataset.colIndex ?? '', 10),
];
setEditingCell([row, col]);
},
[setEditingCell]
);

const handleCellValueChange = useCallback(
(e: ChangeEvent<HTMLInputElement>) => {
const [row, col] = [
parseInt(e.currentTarget.dataset.rowIndex ?? '', 10),
parseInt(e.currentTarget.dataset.colIndex ?? '', 10),
];
const value = e.currentTarget.value;
const newTable = [...table];
newTable[row][col] = parseRawValue(value);
onContentChange(tableToString(newTable));
},
[onContentChange, table]
);

const removeRow = useCallback(
(e: RMouseEvent<HTMLButtonElement>) => {
const rowIndex = parseInt(e.currentTarget.dataset.rowIndex || '', 10);

const newTable = [...table];
newTable.splice(rowIndex, 1);
onContentChange(tableToString(newTable));
},
[onContentChange, table]
);

const addRow = useCallback(() => {
const columnCount = table[0].length;
const newRow = [];
for (let i = 0; i < columnCount; i++) {
newRow.push('');
}
onContentChange(tableToString([...table, newRow]));
}, [onContentChange, table]);

const addColumn = useCallback(() => {
const newTable = [...table];
for (let i = 0; i < newTable.length; ++i) {
newTable[i].push('');
}
onContentChange(tableToString(newTable));
}, [onContentChange, table]);

return (
<>
<table ref={tableRef} className={styles.csvEditorTable}>
<thead>
<tr>
{table[0].map((cellContent, index) => (
<td
data-row-index={0}
data-col-index={index}
onClick={handleTdClick}
className={`${styles.cell} ${styles.tableheader}`}
key={index}
>
{editingCell &&
editingCell[0] === 0 &&
editingCell[1] === index ? (
<input
className={styles.tableItemInput}
data-row-index={0}
data-col-index={index}
value={parseCellValue(cellContent)}
onChange={handleCellValueChange}
/>
) : (
parseCellValue(cellContent)
)}
</td>
))}
</tr>
</thead>
<tbody>
{table.slice(1).map((row, rowIndex) => (
<tr key={rowIndex}>
{row.map((cellContent, colIndex) => {
const correctedRowIndex = rowIndex + 1;
return (
<td
className={styles.cell}
key={colIndex}
data-row-index={correctedRowIndex}
data-col-index={colIndex}
onClick={handleTdClick}
>
{editingCell &&
editingCell[0] === correctedRowIndex &&
editingCell[1] === colIndex ? (
<input
className={styles.tableItemInput}
ref={(ref) => setActiveInput(ref)}
data-row-index={correctedRowIndex}
data-col-index={colIndex}
value={parseCellValue(cellContent)}
onChange={handleCellValueChange}
/>
) : (
parseCellValue(cellContent)
)}
</td>
);
})}
<td className={styles.actionsCell}>
<span className={styles.tableActionsContainer}>
<button
data-row-index={rowIndex + 1}
onClick={removeRow}
className={styles.addTableItem}
>
{' '}
-{' '}
</button>
</span>
</td>
</tr>
))}
</tbody>
</table>
<div className={styles.addTableItemContainer}>
<button className={styles.addTableItem} onClick={addRow}>
{' '}
+ Row
</button>
<button className={styles.addTableItem} onClick={addColumn}>
{' '}
+ Column
</button>
</div>
</>
);
}

export default CSVTableEditor;

const stringToTable = (content: string) => {
return content.split('\n').map((row) => {
const items = [''];
row.split('').forEach((char, index) => {
if (char === ',' && row[index - 1] !== '\\') {
items.push('');
return;
}
items[items.length - 1] += char;
});
return items;
});
};

const parseCellValue = (cellContent: string) => {
return cellContent.replace(/\\,/g, ',');
};

const parseRawValue = (value: string) => {
let parsedValue = '';
if (value) {
parsedValue = value.replace(/,/g, '\\,');
}
return parsedValue ?? '';
};

const tableToString = (table: string[][]) =>
table.map((row) => row.join(',')).join('\n');
41 changes: 41 additions & 0 deletions src/components/InputFileEditor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import React, { useMemo } from 'react';
import { InputFile } from '../contexts/InputContext';
import CodeEditor from './CodeEditor';
import styles from '../css/RMLMappingEditor.module.scss';
import CSVTableEditor from './CSVTableEditor';

interface InputFileEditorProps {
inputFile: InputFile;
onFileContentsChange: (newContent: string) => void;
}

function InputFileEditor({
inputFile,
onFileContentsChange,
}: InputFileEditorProps) {
const fileType = useMemo(() => {
const fileNameParts = inputFile.name.split('.');
return fileNameParts[fileNameParts.length - 1];
}, [inputFile]);

return (
<>
{fileType === 'csv' && (
<CSVTableEditor
content={inputFile.contents}
onContentChange={onFileContentsChange}
/>
)}
{fileType !== 'csv' && (
<CodeEditor
mode={fileType}
code={inputFile.contents ?? ''}
onChange={onFileContentsChange}
classes={styles.mappingEditorCodeView}
/>
)}
</>
);
}

export default InputFileEditor;
47 changes: 22 additions & 25 deletions src/components/InputPanel.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { useCallback, useContext, useEffect, useMemo, useState } from "react";
import InputContext from "../contexts/InputContext";
import styles from "../css/RMLMappingEditor.module.scss";
import CodeEditor from "./CodeEditor";
import { ReactComponent as PlusIcon } from "../images/plus.svg";
import { ReactComponent as DownArrow } from "../images/down-arrow.svg";
import { INPUT_TYPES } from '../util/Constants';
import { useCallback, useContext, useEffect, useMemo, useState } from 'react';
import InputContext from '../contexts/InputContext';
import styles from '../css/RMLMappingEditor.module.scss';
// import CodeEditor from './CodeEditor';
import { ReactComponent as PlusIcon } from '../images/plus.svg';
import { ReactComponent as DownArrow } from '../images/down-arrow.svg';
import InputFileEditor from './InputFileEditor';

const views = {
inputs: "Input Files",
Expand All @@ -31,17 +31,17 @@ function InputPanel({ addNewInput }: InputPanelProps) {
inputFiles.length
);

const inputType = useMemo(() => {
if (selectedInputFile) {
if (selectedInputFile.name.endsWith(".json")) {
return INPUT_TYPES.json;
} else if (selectedInputFile.name.endsWith(".xml")) {
return INPUT_TYPES.xml;
} else if (selectedInputFile.name.endsWith(".csv")) {
return INPUT_TYPES.csv;
}
}
}, [selectedInputFile]);
// const inputType = useMemo(() => {
// if (selectedInputFile) {
// if (selectedInputFile.name.endsWith('.json')) {
// return INPUT_TYPES.json;
// } else if (selectedInputFile.name.endsWith('.xml')) {
// return INPUT_TYPES.xml;
// } else if (selectedInputFile.name.endsWith('.csv')) {
// return INPUT_TYPES.csv;
// }
// }
// }, [selectedInputFile]);

const changeToInputView = useCallback(() => setView(views.inputs), [setView]);

Expand Down Expand Up @@ -81,7 +81,7 @@ function InputPanel({ addNewInput }: InputPanelProps) {
<button
onClick={changeToInputView}
className={`${styles.headerButton} ${
view === views.inputs ? styles.headerButtonSelected : ""
view === views.inputs ? styles.headerButtonSelected : ''
}`}
>
Input Files
Expand Down Expand Up @@ -124,12 +124,9 @@ function InputPanel({ addNewInput }: InputPanelProps) {
{selectedInputFile.name}
</div>
</div>
<CodeEditor
key={selectedInputFileIndex}
mode={inputType}
code={selectedInputFile.contents ?? ""}
onChange={updateSelectedInputFile}
classes={styles.mappingEditorCodeView}
<InputFileEditor
inputFile={selectedInputFile}
onFileContentsChange={updateSelectedInputFile}
/>
</>
)}
Expand Down
25 changes: 20 additions & 5 deletions src/contexts/InputContext.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,33 @@
import { createContext } from 'react';
import { ValueOf } from '../util/TypeUtil';

export const INPUT_TYPES = {
json: 'json',
csv: 'csv',
xml: 'xml',
};

export const DEFAULT_INPUT_FILE_BY_TYPE = {
[INPUT_TYPES.json]: '[\n {\n \n }\n]',
[INPUT_TYPES.csv]: 'Name, age\nAlice, 34\nBob, 68',
[INPUT_TYPES.xml]: '',
};

export type InputType = ValueOf<typeof INPUT_TYPES>;

export interface InputFile {
name: string;
contents: string;
}

interface InputContextType {
inputFiles: InputFile[],
setInputFiles: (inputFiles: InputFile[]) => void,
inputFiles: InputFile[];
setInputFiles: React.Dispatch<React.SetStateAction<InputFile[]>>;
}

const InputContext = createContext<InputContextType>({
const InputContext = createContext<InputContextType>({
inputFiles: [],
setInputFiles: (inputFiles: InputFile[]) => {},
setInputFiles: (inputFiles) => inputFiles,
});

export default InputContext;
export default InputContext;
Loading