Giter VIP home page Giter VIP logo

ember-truth-helpers's Introduction

Ember Truth Helpers CI

HTMLBars template helpers for additional truth logic in if and unless statements.

Compatibility

  • Ember.js v3.28 or above
  • Embroider or ember-auto-import >= 2 (this is v2 addon)

Installation

ember install ember-truth-helpers

Usage

Helper JavaScript HTMLBars Variable argument count allowed
eq if (a === b) {{if (eq a b)}} No
not-eq if (a !== b) {{if (not-eq a b)}} No
not if (!a) {{if (not a)}} Yes
and if (a && b) {{if (and a b)}} Yes
or if (a || b) {{if (or a b)}} ย  ย  Yes
xor if (a !== b) {{if (xor a b)}} No
gt if (a > b) {{if (gt a b)}} No
gte if (a >= b) {{if (gte a b)}} No
lt if (a < b) {{if (lt a b)}} No
lte if (a <= b) {{if (lte a b)}} No
is-array if (Ember.isArray(a)) {{if (is-array a)}} Yes
is-empty if (Ember.isEmpty(a)) {{if (is-empty a)}} No
is-equal if (Ember.isEqual(a, b)) {{if (is-equal a b)}} No

API

is-equal

is-equal uses Ember.isEqual helper to evaluate equality of two values. eq should be sufficient for most applications. is-equal is necessary when trying to compare a complex object to a primitive value.

Other Helpers

Usage with Glint

ember-truth-helpers is a glint enabled addon. Add this to your types/global.d.ts file:

import '@glint/environment-ember-loose';

import type EmberTruthRegistry from 'ember-truth-helpers/template-registry';

declare module '@glint/environment-ember-loose/registry' {
  export default interface Registry extends EmberTruthRegistry, /* other addon registries */ {
    // local entries
  }
}

For the entire guide, please refer to Using Addons section on the glint handbook.

Types are made available through package.json exports field. In order for TS to recognize this (beginning from TS 4.7), you must set moduleResolution to node16 or nodenext.

Usage in Single File Components

For usage in gts or gjs files, all helpers are exported from the index:

import { or } from 'ember-truth-helpers';

