Compare commits

...

3 Commits

Author SHA1 Message Date
Nicolás Hatcher
ae661f8e93 WIP 2024-12-30 11:46:46 +01:00
francisco aloi
e5265ce3ad refactored NameManager logic for new design 2024-12-29 18:12:00 +01:00
francisco aloi
17ba7a5f84 NamedRanges changes 2024-12-28 12:32:40 +01:00
7 changed files with 507 additions and 24 deletions

View File

@@ -0,0 +1,178 @@
import type { Model } from "@ironcalc/wasm";
import {
Box,
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
IconButton,
Stack,
styled,
} from "@mui/material";
import { t } from "i18next";
import { BookOpen, Plus, X } from "lucide-react";
import { useState } from "react";
import { getFullRangeToString } from "../util";
import NamedRangeActive, { NamedRangeInactive } from "./NamedRange";
interface NameManagerDialogProperties {
onClose: () => void;
open: boolean;
model: Model;
onNamesChanged: () => void;
}
function NameManagerDialog(properties: NameManagerDialogProperties) {
const { onClose, open, model, onNamesChanged } = properties;
// If editingNameIndex is -1, then we are adding a new name
// If editingNameIndex is -2, then we are not editing any name
// If editingNameIndex is a positive number, then we are editing that index
const [editingNameIndex, setEditingNameIndex] = useState(-2);
const handleNewName = () => {
setEditingNameIndex(-1);
};
const handleDelete = () => {
onNamesChanged();
};
const formatFormula = (): string => {
const worksheets = model.getWorksheetsProperties();
const selectedView = model.getSelectedView();
return getFullRangeToString(selectedView, worksheets);
};
const worksheets = model.getWorksheetsProperties();
const definedNameList = model.getDefinedNameList();
return (
<StyledDialog open={open} onClose={onClose} maxWidth={false} scroll="paper">
<StyledDialogTitle>
{t("name_manager_dialog.title")}
<IconButton onClick={onClose}>
<X size={16} />
</IconButton>
</StyledDialogTitle>
<StyledDialogContent dividers>
<StyledRangesHeader>
<StyledBox>{t("name_manager_dialog.name")}</StyledBox>
<StyledBox>{t("name_manager_dialog.range")}</StyledBox>
<StyledBox>{t("name_manager_dialog.scope")}</StyledBox>
</StyledRangesHeader>
<NameLisWrapper>
{definedNameList.map((definedName, index) => {
if (index === editingNameIndex) {
return (
<NamedRangeActive
model={model}
worksheets={worksheets}
name={definedName.name}
scope={definedName.scope}
formula={definedName.formula}
key={definedName.name}
onSave={onNamesChanged}
onCancel={() => setEditingNameIndex(-2)}
/>
);
}
return (
<NamedRangeInactive
name={definedName.name}
scope={definedName.scope}
formula={definedName.formula}
key={definedName.name}
onEdit={() => setEditingNameIndex(index)}
onDelete={handleDelete}
/>
);
})}
</NameLisWrapper>
{editingNameIndex === -1 && (
<NamedRangeActive
model={model}
worksheets={worksheets}
name={"Name1"}
scope={0}
formula={formatFormula()}
onSave={onNamesChanged}
onCancel={() => setEditingNameIndex(-2)}
/>)
}
</StyledDialogContent>
<StyledDialogActions>
<Box display="flex" alignItems="center" gap={"8px"}>
<BookOpen color="grey" size={16} />
<span style={{ fontSize: "12px", fontFamily: "Inter" }}>
{t("name_manager_dialog.help")}
</span>
</Box>
<Button
onClick={handleNewName}
variant="contained"
disableElevation
sx={{ textTransform: "none" }}
startIcon={<Plus size={16} />}
disabled={editingNameIndex > -2}
>
{t("name_manager_dialog.new")}
</Button>
</StyledDialogActions>
</StyledDialog>
);
}
const NameLisWrapper = styled(Stack)`
overflow-y: auto;
`;
const StyledBox = styled("div")`
width: 171px;
`;
const StyledDialog = styled(Dialog)(() => ({
"& .MuiPaper-root": {
height: "380px",
minWidth: "620px",
},
}));
const StyledDialogTitle = styled(DialogTitle)`
padding: 12px 20px;
font-size: 14px;
font-weight: 600;
display: flex;
align-items: center;
justify-content: space-between;
`;
const StyledDialogContent = styled(DialogContent)`
display: flex;
flex-direction: column;
gap: 12px;
padding: 20px 12px 20px 20px;
`;
const StyledRangesHeader = styled(Box)(({ theme }) => ({
display: "flex",
paddingLeft: "6px",
fontFamily: theme.typography.fontFamily,
fontSize: "12px",
fontWeight: "700",
color: theme.palette.info.main,
}));
const StyledDialogActions = styled(DialogActions)`
padding: 12px 20px;
height: 40px;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 12px;
color: #757575;
`;
export default NameManagerDialog;

