Skip to content

Commit

Permalink
Merge pull request mito-ds#1289 from mito-ds/set-default-cell-editor
Browse files Browse the repository at this point in the history
mitosheet: set default_apply_formula_to_column
  • Loading branch information
Nate Rush authored Mar 19, 2024
2 parents f59dc37 + f0dda17 commit 7a260a7
Show file tree
Hide file tree
Showing 15 changed files with 66 additions and 16 deletions.
8 changes: 6 additions & 2 deletions mitosheet/mitosheet/mito_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from mitosheet.steps_manager import StepsManager
from mitosheet.telemetry.telemetry_utils import (log, log_event_processed,
telemetry_turned_on)
from mitosheet.types import CodeOptions, ColumnDefinintion, ColumnDefinitions, ConditionalFormat, MitoTheme, ParamMetadata
from mitosheet.types import CodeOptions, ColumnDefinintion, ColumnDefinitions, ConditionalFormat, DefaultEditingMode, MitoTheme, ParamMetadata
from mitosheet.updates.replay_analysis import REPLAY_ANALYSIS_UPDATE
from mitosheet.user.create import try_create_user_json_file
from mitosheet.user.db import USER_JSON_PATH, get_user_field
Expand Down Expand Up @@ -58,6 +58,7 @@ def __init__(
user_defined_editors: Optional[List[Callable]]=None,
code_options: Optional[CodeOptions]=None,
column_definitions: Optional[List[ColumnDefinitions]]=None,
default_editing_mode: Optional[DefaultEditingMode]=None,
theme: Optional[MitoTheme]=None,
):
"""
Expand Down Expand Up @@ -94,6 +95,8 @@ def __init__(
if not os.path.exists(import_folder):
raise ValueError(f"Import folder {import_folder} does not exist. Please change the file path or create the folder.")

default_apply_formula_to_column = False if default_editing_mode == 'cell' else True

# Set up the state container to hold private widget state
self.steps_manager = StepsManager(
args,
Expand All @@ -106,7 +109,8 @@ def __init__(
user_defined_editors=user_defined_editors,
code_options=code_options,
column_definitions=column_definitions,
theme=theme
theme=theme,
default_apply_formula_to_column=default_apply_formula_to_column
)

# And the api
Expand Down
8 changes: 7 additions & 1 deletion mitosheet/mitosheet/steps_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ def __init__(
user_defined_editors: Optional[List[Callable]]=None,
code_options: Optional[CodeOptions]=None,
column_definitions: Optional[List[ColumnDefinitions]]=None,
default_apply_formula_to_column: Optional[bool]=None,
theme: Optional[MitoTheme]=None,
):
"""
Expand Down Expand Up @@ -255,6 +256,9 @@ def __init__(

if not is_running_test() and not is_pro() and column_definitions is not None:
raise ValueError("column definitions are only supported in the enterprise version of Mito. See Mito plans https://www.trymito.io/plans")

if not is_running_test() and not is_pro() and default_apply_formula_to_column is not None:
raise ValueError(f'Setting default_editing_mode is only supported in the enterprise version of Mito. See Mito plans https://www.trymito.io/plans')

# The version of the public interface used by this analysis
self.public_interface_version = 3
Expand Down Expand Up @@ -348,6 +352,7 @@ def __init__(
self.code_options: CodeOptions = get_default_code_options(self.analysis_name) if code_options is None else code_options

self.theme = theme
self.default_apply_formula_to_column = default_apply_formula_to_column if default_apply_formula_to_column is not None else True

@property
def curr_step(self) -> Step:
Expand Down Expand Up @@ -421,7 +426,8 @@ def analysis_data_json(self):
'path': self.import_folder,
'pathParts': get_path_parts(self.import_folder)
} if self.import_folder is not None else None,
"theme": self.theme
"theme": self.theme,
"defaultApplyFormulaToColumn": self.default_apply_formula_to_column
},
cls=NpEncoder
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5, 6, 7, 8, 9],
'B': [1, 2, 3, 4, 5, 6, 7, 8, 9]
})
}, index=['a', 'b', 'c', 'd', 'e', 'b', 'g', 'h', 'i'])
new_dfs, code = spreadsheet(
df,
height='1200px',
default_editing_mode='cell',
column_definitions=[
[
{
Expand Down
7 changes: 6 additions & 1 deletion mitosheet/mitosheet/streamlit/v1/spreadsheet.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@

from mitosheet.mito_backend import MitoBackend
from mitosheet.selection_utils import get_selected_element
from mitosheet.types import CodeOptions, ColumnDefinitions, ConditionalFormat, ParamMetadata, ParamType
from mitosheet.types import CodeOptions, ColumnDefinitions, ConditionalFormat, DefaultEditingMode, ParamMetadata, ParamType
from mitosheet.user.utils import is_pro
from mitosheet.utils import get_new_id

CURRENT_MITO_ANALYSIS_VERSION = 1
Expand Down Expand Up @@ -270,6 +271,7 @@ def _get_mito_backend(
_sheet_functions: Optional[List[Callable]]=None,
_code_options: Optional[CodeOptions]=None,
_column_definitions: Optional[List[ColumnDefinitions]]=None,
_default_editing_mode: Optional[DefaultEditingMode]=None,
import_folder: Optional[str]=None,
df_names: Optional[List[str]]=None,
session_id: Optional[str]=None,
Expand All @@ -282,6 +284,7 @@ def _get_mito_backend(
user_defined_importers=_importers, user_defined_functions=_sheet_functions, user_defined_editors=_editors,
code_options=_code_options,
column_definitions = _column_definitions,
default_editing_mode=_default_editing_mode,
)

# Make a send function that stores the responses in a list
Expand Down Expand Up @@ -323,6 +326,7 @@ def spreadsheet( # type: ignore
import_folder: Optional[str]=None,
code_options: Optional[CodeOptions]=None,
column_definitions: Optional[List[ColumnDefinitions]]=None,
default_editing_mode: Optional[DefaultEditingMode]=None,
return_type: str='default',
height: Optional[str]=None,
key=None
Expand Down Expand Up @@ -370,6 +374,7 @@ def spreadsheet( # type: ignore
_editors=editors,
_code_options=code_options,
_column_definitions=column_definitions,
_default_editing_mode=default_editing_mode,
import_folder=import_folder,
session_id=session_id,
df_names=df_names,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import glob
import os
import openpyxl
import pandas as pd
import pytest
from mitosheet.tests.test_utils import check_dataframes_equal, create_mito_wrapper, get_dataframe_generation_code
Expand Down
10 changes: 10 additions & 0 deletions mitosheet/mitosheet/tests/streamlit/test_streamlit.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,4 +164,14 @@ def test_spreadsheet_with_column_definitions_only_one_color():
code_options={'as_function': True, 'call_function': False, 'function_name': 'test', 'function_params': {}},
return_type='function'
)
assert callable(f)

@requires_streamlit
def test_spreadsheet_with_default_apply_formula_to_column():
f = spreadsheet(
df1,
default_editing_mode='cell',
code_options={'as_function': True, 'call_function': False, 'function_name': 'test', 'function_params': {}},
return_type='function'
)
assert callable(f)
10 changes: 10 additions & 0 deletions mitosheet/mitosheet/tests/test_mito_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,4 +191,14 @@ def test_create_backend_with_code_options_works():
mito_backend = MitoBackend(code_options=code_options)
assert mito_backend.steps_manager.code_options == code_options

def test_create_backend_default_apply_formula_to_column():
mito_backend = MitoBackend(default_editing_mode='cell')
assert mito_backend.steps_manager.default_apply_formula_to_column == False

mito_backend = MitoBackend(default_editing_mode='column')
assert mito_backend.steps_manager.default_apply_formula_to_column == True

mito_backend = MitoBackend()
assert mito_backend.steps_manager.default_apply_formula_to_column == True


4 changes: 3 additions & 1 deletion mitosheet/mitosheet/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,9 +383,10 @@ class ColumnDefinintion(TypedDict):
columns: List[ColumnHeader]
conditional_formats: List[ColumnDefinitionConditionalFormats]

# TODO: This is a confusing name. Think of a better one.
ColumnDefinitions = List[ColumnDefinintion]

DefaultEditingMode = Literal['cell', 'column']

UserDefinedFunctionParamType = Literal['any', 'str', 'int', 'float', 'bool', 'DataFrame', 'ColumnHeader']

class MitoTheme(TypedDict):
Expand Down Expand Up @@ -455,6 +456,7 @@ class ExecuteThroughTranspileNewDataframeParams(TypedDict):
ColumnDefinitionConditionalFormats = Any # type: ignore
ColumnDefinintion = Any # type: ignore
ColumnDefinitions = Any # type: ignore
DefaultEditingMode = Any # type: ignore

ParamName = str # type: ignore
ParamType = str # type: ignore
Expand Down
4 changes: 2 additions & 2 deletions mitosheet/src/mito/components/endo/EndoGrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,7 @@ function EndoGrid(props: {
return;
}

const {startingColumnFormula, arrowKeysScrollInFormula, editingMode} = getStartingFormula(sheetData, props.editorState, rowIndex, columnIndex);
const {startingColumnFormula, arrowKeysScrollInFormula, editingMode} = getStartingFormula(sheetData, props.editorState, rowIndex, columnIndex, props.analysisData.defaultApplyFormulaToColumn);

setEditorState({
rowIndex: rowIndex,
Expand Down Expand Up @@ -621,7 +621,7 @@ function EndoGrid(props: {
setGridState((gridState) => {
const lastSelection = gridState.selections[gridState.selections.length - 1]

const {startingColumnFormula, arrowKeysScrollInFormula, editingMode} = getStartingFormula(sheetData, undefined, lastSelection.startingRowIndex, lastSelection.startingColumnIndex, e);
const {startingColumnFormula, arrowKeysScrollInFormula, editingMode} = getStartingFormula(sheetData, undefined, lastSelection.startingRowIndex, lastSelection.startingColumnIndex, props.analysisData.defaultApplyFormulaToColumn, e);

setEditorState({
rowIndex: lastSelection.startingRowIndex,
Expand Down
4 changes: 2 additions & 2 deletions mitosheet/src/mito/components/endo/FormulaBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import Col from '../layout/Col';
import Row from '../layout/Row';
import { TaskpaneType } from '../taskpanes/taskpanes';
import CellEditor from './celleditor/CellEditor';
import { getFullFormula } from './celleditor/cellEditorUtils';
import { getDefaultEditingMode, getFullFormula } from './celleditor/cellEditorUtils';
import { calculateCurrentSheetView } from './sheetViewUtils';
import { getCellDataFromCellIndexes } from './utils';

Expand Down Expand Up @@ -100,7 +100,7 @@ const FormulaBar = (props: {
formula: formulaBarValue,
arrowKeysScrollInFormula: true,
editorLocation: 'formula bar',
editingMode: columnFormulaLocation || 'entire_column',
editingMode: columnFormulaLocation || getDefaultEditingMode(props.analysisData.defaultApplyFormulaToColumn),
sheetIndex: props.sheetIndex,
})
// If we're opening the formula cell editor while the cell editor is currently open,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ const CellEditor = (props: {
return prevEditingState;
}

const startingColumnFormula = getStartingFormula(sheetData, prevEditingState, props.editorState.rowIndex, props.editorState.columnIndex).startingColumnFormula
const startingColumnFormula = getStartingFormula(sheetData, prevEditingState, props.editorState.rowIndex, props.editorState.columnIndex, props.analysisData.defaultApplyFormulaToColumn).startingColumnFormula
return {
...prevEditingState,
formula: startingColumnFormula
Expand Down
15 changes: 12 additions & 3 deletions mitosheet/src/mito/components/endo/celleditor/cellEditorUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ export const getCellEditorInputCurrentSelection = (containerDiv: HTMLDivElement
}
}

/**
* Gets the editing mode that the cell editor should start in, based on the default.
*/
export const getDefaultEditingMode = (defaultApplyFormulaToColumn: boolean): 'entire_column' | 'specific_index_labels' => {
return defaultApplyFormulaToColumn ? 'entire_column' : 'specific_index_labels';
}


/**
* Keys that don't get appended to the cell editing mode when you
Expand Down Expand Up @@ -114,8 +121,10 @@ export const getStartingFormula = (
editorState: EditorState | undefined,
rowIndex: number,
columnIndex: number,
defaultApplyFormulaToColumn: boolean,
e?: KeyboardEvent
): {startingColumnFormula: string, arrowKeysScrollInFormula: boolean, editingMode: 'entire_column' | 'specific_index_labels'} => {

// Preserve the formula if setting the same column's formula and you're just switching cell editors.
// ie: from the floating cell editor to the formula bar.
if (editorState !== undefined && editorState.columnIndex === columnIndex) {
Expand All @@ -132,7 +141,7 @@ export const getStartingFormula = (
return {
startingColumnFormula: '',
arrowKeysScrollInFormula: false,
editingMode: 'entire_column'
editingMode: getDefaultEditingMode(defaultApplyFormulaToColumn)
};
}

Expand Down Expand Up @@ -174,14 +183,14 @@ export const getStartingFormula = (
return {
startingColumnFormula: '',
arrowKeysScrollInFormula: false,
editingMode: 'entire_column'
editingMode: getDefaultEditingMode(defaultApplyFormulaToColumn)
}
}

return {
startingColumnFormula: originalValue,
arrowKeysScrollInFormula: true,
editingMode: columnFormulaLocation || 'entire_column'
editingMode: columnFormulaLocation || getDefaultEditingMode(defaultApplyFormulaToColumn)
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export const FormulaTabContents = (
} else {
const rowIndex = props.gridState.selections[0].startingRowIndex;
const columnIndex = props.gridState.selections[0].startingColumnIndex;
const {startingColumnFormula, arrowKeysScrollInFormula, editingMode} = getStartingFormula(props.sheetData, props.editorState, rowIndex, columnIndex);
const {startingColumnFormula, arrowKeysScrollInFormula, editingMode} = getStartingFormula(props.sheetData, props.editorState, rowIndex, columnIndex, false);
const newFormula = `=${functionObject.function}(${startingColumnFormula.startsWith('=') ? startingColumnFormula.substring(1) : startingColumnFormula}`;

props.setEditorState({
Expand Down
1 change: 1 addition & 0 deletions mitosheet/src/mito/types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -802,6 +802,7 @@ export interface AnalysisData {
pathParts: string[],
} | null;
theme: MitoTheme | null;
defaultApplyFormulaToColumn: boolean;
}

export interface MitoConfig {
Expand Down
2 changes: 1 addition & 1 deletion mitosheet/src/mito/utils/actions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ export const getActions = (
const startingRowIndex = gridState.selections[gridState.selections.length - 1].startingRowIndex;
const startingColumnIndex = gridState.selections[gridState.selections.length - 1].startingColumnIndex;
const {columnID, cellValue, columnDtype } = getCellDataFromCellIndexes(sheetData, startingRowIndex, startingColumnIndex);
const {startingColumnFormula, arrowKeysScrollInFormula} = getStartingFormula(sheetData, undefined, startingRowIndex, startingColumnIndex);
const {startingColumnFormula, arrowKeysScrollInFormula} = getStartingFormula(sheetData, undefined, startingRowIndex, startingColumnIndex, analysisData.defaultApplyFormulaToColumn);
const startingColumnID = columnID;
const lastStepSummary = analysisData.stepSummaryList[analysisData.stepSummaryList.length - 1];

Expand Down

0 comments on commit 7a260a7

Please sign in to comment.