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 19 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: 26 additions & 2 deletions lib/src/node/compile.dart
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,28 @@ 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}
Object simplify(Object value) => switch (value) {
jerivas marked this conversation as resolved.
Show resolved Hide resolved
SassCalculation() => switch ((
// Match against...
value.name, // ...the calculation name
value.arguments.map(simplify).toList() // ...and simplified arguments
)) {
('calc', [var first, ...]) => first,
jerivas marked this conversation as resolved.
Show resolved Hide resolved
('clamp', [var min, var value, var max]) =>
SassCalculation.clamp(min, value, max),
('clamp', _) =>
throw ArgumentError('clamp() requires exactly 3 arguments.'),
('min', var args) => SassCalculation.min(args),
('max', var args) => SassCalculation.max(args),
(var name, var args) => SassCalculation.unsimplified(name, args)
jerivas marked this conversation as resolved.
Show resolved Hide resolved
},
CalculationOperation() => SassCalculation.operate(
value.operator, simplify(value.left), simplify(value.right)),
_ => value,
};

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

if (result is Value) return result;
var simplified = simplify(result as Object);
if (simplified is Value) return simplified;
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
128 changes: 128 additions & 0 deletions lib/src/node/value/calculation.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// 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) {
if (arg is! SassNumber &&
arg is! SassString &&
arg is! SassCalculation &&
arg is! CalculationOperation &&
arg is! CalculationInterpolation) {
jsThrow(JsError('Argument `$arg` must be one of '
'SassNumber, SassString, SassCalculation, CalculationOperation, '
'CalculationInterpolation'));
}
if (arg is SassString && arg.hasQuotes) {
jerivas marked this conversation as resolved.
Show resolved Hide resolved
jsThrow(JsError('Argument `$arg` must be unquoted SassString'));
}
}

/// Check that [arg] is an unquoted string or interpolation
bool isValidClampArg(Object? arg) => ((arg is CalculationInterpolation) ||
(arg is SassString && !arg.hasQuotes));

/// 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 && !isValidClampArg(min)) ||
(max == null) && !([min, value]).any(isValidClampArg)) {
jerivas marked this conversation as resolved.
Show resolved Hide resolved
jsThrow(JsError('Expected at least one SassString or '
'CalculationInterpolation in `${[
min,
value,
max
].whereNotNull()}`'));
}
[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);
assertCalculationValue(right);
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
Loading