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

Expose calculations in JS API #1988

Merged
merged 28 commits into from
Jul 19, 2023
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
f5ce090
Expose calculations in JS API
jerivas Jun 6, 2023
fbfe7f1
Merge branch 'main' into js-api-calculations
jgerigmeyer Jun 7, 2023
8c9a7d8
Use strings for CalculationOperator in JS
jerivas Jun 7, 2023
64d50c8
Merge branch 'main' into js-api-calculations
jgerigmeyer Jun 8, 2023
fb9bb04
Update date
jerivas Jun 8, 2023
3f7b3ab
Fix call stack errors in JS
jerivas Jun 9, 2023
bdb6773
Refactor static methods
jerivas Jun 9, 2023
f09910f
Return an immutable list of arguments
jerivas Jun 9, 2023
13b4f33
No need to define left/right
jerivas Jun 13, 2023
71aa9a2
Fix call stack errors on operator access
jerivas Jun 16, 2023
6277580
Export calculations classes to the browser
jerivas Jun 17, 2023
60243ca
Simplify custom function return values
jerivas Jun 22, 2023
c63fa7e
lint
jerivas Jun 22, 2023
70e567e
Parse `value` and `max` from `min`
jerivas Jul 6, 2023
b4fff6c
Merge branch 'main' into js-api-calculations
jerivas Jul 6, 2023
b4e9ade
Address changes to the clamp spec
jerivas Jul 11, 2023
024c239
Improve simplification implementation
jerivas Jul 12, 2023
399dd25
Update after spec changes
jerivas Jul 13, 2023
b292fb8
Streamline simplification
jerivas Jul 13, 2023
e300e41
Check for Value before and after simplification
jerivas Jul 13, 2023
e70e5e3
Address review
jerivas Jul 14, 2023
d30acbd
Uniform error messages
jerivas Jul 18, 2023
cd06089
Address review
jerivas Jul 18, 2023
f3d169e
Clean up
jerivas Jul 18, 2023
6b3b5b8
Test assertCalculation in other types
jerivas Jul 18, 2023
52ab266
Add basic calculation tests
jerivas Jul 19, 2023
2928f3e
Update pubspec and changelog
nex3 Jul 19, 2023
859069e
Merge branch 'main' into js-api-calculations
nex3 Jul 19, 2023
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
3 changes: 3 additions & 0 deletions lib/src/node.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ void main() {
exports.Value = valueClass;
exports.SassBoolean = booleanClass;
exports.SassArgumentList = argumentListClass;
exports.SassCalculation = calculationClass;
exports.CalculationOperation = calculationOperationClass;
exports.CalculationInterpolation = calculationInterpolationClass;
exports.SassColor = colorClass;
exports.SassFunction = functionClass;
exports.SassList = listClass;
Expand Down
28 changes: 28 additions & 0 deletions lib/src/node/compile.dart
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,32 @@ Importer _parseImporter(Object? importer) {
}
}

/// Implements the simplification algorithm for custom function return values.
/// {@link https://github.com/sass/sass/blob/main/spec/types/calculation.md#simplifying-a-calculationvalue}
dynamic simplify(dynamic value) {
jerivas marked this conversation as resolved.
Show resolved Hide resolved
if (value is SassCalculation) {
var simplifiedArgs = value.arguments.map(simplify).toList().cast<Object>();
jerivas marked this conversation as resolved.
Show resolved Hide resolved
if (value.name == 'calc') {
return simplifiedArgs[0];
}
if (value.name == 'clamp') {
return simplify(Function.apply(SassCalculation.clamp, simplifiedArgs));
jerivas marked this conversation as resolved.
Show resolved Hide resolved
jerivas marked this conversation as resolved.
Show resolved Hide resolved
}
if (value.name == 'min') {
return simplify(Function.apply(SassCalculation.min, [simplifiedArgs]));
}
if (value.name == 'max') {
return simplify(Function.apply(SassCalculation.max, [simplifiedArgs]));
}
jerivas marked this conversation as resolved.
Show resolved Hide resolved
return SassCalculation.unsimplified(value.name, simplifiedArgs);
}
if (value is CalculationOperation) {
jerivas marked this conversation as resolved.
Show resolved Hide resolved
return simplify(SassCalculation.operate(value.operator,
simplify(value.left) as Object, simplify(value.right) as Object));
}
return value;
}

