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

Formulas: add the SWITCH function #5407

Open
wants to merge 2 commits into
base: master
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
73 changes: 69 additions & 4 deletions src/components/composer/composer/composer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { functionRegistry } from "../../../functions/index";
import { clip, setColorAlpha } from "../../../helpers/index";

import { EnrichedToken } from "../../../formulas/composer_tokenizer";
import { argTargeting } from "../../../functions/arguments";
import { Store, useLocalStore, useStore } from "../../../store_engine";
import { DOMFocusableElementStore } from "../../../stores/DOM_focus_store";
import {
Expand Down Expand Up @@ -137,7 +138,7 @@ interface FunctionDescriptionState {
showDescription: boolean;
functionName: string;
functionDescription: FunctionDescription;
argToFocus: number;
argsToFocus: number[];
}

export class Composer extends Component<CellComposerProps, SpreadsheetChildEnv> {
Expand Down Expand Up @@ -179,7 +180,7 @@ export class Composer extends Component<CellComposerProps, SpreadsheetChildEnv>
showDescription: false,
functionName: "",
functionDescription: {} as FunctionDescription,
argToFocus: 0,
argsToFocus: [],
});
assistant = useState({
forcedClosed: false,
Expand Down Expand Up @@ -712,7 +713,8 @@ export class Composer extends Component<CellComposerProps, SpreadsheetChildEnv>
* the autocomplete engine otherwise we initialize the formula assistant.
*/
private processTokenAtCursor(): void {
let content = this.props.composerStore.currentContent;
const composerStore = this.props.composerStore;
let content = composerStore.currentContent;
if (this.autoCompleteState.provider) {
this.autoCompleteState.hide();
}
Expand All @@ -735,15 +737,78 @@ export class Composer extends Component<CellComposerProps, SpreadsheetChildEnv>
// initialize Formula Assistant
const description = functions[parentFunction];
const argPosition = tokenContext.argPosition;
const nbrArgSupplied = tokenContext.args.length;

this.functionDescriptionState.functionName = parentFunction;
this.functionDescriptionState.functionDescription = description;
this.functionDescriptionState.argToFocus = description.getArgToFocus(argPosition + 1) - 1;

const isParenthesisClosed = !!this.props.composerStore.currentTokens.find(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use some :)

(t) => t.type === "RIGHT_PAREN" && t.parenthesesCode === token.parenthesesCode
);

this.functionDescriptionState.argsToFocus = this.getArgsToFocus(
isParenthesisClosed,
description,
nbrArgSupplied,
argPosition
);

this.functionDescriptionState.showDescription = true;
}
}
}

/**
* Compute the argument to focus depending on the current value position.
*
* This function is useful to indicate in the functionDescriptionState which argument should be focused.
* Normally, 'argTargeting' is used to compute the argument to focus, but in the composer,
* we don't yet know how many arguments the user will supply.
*
* This function will compute all the possible arguments to focus for different numbers of arguments supplied.
*/
private getArgsToFocus(
isParenthesisClosed: boolean,
description: FunctionDescription,
nbrArgSupplied: number,
argPosition: number
): number[] {
// When the parenthesis is closed, we consider the user is done with the function,
// so we know exactly the number of arguments supplied.

if (isParenthesisClosed) {
const focusedArg = argTargeting(
description,
Math.max(Math.min(description.maxArgPossible, nbrArgSupplied), description.minArgRequired)
)(argPosition);
return focusedArg !== undefined ? [focusedArg] : [];
}

// Otherwise, the user is still typing the formula, so we don't know yet how many arguments the user will supply.
// Consequently, we need to compute not only the argument to focus for the current number of arguments supplied
// but also for all the possible numbers of arguments supplied.

const minArgsNumberPossibility = Math.max(nbrArgSupplied, description.minArgRequired);
const maxArgsNumberPossibility = description.nbrArgRepeating
? description.minArgRequired +
Math.ceil(
(minArgsNumberPossibility - description.minArgRequired) / description.nbrArgRepeating
) *
description.nbrArgRepeating +
description.nbrArgOptional
: description.maxArgPossible;

const argsToFocus: number[] = [];
for (let i = minArgsNumberPossibility; i <= maxArgsNumberPossibility; i++) {
const focusedArg = argTargeting(description, i)(argPosition);
if (focusedArg !== undefined) {
argsToFocus.push(focusedArg);
}
}

return [...new Set(argsToFocus)];
}

