Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Implemented async bindings in #let. #412

Merged
merged 3 commits into from
May 12, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
35 changes: 27 additions & 8 deletions packages/blaze/builtins.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,22 +32,41 @@ Blaze.With = function (data, contentFunc) {
return view;
};


/**
* @summary Shallow compare of two bindings.
* @param {Binding} x
* @param {Binding} y
*/
function _isEqualBinding(x, y) {
return x && y ? x.error === y.error && x.value === y.value : x === y;
}

/**
* Attaches bindings to the instantiated view.
* @param {Object} bindings A dictionary of bindings, each binding name
* corresponds to a value or a function that will be reactively re-run.
* @param {View} view The target.
* @param {Blaze.View} view The target.
*/
Blaze._attachBindingsToView = function (bindings, view) {
function setBindingValue(name, value) {
if (value instanceof Promise) {
value.then(
value => view._scopeBindings[name].set({ value }),
error => view._scopeBindings[name].set({ error }),
);
} else {
view._scopeBindings[name].set({ value });
}
}

view.onViewCreated(function () {
Object.entries(bindings).forEach(function ([name, binding]) {
view._scopeBindings[name] = new ReactiveVar();
view._scopeBindings[name] = new ReactiveVar(undefined, _isEqualBinding);
if (typeof binding === 'function') {
view.autorun(function () {
view._scopeBindings[name].set(binding());
}, view.parentView);
view.autorun(() => setBindingValue(name, binding()), view.parentView);
} else {
view._scopeBindings[name].set(binding);
setBindingValue(name, binding);
}
});
});
Expand Down Expand Up @@ -149,7 +168,7 @@ Blaze.Each = function (argFunc, contentFunc, elseFunc) {

for (var i = from; i <= to; i++) {
var view = eachView._domrange.members[i].view;
view._scopeBindings['@index'].set(i);
view._scopeBindings['@index'].set({ value: i });
}
};

Expand Down Expand Up @@ -240,7 +259,7 @@ Blaze.Each = function (argFunc, contentFunc, elseFunc) {
itemView = eachView.initialSubviews[index];
}
if (eachView.variableName) {
itemView._scopeBindings[eachView.variableName].set(newItem);
itemView._scopeBindings[eachView.variableName].set({ value: newItem });
} else {
itemView.dataVar.set(newItem);
}
Expand Down
40 changes: 33 additions & 7 deletions packages/blaze/lookup.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,31 @@
import has from 'lodash.has';

Blaze._globalHelpers = {};
/** @param {(binding: Binding) => boolean} fn */
function _createBindingsHelper(fn) {
/** @param {string[]} names */
return (...names) => {
const view = Blaze.currentView;

// There's either zero arguments (i.e., check all bindings) or an additional
// "hash" argument that we have to ignore.
names = names.length === 0
// TODO: Should we walk up the bindings here?
? Object.keys(view._scopeBindings)
: names.slice(0, -1);

// TODO: What should happen if there's no such binding?
return names.some(name => fn(_lexicalBindingLookup(view, name).get()));
};
}
radekmie marked this conversation as resolved.
Show resolved Hide resolved

Blaze._globalHelpers = {
/** @summary Check whether any of the given bindings (or all if none given) is still pending. */
'@pending': _createBindingsHelper(binding => binding === undefined),
/** @summary Check whether any of the given bindings (or all if none given) has rejected. */
'@rejected': _createBindingsHelper(binding => !!binding && 'error' in binding),
/** @summary Check whether any of the given bindings (or all if none given) has resolved. */
'@resolved': _createBindingsHelper(binding => !!binding && 'value' in binding),
};

// Documented as Template.registerHelper.
// This definition also provides back-compat for `UI.registerHelper`.
Expand Down Expand Up @@ -103,24 +128,25 @@ function _lexicalKeepGoing(currentView) {
return undefined;
}

Blaze._lexicalBindingLookup = function (view, name) {
function _lexicalBindingLookup(view, name) {
var currentView = view;
var blockHelpersStack = [];

// walk up the views stopping at a Spacebars.include or Template view that
// doesn't have an InOuterTemplateScope view as a parent
do {
// skip block helpers views
// if we found the binding on the scope, return it
if (has(currentView._scopeBindings, name)) {
var bindingReactiveVar = currentView._scopeBindings[name];
return function () {
return bindingReactiveVar.get();
};
return currentView._scopeBindings[name];
}
} while (currentView = _lexicalKeepGoing(currentView));

return null;
}

Blaze._lexicalBindingLookup = function (view, name) {
const binding = _lexicalBindingLookup(view, name);
return binding && (() => binding.get()?.value);
};

// templateInstance argument is provided to be available for possible
Expand Down
9 changes: 9 additions & 0 deletions packages/blaze/view.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,14 @@
/// general it's good for functions that create Views to set the name.
/// Views associated with templates have names of the form "Template.foo".

/**
* A binding is either `undefined` (pending), `{ error }` (rejected), or
* `{ value }` (resolved). Synchronous values are immediately resolved (i.e.,
* `{ value }` is used). The other states are reserved for asynchronous bindings
* (i.e., values wrapped with `Promise`s).
* @typedef {{ error: unknown } | { value: unknown } | undefined} Binding
*/

/**
* @class
* @summary Constructor for a View, which represents a reactive region of DOM.
Expand Down Expand Up @@ -81,6 +89,7 @@ Blaze.View = function (name, render) {
this._hasGeneratedParent = false;
// Bindings accessible to children views (via view.lookup('name')) within the
// closest template view.
/** @type {Record<string, ReactiveVar<Binding>>} */
this._scopeBindings = {};

this.renderCount = 0;
Expand Down