View File

@@ -0,0 +1,244 @@
import type { Model, WorksheetProperties } from "@ironcalc/wasm";
import {
Box,
Divider,
IconButton,
MenuItem,
TextField,
styled,
} from "@mui/material";
import { t } from "i18next";
import { Check, PencilLine, Trash2, X } from "lucide-react";
import { useEffect, useState } from "react";
interface NamedRangeProperties {
model: Model;
worksheets: WorksheetProperties[];
name: string;
scope?: number;
formula: string;
onSave: () => void;
onCancel: () => void;
}
interface NamedRangeInactiveProperties {
name: string;
scope?: number;
formula: string;
onDelete: () => void;
onEdit: () => void;
}
export function NamedRangeInactive(properties: NamedRangeInactiveProperties) {
const { name, scope, formula, onDelete, onEdit } = properties;
const showOptions = true;
return (
<WrappedLine>
<StyledDiv>{name}</StyledDiv>
<StyledDiv>{scope}</StyledDiv>
<StyledDiv>{formula}</StyledDiv>
<WrappedIcons>
<IconButton onClick={onEdit} disabled={!showOptions}>
<StyledPencilLine size={12} />
</IconButton>
<StyledIconButton onClick={onDelete} disabled={!showOptions}>
<Trash2 size={12} />
</StyledIconButton>
</WrappedIcons>
</WrappedLine>
);
}
function NamedRangeActive(properties: NamedRangeProperties) {
const { model, worksheets, name, scope, formula, onCancel, onSave } =
properties;
const [newName, setNewName] = useState(name || "");
const [newScope, setNewScope] = useState(scope);
const [newFormula, setNewFormula] = useState(formula);
const [readOnly, setReadOnly] = useState(true);
const [showEditDelete, setShowEditDelete] = useState(false);
// todo: add error messages for validations
const [nameError, setNameError] = useState(false);
const [formulaError, setFormulaError] = useState(false);
useEffect(() => {
// set state for new name
const definedNamesModel = model.getDefinedNameList();
if (!definedNamesModel.find((n) => n.name === newName)) {
setReadOnly(false);
setShowEditDelete(true);
}
}, [newName, model]);
const handleSaveUpdate = () => {
const definedNamesModel = model.getDefinedNameList();
if (definedNamesModel.find((n) => n.name === name)) {
// update name
try {
model.updateDefinedName(
name || "",
scope,
newName,
newScope,
newFormula
);
} catch (error) {
console.log("DefinedName update failed", error);
}
} else {
// create name
try {
model.newDefinedName(newName, newScope, newFormula);
} catch (error) {
console.log("DefinedName save failed", error);
}
setReadOnly(true);
}
setShowEditDelete(false);
};
const handleCancel = () => {
setReadOnly(true);
setShowEditDelete(false);
setNewName(name || "");
setNewScope(scope);
};
const handleEdit = () => {
setReadOnly(false);
setShowEditDelete(true);
};
const handleDelete = () => {
try {
model.deleteDefinedName(newName, newScope);
} catch (error) {
console.log("DefinedName delete failed", error);
}
};
return (
<>
<StyledBox>
<StyledTextField
id="name"
variant="outlined"
size="small"
margin="none"
fullWidth
error={nameError}
value={newName}
onChange={(event) => setNewName(event.target.value)}
onKeyDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => event.stopPropagation()}
/>
<StyledTextField
id="scope"
variant="outlined"
select
size="small"
margin="none"
fullWidth
value={newScope ?? "global"}
onChange={(event) => {
event.target.value === "global"
? setNewScope(undefined)
: setNewScope(+event.target.value);
}}
>
<MenuItem value={"global"}>
{t("name_manager_dialog.workbook")}
</MenuItem>
{worksheets.map((option, index) => (
<MenuItem key={option.name} value={index}>
{option.name}
</MenuItem>
))}
</StyledTextField>
<StyledTextField
id="formula"
variant="outlined"
size="small"
margin="none"
fullWidth
error={formulaError}
value={newFormula}
onChange={(event) => setNewFormula(event.target.value)}
onKeyDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => event.stopPropagation()}
/>
<>
<IconButton onClick={handleSaveUpdate}>
<StyledCheck size={12} />
</IconButton>
<StyledIconButton onClick={onCancel}>
<X size={12} />
</StyledIconButton>
</>
</StyledBox>
</>
);
}
const StyledBox = styled(Box)`
display: flex;
width: 577px;
`;
const StyledPencilLine = styled(PencilLine)(({ theme }) => ({
color: theme.palette.common.black,
}));
const StyledCheck = styled(Check)(({ theme }) => ({
color: theme.palette.success.main,
}));
const StyledTextField = styled(TextField)(() => ({
padding: "0px",
width: "163px",
marginRight: "8px",
"& .MuiInputBase-root": {
height: "28px",
margin: 0,
},
"& .MuiInputBase-input": {
padding: "6px",
fontSize: "12px",
},
}));
const StyledIconButton = styled(IconButton)(({ theme }) => ({
color: theme.palette.error.main,
"&.Mui-disabled": {
opacity: 0.6,
color: theme.palette.error.light,
},
}));
const WrappedLine = styled(Box)({
display: "flex",
paddingLeft: "6px",
height: "28px",
});
const StyledDiv = styled("div")(({ theme }) => ({
fontFamily: theme.typography.fontFamily,
fontSize: "12px",
fontWeight: "400",
color: theme.palette.common.black,
width: "171px",
}));
const WrappedIcons = styled(Box)({
display: "flex",
gap: "0px",
});
export default NamedRangeActive;