private autoComplete(value: string) {
if (!value || this.assistant.forcedClosed) {
return;
Expand Down
2 changes: 1 addition & 1 deletion src/components/composer/composer/composer.xml
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
t-if="functionDescriptionState.showDescription"
functionName="functionDescriptionState.functionName"
functionDescription="functionDescriptionState.functionDescription"
argToFocus="functionDescriptionState.argToFocus"
argsToFocus="functionDescriptionState.argsToFocus"
/>
<div
t-if="functionDescriptionState.showDescription and autoCompleteState.provider"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,15 @@ css/* scss */ `
interface Props {
functionName: string;
functionDescription: FunctionDescription;
argToFocus: number;
argsToFocus: number[];
}

export class FunctionDescriptionProvider extends Component<Props, SpreadsheetChildEnv> {
static template = "o-spreadsheet-FunctionDescriptionProvider";
static props = {
functionName: String,
functionDescription: Object,
argToFocus: Number,
argsToFocus: Array<Number>,
};

getContext(): Props {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
(
<t t-foreach="context.functionDescription.args" t-as="arg" t-key="arg.name">
<span t-if="arg_index > '0'" t-esc="formulaArgSeparator"/>
<span t-att-class="{ 'o-formula-assistant-focus': context.argToFocus === arg_index }">
<span
t-att-class="{ 'o-formula-assistant-focus': context.argsToFocus.includes(arg_index) }">
<span>
<span t-if="arg.optional || arg.repeating || arg.default">[</span>
<span t-esc="arg.name"/>
Expand Down Expand Up @@ -37,8 +38,8 @@
<div
class="o-formula-assistant-arg p-3 pt-0 display-flex flex-column"
t-att-class="{
'o-formula-assistant-gray': context.argToFocus >= '0',
'o-formula-assistant-focus': context.argToFocus === arg_index,
'o-formula-assistant-gray': context.argsToFocus.length > 0,
'o-formula-assistant-focus': context.argsToFocus.includes(arg_index),
}">
<div>
<span t-esc="arg.name"/>
Expand Down
39 changes: 23 additions & 16 deletions src/formulas/compiler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Token } from ".";
import { argTargeting } from "../functions/arguments";
import { functionRegistry } from "../functions/index";
import { parseNumber, removeStringQuotes, unquote } from "../helpers";
import { _t } from "../translation";
Expand Down Expand Up @@ -125,9 +126,10 @@ function compileTokensOrThrow(tokens: Token[]): CompiledFormula {

const compiledArgs: FunctionCode[] = [];

const argToFocus = argTargeting(functionDefinition, args.length);

for (let i = 0; i < args.length; i++) {
const argToFocus = functionDefinition.getArgToFocus(i + 1) - 1;
const argDefinition = functionDefinition.args[argToFocus];
const argDefinition = functionDefinition.args[argToFocus(i) ?? -1];
const currentArg = args[i];
const argTypes = argDefinition.type || [];

Expand Down Expand Up @@ -316,43 +318,48 @@ function formulaArguments(tokens: Token[]) {
* Check if arguments are supplied in the correct quantities
*/
function assertEnoughArgs(ast: ASTFuncall) {
const nbrArg = ast.args.length;
const nbrArgSupplied = ast.args.length;
const functionName = ast.value.toUpperCase();
const functionDefinition = functions[functionName];
const nbrArgRepeating = functionDefinition.nbrArgRepeating;
const minArgRequired = functionDefinition.minArgRequired;

if (nbrArg < functionDefinition.minArgRequired) {
if (nbrArgSupplied < minArgRequired) {
throw new BadExpressionError(
_t(
"Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.",
functionName,
functionDefinition.minArgRequired.toString(),
nbrArg.toString()
minArgRequired.toString(),
nbrArgSupplied.toString()
)
);
}

if (nbrArg > functionDefinition.maxArgPossible) {
if (nbrArgSupplied > functionDefinition.maxArgPossible) {
throw new BadExpressionError(
_t(
"Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.",
functionName,
functionDefinition.maxArgPossible.toString(),
nbrArg.toString()
nbrArgSupplied.toString()
)
);
}

const repeatableArgs = functionDefinition.nbrArgRepeating;
if (repeatableArgs > 1) {
const unrepeatableArgs = functionDefinition.args.length - repeatableArgs;
const repeatingArgs = nbrArg - unrepeatableArgs;
if (repeatingArgs % repeatableArgs !== 0) {
if (nbrArgRepeating > 1) {
const nbrValueRepeating =
nbrArgRepeating * Math.floor((nbrArgSupplied - minArgRequired) / nbrArgRepeating);
const nbrValueRemaining =
nbrArgSupplied - minArgRequired - nbrValueRepeating - functionDefinition.nbrArgOptional;

if (nbrValueRemaining > 0) {
throw new BadExpressionError(
_t(
"Invalid number of arguments for the %s function. Expected all arguments after position %s to be supplied by groups of %s arguments",
"Invalid number of arguments for the %s function. Repeatable arguments are expected to be supplied by groups of %s argument(s) with maximum %s optional argument(s), but got %s argument(s) too many.",
functionName,
unrepeatableArgs.toString(),
repeatableArgs.toString()
nbrArgRepeating.toString(),
functionDefinition.nbrArgOptional.toString(),
nbrValueRemaining.toString()
)
);
}
Expand Down
6 changes: 3 additions & 3 deletions src/formulas/composer_tokenizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,11 +163,11 @@ function mapParentFunction(tokens: EnrichedToken[]): EnrichedToken[] {
pushTokenToFunctionContext(token);
break;
case "ARG_SEPARATOR":
pushTokenToFunctionContext(token);
if (stack.length) {
// increment position on current function
stack[stack.length - 1].argPosition++;
}
pushTokenToFunctionContext(token);
break;
default:
pushTokenToFunctionContext(token);
Expand Down Expand Up @@ -208,8 +208,8 @@ function addArgsAST(tokens: EnrichedToken[]): EnrichedToken[] {
}
for (const argTokens of argsTokens) {
let tokens = argTokens;
if (tokens.at(-1)?.type === "ARG_SEPARATOR") {
tokens = tokens.slice(0, -1);
if (tokens.at(0)?.type === "ARG_SEPARATOR") {
tokens = tokens.slice(1);
}
try {
args.push(parseTokens(tokens));
Expand Down
Loading