/// Parses `functions` from [record] into a list of [Callable]s or
/// [AsyncCallable]s.
///
Expand All @@ -239,6 +265,7 @@ List<AsyncCallable> _parseFunctions(Object? functions, {bool asynch = false}) {
late Callable callable;
callable = Callable.fromSignature(signature, (arguments) {
var result = (callback as Function)(toJSArray(arguments));
result = simplify(result);
jerivas marked this conversation as resolved.
Show resolved Hide resolved
if (result is Value) return result;
if (isPromise(result)) {
throw 'Invalid return value for custom function '
Expand All @@ -259,6 +286,7 @@ List<AsyncCallable> _parseFunctions(Object? functions, {bool asynch = false}) {
result = await promiseToFuture<Object>(result as Promise);
}

result = simplify(result);
if (result is Value) return result;
throw 'Invalid return value for custom function '
'"${callable.name}": $result is not a sass.Value.';
Expand Down
3 changes: 3 additions & 0 deletions lib/src/node/exports.dart
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ class Exports {
// Value APIs
external set Value(JSClass function);
external set SassArgumentList(JSClass function);
external set SassCalculation(JSClass function);
external set CalculationOperation(JSClass function);
external set CalculationInterpolation(JSClass function);
external set SassBoolean(JSClass function);
external set SassColor(JSClass function);
external set SassFunction(JSClass function);
Expand Down
10 changes: 10 additions & 0 deletions lib/src/node/reflection.dart
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,16 @@ extension JSClassExtension on JSClass {
allowInteropCaptureThis((Object self, _, __, [___]) => inspect(self)));
}

/// Defines a static method with the given [name] and [body].
void defineStaticMethod(String name, Function body) {
setProperty(this, name, allowInteropNamed(name, body));
}

/// A shorthand for calling [defineStaticMethod] multiple times.
void defineStaticMethods(Map<String, Function> methods) {
methods.forEach(defineStaticMethod);
}

/// Defines a method with the given [name] and [body].
///
/// The [body] should take an initial `self` parameter, representing the
Expand Down
3 changes: 3 additions & 0 deletions lib/src/node/value.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import 'reflection.dart';

export 'value/argument_list.dart';
export 'value/boolean.dart';
export 'value/calculation.dart';
export 'value/color.dart';
export 'value/function.dart';
export 'value/list.dart';
Expand All @@ -36,6 +37,8 @@ final JSClass valueClass = () {
'get': (Value self, num index) =>
index < 1 && index >= -1 ? self : undefined,
'assertBoolean': (Value self, [String? name]) => self.assertBoolean(name),
'assertCalculation': (Value self, [String? name]) =>
self.assertCalculation(name),
'assertColor': (Value self, [String? name]) => self.assertColor(name),
'assertFunction': (Value self, [String? name]) => self.assertFunction(name),
'assertMap': (Value self, [String? name]) => self.assertMap(name),
Expand Down
134 changes: 134 additions & 0 deletions lib/src/node/value/calculation.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// Copyright 2023 Google Inc. Use of this source code is governed by an
// MIT-style license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.

import 'package:collection/collection.dart';
import 'package:node_interop/js.dart';
import 'package:sass/src/node/immutable.dart';
import 'package:sass/src/node/utils.dart';

import '../../value.dart';
import '../reflection.dart';

/// Check that [arg] is a valid argument to a calculation function.
void assertCalculationValue(Object arg, {bool checkUnquoted = true}) {
jerivas marked this conversation as resolved.
Show resolved Hide resolved
if (arg is! SassNumber &&
arg is! SassString &&
arg is! SassCalculation &&
arg is! CalculationOperation &&
arg is! CalculationInterpolation) {
jsThrow(JsError('Argument must be one of '
'SassNumber, SassString, SassCalculation, CalculationOperation, '
'CalculationInterpolation'));
}
if (checkUnquoted && arg is SassString && arg.hasQuotes) {
jsThrow(JsError('Argument must be unquoted SassString'));
}
if (arg is CalculationOperation) {
assertCalculationValue(arg.left, checkUnquoted: checkUnquoted);
assertCalculationValue(arg.right, checkUnquoted: checkUnquoted);
}
}

/// Check that [arg] is an unquoted string or interpolation
void assertUnquotedStringOrInterpolation(Object arg) {
if ((arg is! SassString && arg is! CalculationInterpolation) ||
(arg is SassString && arg.hasQuotes)) {
jsThrow(JsError(
'Argument must be an unquoted SassString or CalculationInterpolation'));
}
}

/// The JavaScript `SassCalculation` class.
final JSClass calculationClass = () {
var jsClass =
createJSClass('sass.SassCalculation', (Object self, [Object? _]) {
jsThrow(JsError("new sass.SassCalculation() isn't allowed"));
jerivas marked this conversation as resolved.
Show resolved Hide resolved
});

jsClass.defineStaticMethods({
'calc': (Object argument) {
assertCalculationValue(argument);
return SassCalculation.unsimplified('calc', [argument]);
},
'min': (Object arguments) {
var argList = jsToDartList(arguments).cast<Object>();
argList.forEach(assertCalculationValue);
return SassCalculation.unsimplified('min', argList);
},
'max': (Object arguments) {
var argList = jsToDartList(arguments).cast<Object>();
argList.forEach(assertCalculationValue);
return SassCalculation.unsimplified('max', argList);
},
'clamp': (Object min, [Object? value, Object? max]) {
if (value == null) {
assertUnquotedStringOrInterpolation(min);
} else if (max == null) {
assertUnquotedStringOrInterpolation(min);
assertUnquotedStringOrInterpolation(value);
jerivas marked this conversation as resolved.
Show resolved Hide resolved
}
[min, value, max].whereNotNull().forEach(assertCalculationValue);
return SassCalculation.unsimplified(
'clamp', [min, value, max].whereNotNull());
}
});

jsClass.defineMethods({
'assertCalculation': (SassCalculation self, [String? name]) => self,
});

jsClass.defineGetters({
// The `name` getter is included by default by `createJSClass`
jerivas marked this conversation as resolved.
Show resolved Hide resolved
'arguments': (SassCalculation self) => ImmutableList(self.arguments),
});

getJSClass(SassCalculation.unsimplified('calc', [SassNumber(1)]))
.injectSuperclass(jsClass);
jerivas marked this conversation as resolved.
Show resolved Hide resolved
return jsClass;
}();

/// The JavaScript CalculationOperation class
final JSClass calculationOperationClass = () {
var jsClass = createJSClass('sass.CalculationOperation',
(Object self, String strOperator, Object left, Object right) {
var operator = CalculationOperator.values
.firstWhereOrNull((value) => value.operator == strOperator);
if (operator == null) {
jsThrow(JsError('Invalid operator: $strOperator'));
}
assertCalculationValue(left, checkUnquoted: false);
assertCalculationValue(right, checkUnquoted: false);
return SassCalculation.operateInternal(operator, left, right,
inMinMax: false, simplify: false);
});

jsClass.defineMethods({
'equals': (CalculationOperation self, Object other) => self == other,
'hashCode': (CalculationOperation self) => self.hashCode,
});

jsClass.defineGetters({
'operator': (CalculationOperation self) => self.operator.operator,
jerivas marked this conversation as resolved.
Show resolved Hide resolved
jerivas marked this conversation as resolved.
Show resolved Hide resolved
});

getJSClass(SassCalculation.operateInternal(
CalculationOperator.plus, SassNumber(1), SassNumber(1),
inMinMax: false, simplify: false))
.injectSuperclass(jsClass);
return jsClass;
}();

/// The JavaScript CalculationInterpolation class
final JSClass calculationInterpolationClass = () {
jerivas marked this conversation as resolved.
Show resolved Hide resolved
var jsClass = createJSClass('sass.CalculationInterpolation',
(Object self, String value) => CalculationInterpolation(value));

jsClass.defineMethods({
'equals': (CalculationInterpolation self, Object other) => self == other,
'hashCode': (CalculationInterpolation self) => self.hashCode,
});

getJSClass(CalculationInterpolation('')).injectSuperclass(jsClass);
return jsClass;
}();
10 changes: 8 additions & 2 deletions lib/src/value/calculation.dart
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,13 @@ class SassCalculation extends Value {
@sealed
class CalculationOperation {
/// The operator.
final CalculationOperator operator;
CalculationOperator get operator {
// We use a getter to allow overriding the logic in the JS API
// implementation
return _operator;
}

final CalculationOperator _operator;

/// The left-hand operand.
///
Expand All @@ -343,7 +349,7 @@ class CalculationOperation {
/// [SassString], a [CalculationOperation], or a [CalculationInterpolation].
final Object right;

CalculationOperation._(this.operator, this.left, this.right);
CalculationOperation._(this._operator, this.left, this.right);

bool operator ==(Object other) =>
other is CalculationOperation &&
Expand Down
3 changes: 3 additions & 0 deletions tool/grind.dart
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ void main(List<String> args) {
'Logger',
'SassArgumentList',
'SassBoolean',
'SassCalculation',
'CalculationOperation',
'CalculationInterpolation',
'SassColor',
'SassFunction',
'SassList',
Expand Down