View File

@@ -0,0 +1 @@
export { default } from "./NameManagerDialog";

View File

@@ -1,6 +1,7 @@
import type { import type {
BorderOptions, BorderOptions,
HorizontalAlignment, HorizontalAlignment,
Model,
VerticalAlignment, VerticalAlignment,
} from "@ironcalc/wasm"; } from "@ironcalc/wasm";
import { styled } from "@mui/material/styles"; import { styled } from "@mui/material/styles";
@@ -22,6 +23,7 @@ import {
Percent, Percent,
Redo2, Redo2,
Strikethrough, Strikethrough,
Tags,
Type, Type,
Underline, Underline,
Undo2, Undo2,
@@ -34,6 +36,7 @@ import {
DecimalPlacesIncreaseIcon, DecimalPlacesIncreaseIcon,
} from "../icons"; } from "../icons";
import { theme } from "../theme"; import { theme } from "../theme";
import NameManagerDialog from "./NameManagerDialog";
import BorderPicker from "./borderPicker"; import BorderPicker from "./borderPicker";
import ColorPicker from "./colorPicker"; import ColorPicker from "./colorPicker";
import { TOOLBAR_HEIGHT } from "./constants"; import { TOOLBAR_HEIGHT } from "./constants";
@@ -72,12 +75,15 @@ type ToolbarProperties = {
numFmt: string; numFmt: string;
showGridLines: boolean; showGridLines: boolean;
onToggleShowGridLines: (show: boolean) => void; onToggleShowGridLines: (show: boolean) => void;
onNamesChanged: () => void;
model: Model;
}; };
function Toolbar(properties: ToolbarProperties) { function Toolbar(properties: ToolbarProperties) {
const [fontColorPickerOpen, setFontColorPickerOpen] = useState(false); const [fontColorPickerOpen, setFontColorPickerOpen] = useState(false);
const [fillColorPickerOpen, setFillColorPickerOpen] = useState(false); const [fillColorPickerOpen, setFillColorPickerOpen] = useState(false);
const [borderPickerOpen, setBorderPickerOpen] = useState(false); const [borderPickerOpen, setBorderPickerOpen] = useState(false);
const [nameManagerDialogOpen, setNameManagerDialogOpen] = useState(false);
const fontColorButton = useRef(null); const fontColorButton = useRef(null);
const fillColorButton = useRef(null); const fillColorButton = useRef(null);
@@ -340,6 +346,18 @@ function Toolbar(properties: ToolbarProperties) {
> >
{properties.showGridLines ? <Grid2x2Check /> : <Grid2x2X />} {properties.showGridLines ? <Grid2x2Check /> : <Grid2x2X />}
</StyledButton> </StyledButton>
<Divider />
<StyledButton
type="button"
$pressed={false}
onClick={() => {
setNameManagerDialogOpen(true);
}}
disabled={!canEdit}
title={t("toolbar.name_manager")}
>
<Tags />
</StyledButton>
<ColorPicker <ColorPicker
color={properties.fontColor} color={properties.fontColor}
@@ -375,6 +393,14 @@ function Toolbar(properties: ToolbarProperties) {
anchorEl={borderButton} anchorEl={borderButton}
open={borderPickerOpen} open={borderPickerOpen}
/> />
<NameManagerDialog
open={nameManagerDialogOpen}
onClose={() => {
setNameManagerDialogOpen(false);
}}
model={properties.model}
onNamesChanged={properties.onNamesChanged}
/>
</ToolbarContainer> </ToolbarContainer>
); );
} }