<template>
  {{#if (or @admin @user)}}
    Admin Controls are going here
  {{/if}}
</template>

Contributing

See the Contributing guide for details.

License

This project is licensed under the MIT License.

ember-truth-helpers's People

Contributors

adjohnson916 avatar dependabot[bot] avatar dhaulagiri avatar ef4 avatar elwayman02 avatar ember-tomster avatar gabrielgrant avatar glavin001 avatar gossi avatar jayphelps avatar jevanlingen avatar jmurphyau avatar keeo avatar lifeart avatar loganrosen avatar mixonic avatar nlfurniss avatar nullvoxpopuli avatar rondale-sc avatar rwjblue avatar rwolffgang avatar sergeastapov avatar snewcomer avatar taras avatar techn1x avatar toranb avatar turbo87 avatar wagenet avatar xiphiasuvella avatar xuefeng-zhu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ember-truth-helpers's Issues

Ember 2.x

Were you planning to upgrade to the newest ember version soon?

Add is-none helper

...that proxies the Ember function of the same name (it's useful to distinguish between null/undefined values and empty strings)

I'm using this in a project; hopefully find time to pull it out, add the needed tests and docs, and submit a PR soon

May have a bug defining the helpers

I think you may have a bug. I wasn't able to fix. I'm getting this error when trying to use ember-truth-helpers as an addon of ember-cli:

"uncaught type error: cannot read property '_registerhelper' of undefined"

Specifically here in the 24 line in the file register-helper.js:

function registerHelper(name, helperFunction) {
if (Ember['default'].HTMLBars._registerHelper) {
if (Ember['default'].HTMLBars.helpers) {
...

I'm using the latest version of ember-cli 0.1.15

`or` doesn't work the same way as `||` in JavaScript

(or (array) 1)

Will return 1.

[] || 1

Will return [].

That's because of this line. I believe this is confusing to users. It was for me at least. Of course, doing it the other way will be a horrible breaking change so a major version is the least you could do if you decide to change it.

Helper "not" has wrong value when passing PromiseProxy

This bug actually related to all truthConvert-helpers.
Initially, I reproduced this bug with an ember-data model (async belongsTo relationship), but it can be reproduced on any Ember.ProxyMixin based object.

What's going on here:

  1. I have an ember-data model in loading state (isPending == true)
  2. {{not model}} returns true (offtopic: isn't that weird already? model != null, so I expect false as result of {{not model}}). OK, it returns true because truthConvert checks isTruthy and model.isTruthy === false until it is fulfilled.
  3. After some time, the model is loaded. model.isTruthy becomes true, model.isSettled === true.
  4. {{not model}} is not recomputed, it still returns true (expected false).

Ember: 3.4.8
Ember Data: 3.4.4
ember-truth-helpers: 2.1.0

Demo: https://ember-twiddle.com/1dd51cbbc7e12f94e255913ef279baec?openFiles=controllers.application.js%2C

Does not work: {{ some-component disabled=(not someModel.isDirty) }}

So I'm trying to use ember-truth-helpers with this addon: ember-cli-async-button.

It is a simple component that has a disabled property bound to an attribute.

This works as expected:

Component disabled: {{ async-button disabled=true }}
Component disabled: {{ async-button disabled=(not false) }}

Component enabled: {{ async-button disabled=false }}
Component enabled: {{ async-button disabled=(not true) }}

Bot then I've got an Ember Data model. This also works fine:

Displays "false" or "true": {{ model.isDirty }}

Component enabled or disabled depending on `isDirty` state:
{{ async-button disabled=model.isDirty }}

Now, i'm putting model.isDirty into the not subexpression, and suddenly it's not working!

Displays "false" or "true": {{ model.isDirty }}

Component always enabled, regardless of `isDirty` state:
{{ async-button disabled=(not model.isDirty) }}

dafuq

Latest ember depreciations with helpers

FYI latest version of ember yet again screwed with things.

https://github.com/emberjs/ember.js/releases/tag/v1.13.6

DEPRECATION: Using Ember.HTMLBars._registerHelper is deprecated. Helpers (even dashless ones) are automatically resolved. [deprecation id: ember-htmlbars.register-helper]

DEPRECATION: UsingEmber.HTMLBars.makeBoundHelperis deprecated. Please refactor to usingEmber.HelperorEmber.Helper.helper. [deprecation id: ember-htmlbars.make-bound-helper]

Array.includes helper?

It would be super useful to have a {{includes array item}} helper that does Array.prototype.includes. Would this helper be appropriate for this addon?

How to compare mulitple condition

{{if ( or (not-eq a b) (not-eq a b) ) }}
This is the format I'm presuming that would work if I wanted to check two things within an or statement, but this breaks my build and left me with a blank page. Is there another format I can try?

Project maintenance

Hi! I'm reaching out from simplabs as we're interested in taking over maintenance of this addon.

Compatibility with Ember 2.15

I just bumped ember-cli to 2.15.1 and am getting some test failures that I think are related to this addon. I'm using ember-truth-helpers@^1.3.0. I'm seeing failures like these:

"SYNTAX ERROR: #if requires a single argument"

The only thing that looks at all out of the ordinary is a line that resembles this:

{{#if (and foo (eq bar baz))}}

Can you verify if this is supported with the new version of glimmer that ships with 2.15?

modulo helper

Have you considered a modulo helper? Useful for even/odd on array indexes. I'd imagine something like {{if (mod i 2 0)}} representing if (i % 2 === 0), and/or shorthand {{if (mod i)}} to return truthy 1 or true (for odd) and falsy 0 or false (for even). I could submit a PR if you might accept it.

Use truth helpers in unit tests

I run ember test to unit test my Ember CLI project and it seems truth helpers cannot be found. After search around, I added helper:eq to my unit test like this

moduleForComponent('x-component', {
  // specify the other units that are required for this test
  // needs: ['component:foo', 'helper:bar']
  needs: ['helper:eq']
});

Now I get

beforeEach failed on it renders: Attempting to register an unknown factory: `helper:eq`

Is there a recommended way to register truth helpers for testing?

Lazy evaluation

So if I use the and helper like so;

{{if (and firstExpression secondExpression)}}

It will evaluate both firstExpression and secondExpression even if firstExpression is false.

Is there a way to get it to evaluate just the firstExpression and stop there when it fails? The reason I ask is because 99% of the time my secondExpression is not necessary, and is quite taxing, so I only want to evaluate it when necessary.

I am trying to do this with ember-truth-helpers because both of my expressions are actually handlebar helpers :p

1.3.0

Hi

I see that the last commit is Released 1.3.0 but there's no tag. Can this be created please?

Thanks

is-array helper is returning false when array only has one object inside it.

The is-array truth helper in templates is returning false when the array only has a length of one. However running the same array through isArray from @ember/array in the controller returns true.

image
image
First true is from the controller function, second is the array itself logged out and the final is the truth helper is-array logged from the hbs template

Add bool helper

In a form I have an attribute that relies on the existence of a property:

readonly=(if card true)

would it make sense to have a short-cut in this lib such as readonly=(bool card)?

`and` helper should short-circuit

It seems like the and helper should short circuit, so using methods or computed props as the arguments does not cause the rightmost expressions to be evaluated if the left evaluates to false. This behavior would be more consistent with how JS works.

This came up in our application due to evaluation of computed properties on one of our models causing unnecessary network fetches. We hoped to prevent these with short-circuiting logic but were surprised to find that even when the first expression evaluated to false the second was still called.

We reproduced this behavior in the twiddle below.

Twiddle: https://ember-twiddle.com/cc9681fd51fe0c2505ac62781dbd41a0?openFiles=templates.application.hbs%2C

not-eq has unknown reexport

Hi,
I noticed the following due to a warning from embroider.

app/not-eq tries to reexport notEq from addon/not-equal.
addon/not-equal only exports notEqualHelper.

This means that there's an export happening that doesn't exist.
Would you be ok with renaming notEqualHelper into notEq? This should fix the warning.

We could also add an alias export notEqualHelper to still be backwards compatible.

If that's ok, I could open a PR.

Calling model attributes are undefined params in eq

So in a simple eq helper statement like this: {{#if (eq requistion.status "Draft")}} Where requisition is my model, I ran a console.log for params[0] in the equal.js file in helpers folder and I'm getting undefined. I have other places in my view which reference {{requisition.status}} and it is not undefined and returns the expected value in those cases. I should mention that using a string value for both params like this causes the behavior to be expected: {{#if (eq "Draft" "Draft")}} Does ember truth helpers not allow referencing of models/properties?

Special note about how `not` handles empty arrays

Ran into the unexpected asymmetry between how (not arr) (in templates) and !arr (in JS) behave. I don't really have a problem with it (probably makes sense in a lot of cases), but I think there should be a special note somewhere (in the readme?)

Either that, or make not exactly the same as ! and add a new helper like empty or something.

Add NPM Owner?

@jmurphyau - A while back you gave me access to help maintain this addon, but it looks like we forgot to add me to NPM. Can you run the following:

npm owner add rwjblue ember-truth-helpers

Thanks!

npm package published with engine: "ember-cli-app-version"

Extremely unimportant detail, but it's not in package.json but it's on npm:

$ npm show ember-truth-helpers engines
{ node: '>= 0.10.0', 'ember-cli-app-version': '1.0.0' }

It also makes yarn ๐Ÿ˜ž :

$ yarn
yarn install v0.16.1
[1/4] ๐Ÿ”  Resolving packages...
[2/4] ๐Ÿšš  Fetching packages...
warning [email protected]: The engine "ember-cli-app-version" appears to be invalid.

Ember version?

is there a specific Ember version that this needs in order to work?

Getting started...

Hey!

I'm fairly new to ember and I'm struggling to get this working.

I have ran ember install ember-truth-helpers which worked but when using any of the helpers I get Handlebars error: Could not find property 'gt' on object in the console?

A new `is-empty` helper should be added

This should use the Ember.isEmpty function, and consider changing truthConvert to no longer be falsy for empty arrays. That's not how JS works, and truth helpers aren't block helpers. Consider encourage users to use (is-empty value) or (not (is-empty value)) to check arrays. This change would require a semver major bump.

Does not handle aysnc conditions

We recently had a scenario where we were using the and helper like this:

{{#if (and (is-permitted 'deleteFile') showDelete)}}
 <button>Delete</button>
{{/if}}

The is-permitted helper returned a DS.PromiseObject, which is handled correctly by the if component.
The and helper evaluates this code with the DS.PromiseObject

if (truthConvert(params[i]) === false) {
      return params[i];
 }

The truthConvert(<DS.PromiseObject>) === false, so the condition passes and returns the Promise object to the if component. When the promise evaluates to true, the Delete button is shown, regardless of the value for showDelete - that param is never evaluated by the truth helper.

I started to mock up a replacement, before I found that ember-promise-helpers could be used.

{{#if (and (await (is-permitted 'deleteFile')) showDelete)}}
 <button>Delete</button>
{{/if}}

So... I wonder if it's worth updating the docs to cover this scenario?

`or` cant be used when or condition value can be `false`

When I want to use a provided @arg whos value can be false and I want to default to true the or helper doesnt work as I need. See this example:

<Foo
	@bar={{or @argThatCanBeFalse true}}
/>

If @argThatCanBeFalse is sent in as false @bar will be resolved to true.

This is because or uses the truthConvert util that does a regular double not operator (!!): https://github.com/jmurphyau/ember-truth-helpers/blob/master/addon/utils/truth-convert.js#L11

Should we change the or helper to only treat undefined (and maybe null) as false values or should we create a new helper. Called something like or-nullish or or-undefined or something that works more like the Nullish coalescing operator (??) ?

I can do a PR if this is something that that maintainers want to add to the project. First question then is if we should change the current or helper or what the new one should then be called ๐Ÿ˜…

Not strict comparison?

Today I tried to do this: (not-eq currentRegion.id 1), but it failed, because id was "1", not 1. Would be nice if we have something like non-strict-not-eq.

I could create a PR if needed.

Can't import helper functions to use functions from Components or Controllers

It would be really cool to be able to access these functions from my component logic rather than having to write new, redundant helpers.

Can the library be updated to export each of the helper functions so that I can import them like so:

import { ltHelper } from 'ember-truth-helpers/helpers/lt';

would allow me to access functions like ltHelper in my js code?

Short-circuit Problem With `SafeString` Using `or` (And Maybe Other Helper)

In our app we used the or-helper in a template condition with two parameters, the first a SafeString (created with htmlSafe) and the other a tracked local property.

{{#if (or @safeString this.trackedProperty)}}
... awesome application html
{{/if}}

The problem we faced is that since the @safeString is always an object (even if its an empty string) the or evaluates to true for it, but the รฌf handles an empty safe string object properly and doesnt evaluate to true. This causes to never evaluate the second param, no matter if it changes to a "more truthy" value than the empty safe string. Is this something that should be changed or does it work as intended and should be addressed by the application? My problem with it is, that it handles htmlSafe in another way as the รฌf-helper does.

At the moment we just simply add checks for the string before we create our SafeString, e.g.:

const safeString = isEmpty(maybeHtml) ? '' : htmlSafe(maybeHtml);

This way the or checks on a normal empty string, which evaluates to false and therefore checks also the second param. Of course there are several other approaches like changing the order of the params, putting the or logic in a local getter and so on, but thats not part of my original question

Performances using plugin like ember-truth-helpers instead of just the Ember default way

If I use this plugin: https://github.com/jmurphyau/ember-truth-helpers

with many, let's say,

{{#if (eq model.beautiful true) }}

or

{{#if (or (eq model.beautiful true) (eq model.crazy true) ) }}

what is Ember creating in background? The same javascript works of computedProperties like these:

isBeautiful: Ember.computed.equal('model.beautiful', true); and so on?

If I have 30 computedProperty (Ember macros and custom ones) it's better to use this plugin or the default Ember way?

I'm wondering because in some templates I can have something like this many many times!:

{{#if (or (eq model.beautiful true) (eq model.crazy true) ) }}

instead of just this one:

{{#if isBeautifulOrCrazy }}

What is the best solution in terms of performances?

Process of creating this addon.

How you created this addon? I want to create an addon similar to these for Url and other helpers.
It would be greate if you can guide me a little. I'm very new to js and ember.

eq evaluates always false

I have this demo in Ember 2.4:

{{#each clients as |clientChoice|}}
{{clientId}} - {{clientChoice.id}}
{{eq clientId clientChoice.id}}
<br>
{{/each}}

And I get this evaluation in screen:
4 - 1 false
4 - 3 false
4 - 4 false
4 - 5 false

Why is this happening?

The complete code (I'm working with components):
component.hbs:

<select class="form-control" onchange={{action "selectClient" value="target.value"}} id="selcl">
  <option value="" disabled selected>{{title}}</option>
  {{#each clients as |clientChoice|}}
    <option value={{clientChoice.id}} selected={{eq clientId clientChoice.id}}>{{clientChoice.firstName}} {{clientChoice.lastName}}</option>
  {{/each}}
</select>
{{clientId}}
{{#each clients as |clientChoice|}}
<br>
{{clientId}} - {{clientChoice.id}}
{{eq clientId clientChoice.id}}
{{/each}}

component.js

import Ember from 'ember';

export default Ember.Component.extend({
  clientId: Ember.computed('clientId', function() {
    return this.get('clientId');
  }),
  client: null,
  clients: Ember.computed('clients', function() {
    return this.get('clients');
  }),
  actions: {
    selectClient(clientId) {
      this.set('clientId', clientId);
      console.log($("select").val());
    }
  }
});

Ember Global Deprecation Warning

There's a deprecation warning suggesting that ember-truth-helpers is dependent on an outdated version of ember-cli-babel.

WARNING: [DEPRECATION] [DEPRECATION] Usage of the Ember Global is deprecated. You should import the Ember module or the specific API instead.

See https://deprecations.emberjs.com/v3.x/#toc_ember-global for details.

Usages of the Ember Global may be caused by an outdated ember-cli-babel dependency. The following steps may help:

* Upgrade the following addons to the latest version:
[other addons]
  * ember-truth-helpers
### Details ###

Prior to v7.26.6, ember-cli-babel sometimes transpiled imports into the equivalent Ember Global API, potentially triggering this deprecation message indirectly, even when you did not observe these deprecated usages in your code.

<snip>

It looks like this can be fixed by updating ember-cli-babel to at least 7.26.6

Cascade helper lookup for addon developers

I'd like to package this addon with some of my addons in a way that consumers of my addon don't also need to install this dependency. Is this possible? I had thought that including it as a "dependency" rather than just a "devDependency" would be all that's needed but that appears not the be the case.

is-in helper

I have my own helper called is-in (and inversely, not-in)

{{#if (is-in messageType 'ignition_on' 'ignition_off' 'idling_start' 'idling_end')}}
 {{!-- messageType is equal to one of the given items --}}
{{/if}}

Is this worth adding to ember-truth-helpers? I will make a PR for it, but only if it's worth adding (I don't want to make a PR that just sits unmerged)

If so, I'll probably change it to something like this, so that it's always clear what item is the main element
{{#if (is-in item=messageType 'ignition_on' 'ignition_off' 'idling_start' 'idling_end')}}

Thoughts?

Update to ember-cli-babel@7

I include ember-truth-helpers as part of my own addon (let's say ember-foo-bar) in dependencies. When I install ember-foo-bar in an app that has config/targets.js set to add include Safari 13, ember serve breaks.

I believe this is happening because ember-cli-babel from here is being used as a preprocess because it's in dependencies of ember-foo-bar, and that preprocessor has an outdated version of browserslist which throws because it doesn't know about Safari 13.

Some workarounds I can think of but haven't tested yet:

  • Move e-t-h to devDeps of ember-foo-bar
  • Update browserlist directly? (not sure if there's a way to do this for something so nested)

But I'm filing this since ember-cli-babel@7 has been out for a while and it probably makes sense to update it here too.

How to use in ember-cli app?

Hi dudes,

most likely this is a very silly question, I apologize for it.

I try to use these awesome helpers in a ember-cli app, but I have "issues".

Added this into my bower.json

    "ember-truth-helpers": "0.0.5"

and run npm install. And now? Does ember-cli autoload the helper classes? Do I have to import something in my Brocfile.js? Or must I import the helpers somehow? Would be cool to have some short startup howto :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.