View File

@@ -1,6 +1,10 @@
import type { Area, Cell } from "./types"; import type { Area, Cell } from "./types";
import { columnNameFromNumber } from "@ironcalc/wasm"; import {
type SelectedView,
type WorksheetProperties,
columnNameFromNumber,
} from "@ironcalc/wasm";
/** /**
* Returns true if the keypress should start editing * Returns true if the keypress should start editing
@@ -57,7 +61,24 @@ export function rangeToStr(
if (rowStart === rowEnd && columnStart === columnEnd) { if (rowStart === rowEnd && columnStart === columnEnd) {
return `${sheetName}${columnNameFromNumber(columnStart)}${rowStart}`; return `${sheetName}${columnNameFromNumber(columnStart)}${rowStart}`;
} }
return `${sheetName}${columnNameFromNumber( return `${sheetName}${columnNameFromNumber(columnStart)}${rowStart}:${columnNameFromNumber(
columnStart, columnEnd,
)}${rowStart}:${columnNameFromNumber(columnEnd)}${rowEnd}`; )}${rowEnd}`;
}
export function getFullRangeToString(
selectedView: SelectedView,
worksheets: WorksheetProperties[],
): string {
// order of values is confusing compared to rangeToStr range type, needs refactoring for consistency
const [rowStart, columnStart, rowEnd, columnEnd] = selectedView.range;
const sheetNames = worksheets.map((s) => s.name);
const sheetName = `${sheetNames[selectedView.sheet]}!`;
if (rowStart === rowEnd && columnStart === columnEnd) {
return `${sheetName}${columnNameFromNumber(columnStart)}${rowStart}`;
}
return `${sheetName}${columnNameFromNumber(columnStart)}${rowStart}:${columnNameFromNumber(
columnEnd,
)}${rowEnd}`;
} }

View File

@@ -137,16 +137,17 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
// FIXME: This is so that the cursor indicates there are styles to be pasted // FIXME: This is so that the cursor indicates there are styles to be pasted
const el = rootRef.current?.getElementsByClassName("sheet-container")[0]; const el = rootRef.current?.getElementsByClassName("sheet-container")[0];
if (el) { if (el) {
(el as HTMLElement).style.cursor = (
`url('data:image/svg+xml;utf8,${encodeURIComponent( el as HTMLElement
ReactDOMServer.renderToString( ).style.cursor = `url('data:image/svg+xml;utf8,${encodeURIComponent(
<PaintRoller ReactDOMServer.renderToString(
width={24} <PaintRoller
height={24} width={24}
style={{ transform: "rotate(-8deg)" }} height={24}
/>, style={{ transform: "rotate(-8deg)" }}
), />
)}'), auto`; )
)}'), auto`;
} }
}; };
@@ -168,12 +169,12 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
row, row,
column, column,
row + height, row + height,
column + width, column + width
); );
setRedrawId((id) => id + 1); setRedrawId((id) => id + 1);
}, },
onExpandAreaSelectedKeyboard: ( onExpandAreaSelectedKeyboard: (
key: "ArrowRight" | "ArrowLeft" | "ArrowUp" | "ArrowDown", key: "ArrowRight" | "ArrowLeft" | "ArrowUp" | "ArrowDown"
): void => { ): void => {
model.onExpandSelectedRange(key); model.onExpandSelectedRange(key);
setRedrawId((id) => id + 1); setRedrawId((id) => id + 1);
@@ -327,7 +328,7 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
} = model.getSelectedView(); } = model.getSelectedView();
return getCellAddress( return getCellAddress(
{ rowStart, rowEnd, columnStart, columnEnd }, { rowStart, rowEnd, columnStart, columnEnd },
{ row, column }, { row, column }
); );
}, [model]); }, [model]);
@@ -404,7 +405,7 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
source.sheet, source.sheet,
source.area, source.area,
data, data,
source.type === "cut", source.type === "cut"
); );
setRedrawId((id) => id + 1); setRedrawId((id) => id + 1);
} else if (mimeType === "text/plain") { } else if (mimeType === "text/plain") {
@@ -435,7 +436,7 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
// '2024-10-18T14:07:37.599Z' // '2024-10-18T14:07:37.599Z'
let clipboardId = sessionStorage.getItem( let clipboardId = sessionStorage.getItem(
CLIPBOARD_ID_SESSION_STORAGE_KEY, CLIPBOARD_ID_SESSION_STORAGE_KEY
); );
if (!clipboardId) { if (!clipboardId) {
clipboardId = getNewClipboardId(); clipboardId = getNewClipboardId();
@@ -473,7 +474,7 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
// '2024-10-18T14:07:37.599Z' // '2024-10-18T14:07:37.599Z'
let clipboardId = sessionStorage.getItem( let clipboardId = sessionStorage.getItem(
CLIPBOARD_ID_SESSION_STORAGE_KEY, CLIPBOARD_ID_SESSION_STORAGE_KEY
); );
if (!clipboardId) { if (!clipboardId) {
clipboardId = getNewClipboardId(); clipboardId = getNewClipboardId();
@@ -545,7 +546,7 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
}; };
model.setAreaWithBorder( model.setAreaWithBorder(
{ sheet, row, column, width, height }, { sheet, row, column, width, height },
borderArea, borderArea
); );
setRedrawId((id) => id + 1); setRedrawId((id) => id + 1);
}} }}
@@ -569,6 +570,10 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
model.setShowGridLines(sheet, show); model.setShowGridLines(sheet, show);
setRedrawId((id) => id + 1); setRedrawId((id) => id + 1);
}} }}
model={model}
onNamesChanged={() => {
setRedrawId((id) => id + 1);
}}
/> />
<FormulaBar <FormulaBar
cellAddress={cellAddress()} cellAddress={cellAddress()}

View File

@@ -18,6 +18,7 @@
"decimal_places_increase": "Increase decimal places", "decimal_places_increase": "Increase decimal places",
"decimal_places_decrease": "Decrease decimal places", "decimal_places_decrease": "Decrease decimal places",
"show_hide_grid_lines": "Show/hide grid lines", "show_hide_grid_lines": "Show/hide grid lines",
"name_manager": "Name manager",
"vertical_align_bottom": "Align bottom", "vertical_align_bottom": "Align bottom",
"vertical_align_middle": " Align middle", "vertical_align_middle": " Align middle",
"vertical_align_top": "Align top", "vertical_align_top": "Align top",
@@ -58,14 +59,12 @@
"num_fmt": { "num_fmt": {
"title": "Custom number format", "title": "Custom number format",
"label": "Number format", "label": "Number format",
"close": "Close dialog",
"save": "Save" "save": "Save"
}, },
"sheet_rename": { "sheet_rename": {
"rename": "Save", "rename": "Save",
"label": "New name", "label": "New name",
"title": "Rename Sheet", "title": "Rename Sheet"
"close": "Close dialog"
}, },
"formula_input": { "formula_input": {
"update": "Update", "update": "Update",
@@ -75,5 +74,14 @@
"navigation": { "navigation": {
"add_sheet": "Add sheet", "add_sheet": "Add sheet",
"sheet_list": "Sheet list" "sheet_list": "Sheet list"
},
"name_manager_dialog": {
"title": "Named Ranges",
"name": "Name",
"range": "Scope",
"scope": "Range",
"help": "Learn more about Named Ranges",
"new": "Add new",
"workbook": "Workbook (Global)"
} }
} }