mercredi 30 décembre 2020

CssSyntaxError @fullcalendar/common/main.css Unknown word

I'm using Ember 3.19 and ember-auto-import@^1.5.3 with webpack config to build @fullcalendar/core@^5.5.0 as a module into my Ember app.

I run into this error during build, not certain what the issue is since the line causing the syntax error cannot be found in the package at all.

ERROR in ./node_modules/@fullcalendar/common/main.css
Module build failed (from ./node_modules/css-loader/dist/cjs.js):
CssSyntaxError

(1:1) ./node_modules/@fullcalendar/common/main.css Unknown word

> 1 | // Imports
    | ^
  2 | import ___CSS_LOADER_API_IMPORT___ from "../../css-loader/dist/runtime/api.js";
  3 | var ___CSS_LOADER_EXPORT___ = ___CSS_LOADER_API_IMPORT___(function(i){return i[1]});

 @ ./node_modules/@fullcalendar/common/main.js 6:0-20
 @ ./node_modules/@fullcalendar/core/main.js
 @ /tmp/broccoli-6893zcFAzhUCZAyl/cache-1309-bundler/staging/app.js
 @ multi /tmp/broccoli-6893zcFAzhUCZAyl/cache-1309-bundler/staging/l.js /tmp/broccoli

Below is my webpack config

webpack: {
    module: {
        rules: [ 
            { 
                test: /\.css$/, 
                include: [ path.resolve(__dirname, 'node_modules/@fullcalendar') ],
                use: ['css-loader'] 
            } 
        ]
    }
}



mardi 29 décembre 2020

Ember: this.router.refresh() throws error in ember octane

This is the below code I am using while doing refresh the route

export default class MyController extend Controller {
    @service router;

    @action refresh() {
         this.router.refresh()
    }
}

While calling this.router.refresh() it throws like refresh function not present.




lundi 28 décembre 2020

Error "str.replace is not a function" when using store.queryRecord with Ember Octane

I'm following an Embercasts course (Ember + Rails). For the screencasts, they used Ember 3.0, but I'm using Octane.

In one video, a custom service is implemented. This is what my version looks like:

import Service, { inject as service } from '@ember/service';

export default class CurrentUserService extends Service {
  @service store;

  load() {
    this.store.queryRecord('user', { me: true })
      .then((user) => {
        this.set('user', user);
      })
      .catch((e) => {
        debugger;
      });
  }
}

In the load function, which is being called from a route, this.store.queryRecord() causes an error:

TypeError: str.replace is not a function
  at Cache.func (index.js:64)
  at Cache.get (index.js:774)
  at decamelize (index.js:167) 
  at Cache.func (index.js:32)
  at Cache.get (index.js:774)
  at Object.dasherize (index.js:190)
  at UserAdapter.pathForType (json-api.js:221)
  at UserAdapter._buildURL (-private.js:293)
  at UserAdapter.buildURL (-private.js:275)
  at UserAdapter.urlForQueryRecord (user.js:13)

The relevant line is

var DECAMELIZE_CACHE = new _utils.Cache(1000, str => str.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase());

What's wrong here?




Ember Data JSON API - How to make a PATCH request using a related links URL

Ember version: 3.23

Ember Data: 3.23

I want to patch a relationship by making a request to the URL provided in the links object in the resources relationships:

{
  "type": "appointments",
  "id": "1",
  "attributes": {},
  "relationships": {
    "status": {
      "links": {
        "self": "/api/appointments/1/relationships/status",
        "related": "/api/appointments/1/status"
      },
      "data": {
        "type": "statuses",
        "id": "1"
      }
    }
  }
}

Given the above I want to issue the PATCH /api/appointments/1/relationships/status request.

// model/appointment.js
import Model, { attr, belongsTo, hasMany } from '@ember-data/model';
export default class AppointmentModel extends Model {
  @belongsTo('status') status;
};
// model/status.js
import Model, { attr, hasMany } from '@ember-data/model';
export default class StatusModel extends Model {
  @hasMany('appointment') appointments;
  @attr('string') name;
}

What I'm trying to do is:

const appointment = this.store.findRecord('appointment', id);
appointment.status = newStatus;
return appointment.get('status').save();

However the above returns an error saying save() is not a function on the status object (the status object is a ember Proxy object).

I know I can do:

const status = this.store.peekRecord('status', appointment.get('status.id'));
return status.save();

But no, that is not what I want to request. That would make a request to /api/statuses/1, which has no context of an appointment, the primary resource.

I also know that I can just save the appointment and get the relationship updates, but that would make the links I've setup completely useless. I want to be able to request the links I've setup for the relationships.

Essentially I want to be able to follow this part of the JSON:API spec: Updating Relationships.

How can I make a save() request to a relationship which uses the relationship links?




What is the correct way to convert observer to octane version of ember?

I was trying to convert all my ember-component into OCTANE version. But I got a bigger doubt. How can I convert the observer code into an OCTANE version? For example,

parent.hbs
 
 <Child @value= />

child.hbs

 <div></div>

child.js

  export default class ChildComponent extends Component {     
      /** Previous code: sample code only
        valueUpdate: observer('value', function() {
            this.newValue = this.value / 12 * 2;
        })
      */
  }


  How can I update the observer into octane way? Any idea please...

Note: I tried using '@observer' but it didn't work inside the component.




Update model hook value after button click and taking new value from input text

Newcomer here,

async model() {

let response = await fetch('http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=[APIKeyPlaceholder]);

var data = await response.json();

return data;

}

I am taking this ‘data’ value and displaying it on .hbs file. Now I have added an input text field and button for entering city name. How do I update the city name and model hook value(i.e data value) with the new value I take from .hbs file ?

Do I use controller? How do I bind input to ember variable?




dimanche 27 décembre 2020

How can I read the code of cardstack project?

I am very interested in the cardstack project, but I cannot read the code of this project. How can I read the code of this project? the project's github repo is enter link description here




vendredi 25 décembre 2020

How to test Ember computed properties that have no arguments/property dependencies?

You can find my source & test code below. I am testing the custom formHasSuccess() function, which has no arguments (or property dependencies). Using hasCorrectLength() & containsLettersAndNumbers(), formHasSuccess() will determine if a password is alphanumeric or of the correct length. In my test code, I've written a test case that I want to pass by returning true. However, when I run the tests, false is returned, which results in a failure.

  • ember-cli: v2.18.0
  • node: v10.16.3
  • os: win32 x64

Source code

import Ember from 'ember';
import layout from './template';

const { computed, defineProperty } = Ember;

export default Ember.Component.extend({
  layout: layout,
  viewport: Ember.inject.service(),
  classNames: ['input-password'],
  classNameBindings: ['showErrorClass:has-danger', 'isValid:has-success'],
  name: 'password',
  model: null,
  value: null,
  valuePath: '',
  show: false,
  validation: null,
  showValidations: false,
  didValidate: false,
  doesNotHaveFocus: true,

  notValidating: computed.not('validation.isValidating').readOnly(),
  hasContent: computed.notEmpty('value').readOnly(),
  hasWarnings: computed.notEmpty('validation.warnings').readOnly(),
  isValid: computed.and('hasContent', 'validation.isTruelyValid'),
  shouldDisplayValidations: computed.or('showValidations', 'didValidate', 'hasContent').readOnly(),
  showErrorClass: computed.and('doesNotHaveFocus', 'notValidating', 'showErrorMessage', 'validation'),
  showErrorMessage: computed.and('doesNotHaveFocus', 'shouldDisplayValidations', 'validation.isInvalid'),
  showWarningMessage: computed.and('doesNotHaveFocus', 'shouldDisplayValidations', 'hasWarnings', 'isValid').readOnly(),
  preventPaste: false,
  init() {
    this._super(...arguments);
    let valuePath = this.get('valuePath');

    defineProperty(this, 'validation', computed.readOnly(`model.validations.attrs.${valuePath}`));
    defineProperty(this, 'value', computed.alias(`model.${valuePath}`));
  },
  hasCorrectLength: Ember.computed('value', function () {
    var password = this.get('value');

    return password && password.length >= 8 && password.length <= 32;
  }),
  containsLettersAndNumbers: Ember.computed('value', function () {
    var password = this.get('value');

    return password && /[0-9]/.test(password) && /[a-zA-Z]/.test(password);
  }),
  // The code I am testing
  // -----------------------------------
  formHasSuccess: Ember.computed(function () {
    return this.hasCorrectLength || this.containsLettersAndNumbers;
  }),
  // -----------------------------------
});

Test code

import Ember from 'ember';
import sinon from 'sinon';
import { moduleFor, test } from 'ember-qunit';

moduleFor('component:ukb-password', 'Unit | Component | ukb-password', {
  unit: true,
  needs: ['service:viewport']
});

test("Should return 'true' as the password is alphanumeric & is of the correct length", async function(assert) {
  let component = this.subject();
  let mockPassword = "testpassword123";
  component.value = mockPassword;
  component.formHasSuccess = sinon.spy();
  await component.formHasSuccess();

  assert.ok(component.formHasSuccess.called, "The formHasSuccess method was called");
  assert.equal(component.formHasSuccess.returned(true), true, "Returned true");
});



Ember-Octane: Obj can't be observed in template while updated?

Most of you thought this is a weired question. Me too...

So, here is a controller file I'm having

application.js

export default class Application extends Controller.extend(someMixin)  {
   @tracked markedValues = {
      item1: {content: "This is item1", count: 1}
      item2: {content: "This is item2", count: 1}
   }

   @action updateCount(itemKey) {
       this.markedValues[itemKey].count = this.markedValues[itemKey].count + 1;
       this.markedValues = {...this.markedValues}
   }
}

application.hbs
  
        <div > and number is </div>
  

While I was updated the count it never reflects in the template. What mistake I did in this place?




jeudi 24 décembre 2020

How to listen parent component value change in child component ember octane?

This is my code

parent.hbs
 
 <ChildComp
   @value=
 />


parent.js
export class ParentComponet extends Component {
  @tracked this.changes = [1,2,3]
  
  @action addChanges() {
     this.changes = [...this.changes, this.changes.length]
  }
}

child-comp.js
export class ChildComponet extends Component {
   // I wanted to observe this.args.changes updated
   // Based on that I need to call some operation
   get operation() {
      let parent = this.args.values.map((obj) {
            if (obj.parent !== null) {
             set(obj, 'goal', null);
             set(obj, 'newSubGoal', null);
            }
    });
   }
}

I wanted to observe this.args.changes in my child compoent. How can I do that in ember-octane way?




mercredi 23 décembre 2020

What causing this issue when capturing screen shot with PIXI JS

I have used PIXI JS to capture screen and save as screenshots. It works fine on some screens and it gives and error on another screen. Anyone have an idea which causing this error?

enter image description here




mardi 22 décembre 2020

How do I go about stubbing a Task in Ember.js?

I am using Sinon with Ember.js Concurrency Tasks and am trying to stub the task in a test.

The code looks something like this:

component .ts file:

import Component from '@glimmer/component';
import { TaskGenerator, TaskInstance } from 'ember-concurrency';
import { task } from 'ember-concurrency-decorators';
import { taskFor } from 'ember-concurrency-ts';

export default class Container extends Component<Args> {

    @task *myTask(): TaskGenerator<Data> {
        const response: Data = yield json('someURL'); //json() returns a JSON object from a request to someURL
        return response;
    }

    get task(): TaskInstance<Data> | null {
        const task = taskFor(this.myTask);
        return task.last ? task.last : task.perform();
    }

    @action
    someMethod(): void {
        const task = taskFor(this.myTask);
        task.perform();
    }
}

relevant test from component test file:

...
module('Integration | Component | container', function(hooks){
    test('some test', async function(this: Context, assert) {
    await render(hbs`
        <Container @someMethod= as |c| >
            // some code that uses c
        </Container>
    `);
}

How would I stub the myTask task? I would essentially like to have it so that I am able to manually control the response that comes out of myTask so an HTTP response doesn't have to be made in the test.




vendredi 18 décembre 2020

How to pass conditional string to ember component attribute using concat?

What is the correct way to pass the conditional string when assigning the component's attribute using ember concat() method?

Consider the following


  

What I want to do is adding the --disabled postfix conditionally, based on model.disabled property.

What I have tried:

")}}
  

Resulting in:

<div class="component-name-row">
  Component name
</div>

The other thing I tried was using ternary helper, based on this answer:


  

but it crashed:

Assertion Failed: A helper named "ternary" could not be found

Is there any way to do that? If not, how would I achieve the same effect using a different approach?




mercredi 16 décembre 2020

Ember.js - Parsing error: Unexpected token, expected ";" in config/environment.d.ts(.js)

I see that error/warning in every build or run.

...lisweb_frontend/app/config/environment.d.ts
  10:9  error  Parsing error: Unexpected token, expected ";"

   8 |  * since different ember addons can materialize new entries.
   9 |  */
> 10 | declare const config: {
     |         ^
  11 |   environment: any;
  12 |   modulePrefix: string;
  13 |   podModulePrefix: string;

✖ 1 problem (1 error, 0 warnings)

But the project works. I tried to change from ".ts" to ".ts" but the problem still the same. The project(Public for limited time): https://github.com/hotsoft-informatica/lisweb_frontend/

Have anyone an idea about how to solve that?

Thanks!




Ember component is not re-rendering on change of @tracked variable

My UserTag component is only re-rendering on page refresh. I expect it to refresh when action saveRoles(updatedUserRoles) is used, since it depends on an @tracked variable. UserRoles is a component from an imported dependency in package.json.

Defined in my template:

<UserTag @tags= />

In my controller:

  @tracked persistedRoles = null;

  @computed('persistedRoles')
  get sortedUserRoles() {
    console.log('sorting user roles...');
    return this.persistedRoles.sort();
  }

  @action
  saveRoles(updatedUserRoles) {
    ... // Some manipulating of updated roles for AJAX call

    this.persistedRoles = [...updatedUserRoles];
  }

I've tried adding a console.log in sortedUserRoles() to see if it is being called when I save permissions, but it is not being used. If I add outside of the @tags=..., it is called and the sorted roles are shown, which leads me to believe it ignored the tracking when set to a property for a component. Is this the case? (Note: @tags is @tracked in <UserTag>)

Versions:

"ember-cli": 3.22.0

"ember-data": "~3.18.0"




dimanche 13 décembre 2020

Ember.js with Yarn: Cannot find module './_baseUniq' (Works with NPM)

Recently, I'm get that error above when using Ember.js project with Yarn, not occurred with NPM.

The error:

Cannot find module './_baseUniq'
Require stack:
- /mnt/82eb80d7-628c-41a3-b046-c40ab727aaaf/home/wellington/projetos/hotsoft/lisweb_frontend/node_modules/inquirer/node_modules/lodash/uniq.js
- /mnt/82eb80d7-628c-41a3-b046-c40ab727aaaf/home/wellington/projetos/hotsoft/lisweb_frontend/node_modules/inquirer/lib/prompts/expand.js
- /mnt/82eb80d7-628c-41a3-b046-c40ab727aaaf/home/wellington/projetos/hotsoft/lisweb_frontend/node_modules/inquirer/lib/inquirer.js
- /mnt/82eb80d7-628c-41a3-b046-c40ab727aaaf/home/wellington/projetos/hotsoft/lisweb_frontend/node_modules/@ember/optional-features/features/application-template-wrapper.js
- /mnt/82eb80d7-628c-41a3-b046-c40ab727aaaf/home/wellington/projetos/hotsoft/lisweb_frontend/node_modules/@ember/optional-features/features.js
- /mnt/82eb80d7-628c-41a3-b046-c40ab727aaaf/home/wellington/projetos/hotsoft/lisweb_frontend/node_modules/@ember/optional-features/index.js
- /mnt/82eb80d7-628c-41a3-b046-c40ab727aaaf/home/wellington/projetos/hotsoft/lisweb_frontend/node_modules/ember-cli/lib/models/package-info-cache/package-info.js
- /mnt/82eb80d7-628c-41a3-b046-c40ab727aaaf/home/wellington/projetos/hotsoft/lisweb_frontend/node_modules/ember-cli/lib/models/package-info-cache/index.js
- /mnt/82eb80d7-628c-41a3-b046-c40ab727aaaf/home/wellington/projetos/hotsoft/lisweb_frontend/node_modules/ember-cli/lib/models/project.js
- /mnt/82eb80d7-628c-41a3-b046-c40ab727aaaf/home/wellington/projetos/hotsoft/lisweb_frontend/node_modules/ember-cli/lib/utilities/get-config.js
- /mnt/82eb80d7-628c-41a3-b046-c40ab727aaaf/home/wellington/projetos/hotsoft/lisweb_frontend/node_modules/ember-cli/lib/utilities/instrumentation.js
- /mnt/82eb80d7-628c-41a3-b046-c40ab727aaaf/home/wellington/projetos/hotsoft/lisweb_frontend/node_modules/ember-cli/lib/cli/index.js
- /mnt/82eb80d7-628c-41a3-b046-c40ab727aaaf/home/wellington/projetos/hotsoft/lisweb_frontend/node_modules/ember-cli/bin/ember


Stack Trace and Error Report: /tmp/error.dump.b626eaa199e9d3b0c084265efd7f89ea.log
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

The gist: https://gist.github.com/wellington1993/2162ea65802e43fbbb6b7669559ee6db

The package.json file: https://gist.github.com/wellington1993/2162ea65802e43fbbb6b7669559ee6db#file-package-json

The Yarn.lock file: https://gist.github.com/wellington1993/2162ea65802e43fbbb6b7669559ee6db#file-yarn-lock

The project(Public available for limited time): https://github.com/hotsoft-informatica/lisweb_frontend

The error log file: https://gist.github.com/wellington1993/2162ea65802e43fbbb6b7669559ee6db#file-error-dump-b626eaa199e9d3b0c084265efd7f89ea-log

The Yarn install output: https://gist.github.com/wellington1993/2162ea65802e43fbbb6b7669559ee6db#file-1-yarn-install

Anyone have ideias to solve that problem?

Thanks!




How to detect if included relationship is loading

Please see related twiddle https://ember-twiddle.com/e3872f1410e0d844b6d6c6bc9a2c9dc1

// models/parent.js
export default class extends Model {
  @attr('string') name;
  @hasMany('child') children;
}

// models/child.js
export default class extends Model {
  @attr('string') name;
}
// routes/application.js
export default Route.extend({
  model() {
    return this.store.findAll('parent');
  }
});

// routes/second-route.js
export default Route.extend({
  model(params) {
    return this.store.findRecord('parent', params.parent_id, { 
      include: 'children'
    });
  }
});
//templates/application.hbs

  <div></div>
  <LinkTo @route="second-route" @model=>
    Go to second route with this model
  </LinkTo>




//templates/second-route.hbs

  <div></div>
  
  <div>Nothing to display</div>

In the ember twiddle

  1. Click link to transition to second route
  2. Observe second route displays "Nothing to display"
  3. After 2 seconds, when the request completes, the template will update to display the hasMany models

I would have expected that the template is only rendered after the request to /parents/1 completes, but this is not the case

  1. Why does the template not wait for the route's model?
  2. How can I improve UX by detecting that the hasMany relationships are loading to display a loading indicator?

Flags on the promise proxies do not seem to change at any point




jeudi 10 décembre 2020

How to creating an app with Laravel + EmberJS

I need to create an app using EmberJS 2.18 for the frontend and Laravel ^6.0 for the backend. I found a guide (here: https://culttt.com/2015/04/06/getting-started-with-laravel-and-ember/) but it's 5 years old and after following its advice it referred to directories that don't exist so I couldn't complete it and I don't know how to check if it's working.

I have zero experience with either framework and I'm trying to piece this all together. Is there an easy to follow tutorial for how to set this up?




mercredi 9 décembre 2020

Reading a Json Array from a snapshot to ember html page with no Jquery

I set a bookmarks and favorites page of movies to a firebase at a movie profile page. Now I am trying to grab the information from only the ones that are bookmarked, grab the information (movieIds, titles, etc., and post that onto my html page. For some reason I cannot read in the information, my console.log shows me that the array is correct and has all the information I need, however I can't access it on the html page for some reason. This is the bookmarks.js file

export default class BookmarksRoute extends Route {
  async model(params) {
    var user = firebase.auth().currentUser;

    //check if user is logged in
    if (user) {
      //first check if movie has been saved before
      firebase
        .database()
        .ref("users/" + user.uid + "/savedMovies/")
        .once("value", (snapshot) => {
          if (snapshot.exists()) {
            //snapshot is returning the json for this particular movie saved by user id and putting it in userData
            const userData = snapshot.val();
            console.log("exists........", userData);
            var returnArr = [];
            snapshot.forEach(function (childSnapshot) {
              var item = childSnapshot.val();
              item.key = childSnapshot.key;
              returnArr.push(item);
            });
            console.log("test", returnArr);
            console.log("Bookmarked: ", returnArr[0].isBookmarked);
            return returnArr;


          }
        });

    }
  }

}

This is the HTML file

<header class="bookmarks-header">
  <h1>BookMarks</h1>
</header>
<main class="bookmark-frame">
  <div class="ui four column grid">
    <div id="text">
      <h1></h1>
      
      <h2></h2>
      
    </div>
  </div>
</main>

Examples of what prints on my console.log is

0: {adult: false, isBookmarked: true, isFavorited: false, movieID: 41586, poster_path: "/1ZsF9u6bBp46mMXTOpSAqowlZW4.jpg", …}
1: {isBookmarked: false, isFavorited: true, movieID: 337401, poster_path: "/aKx1ARwG55zZ0GpRvU2WrGrCG9o.jpg", release_date: "2020-09-04", …}
2: {isBookmarked: true, isFavorited: false, movieID: 497358, poster_path: "/kQp149wW9XN7lEH5B3xkKpkzYGT.jpg", release_date: "1969-12-25", …}
3: {isBookmarked: false, isFavorited: true, movieID: 577922, poster_path: "/k68nPLbIST6NP96JmTxmZijEvCA.jpg", release_date: "2020-08-22", …}
4: {isBookmarked: false, isFavorited: true, movieID: 590706, poster_path: "/eLT8Cu357VOwBVTitkmlDEg32Fs.jpg", release_date: "2020-11-20", …}
5: {isBookmarked: true, isFavorited: false, movieID: 671583, poster_path: "/xfYMQNApIIh8KhpNVtG1XRz0ZAp.jpg", release_date: "2020-07-31", …}
6: {isBookmarked: true, isFavorited: false, movieID: 729648, poster_path: "/6OeGqp18oZucUGziMIRNhLouZ75.jpg", release_date: "2020-11-02", …}
[]: (...)
firstObject: (...)
hasArrayObservers: (...)
lastObject: (...)
length: 7
__proto__: Array(0)

Export of my JSON file looks like:

{
  "CfWjFzxOWBfFbfc80NFmktwFJye2" : {
    "savedMovies" : {
      "454433" : {
        "isBookmarked" : true,
        "isFavorited" : false,
        "movieID" : 454433,
        "poster_path" : "/awcPLFFYjufRXd2oAAP6ZIXF9vM.jpg",
        "release_date" : "2020-08-14",
        "title" : "Magic Camp",
        "vote_average" : 7
      },
      "524047" : {
        "isBookmarked" : false,
        "isFavorited" : true,
        "movieID" : 524047,
        "poster_path" : "/bNo2mcvSwIvnx8K6y1euAc1TLVq.jpg",
        "release_date" : "2020-07-29",
        "title" : "Greenland",
        "vote_average" : 7.2
      },
      "524087" : {
        "isBookmarked" : false,
        "isFavorited" : true,
        "movieID" : 524087,
        "poster_path" : "/3rRUp4WZdvt4LfdXIWL0qmFv9UI.jpg",
        "release_date" : "2018-11-02",
        "title" : "Dear Ex",
        "vote_average" : 7.4
      },
      "590706" : {
        "isBookmarked" : true,
        "isFavorited" : true,
        "movieID" : 590706,
        "poster_path" : "/eLT8Cu357VOwBVTitkmlDEg32Fs.jpg",
        "release_date" : "2020-11-20",
        "title" : "Jiu Jitsu",
        "vote_average" : 5.7
      },
      "602211" : {
        "isBookmarked" : true,
        "isFavorited" : false,
        "movieID" : 602211,
        "poster_path" : "/4n8QNNdk4BOX9Dslfbz5Dy6j1HK.jpg",
        "release_date" : "2020-11-13",
        "title" : "Fatman",
        "vote_average" : 6.1
      },
      "654028" : {
        "isBookmarked" : true,
        "isFavorited" : false,
        "movieID" : 654028,
        "poster_path" : "/6sG0kbEvAi3RRLcGGU5h8l3qAPa.jpg",
        "release_date" : "2020-11-18",
        "title" : "The Christmas Chronicles: Part Two",
        "vote_average" : 7.1
      },
      "724989" : {
        "isBookmarked" : true,
        "isFavorited" : true,
        "movieID" : 724989,
        "poster_path" : "/ugZW8ocsrfgI95pnQ7wrmKDxIe.jpg",
        "release_date" : "2020-10-23",
        "title" : "Hard Kill",
        "vote_average" : 5
      },
      "726208" : {
        "isBookmarked" : false,
        "isFavorited" : true,
        "movieID" : 726208,
        "poster_path" : "/ffdPUteSePSqJEhKJKwgSIWumC2.jpg",
        "release_date" : "2020-07-24",
        "title" : "Don't Listen",
        "vote_average" : 6.7
      }
    }
  },
  "uY5GV5VCMbPufW4eVQChh61sbOC2" : {
    "savedMovies" : {
      "41586" : {
        "adult" : false,
        "isBookmarked" : true,
        "isFavorited" : false,
        "movieID" : 41586,
        "poster_path" : "/1ZsF9u6bBp46mMXTOpSAqowlZW4.jpg",
        "release_date" : "1999-12-07",
        "title" : "K-911",
        "vote_average" : 5.5
      },
      "337401" : {
        "isBookmarked" : false,
        "isFavorited" : true,
        "movieID" : 337401,
        "poster_path" : "/aKx1ARwG55zZ0GpRvU2WrGrCG9o.jpg",
        "release_date" : "2020-09-04",
        "title" : "Mulan",
        "vote_average" : 7.2
      },
      "497358" : {
        "isBookmarked" : true,
        "isFavorited" : false,
        "movieID" : 497358,
        "poster_path" : "/kQp149wW9XN7lEH5B3xkKpkzYGT.jpg",
        "release_date" : "1969-12-25",
        "title" : "Ave, Vita",
        "vote_average" : 6.8
      },
      "577922" : {
        "isBookmarked" : false,
        "isFavorited" : true,
        "movieID" : 577922,
        "poster_path" : "/k68nPLbIST6NP96JmTxmZijEvCA.jpg",
        "release_date" : "2020-08-22",
        "title" : "Tenet",
        "vote_average" : 7.4
      },
      "590706" : {
        "isBookmarked" : false,
        "isFavorited" : true,
        "movieID" : 590706,
        "poster_path" : "/eLT8Cu357VOwBVTitkmlDEg32Fs.jpg",
        "release_date" : "2020-11-20",
        "title" : "Jiu Jitsu",
        "vote_average" : 5.7
      },
      "671583" : {
        "isBookmarked" : true,
        "isFavorited" : false,
        "movieID" : 671583,
        "poster_path" : "/xfYMQNApIIh8KhpNVtG1XRz0ZAp.jpg",
        "release_date" : "2020-07-31",
        "title" : "Upside-Down Magic",
        "vote_average" : 7.7
      },
      "729648" : {
        "isBookmarked" : true,
        "isFavorited" : false,
        "movieID" : 729648,
        "poster_path" : "/6OeGqp18oZucUGziMIRNhLouZ75.jpg",
        "release_date" : "2020-11-02",
        "title" : "The Dalton Gang",
        "vote_average" : 4.7
      }
    }
  }
}



Security issues with having an array of allowed origins for iFrame?

Currently I have a couple environments of the same URL that should be allowed to listen to the postMessage and the issue I have is that these URLs are exposed in the index.html and was wondering is there any issues with doing this? Any suggestions on handling this?

Ex:

const allowedURL = ["https://dev.test.com", "https://stg.test.com",..]

window.addEventListener( function(event) {
if(allowedURL.includes(event.origin)){ return } });



lundi 7 décembre 2020

Interact.js - dragging single div "jumping around" in Ember

I'm using Ember, and I'm trying to setup a simple draggable div example using the interact.js library but I'm having some issues.

I'm aware that the library DOES NOT modify the DOM and you need to do that yourself which is fine. I'm following the example on the website but I translating it to Ember:

https://interactjs.io/docs/draggable

Here's what I've done:

Step #1: Create an Ember template with a simple DIV

<div
    role="button"
    class="draggable-card w-20 h-20"
/>

The "draggable-card" tag will be made "interactive" when I make the call to the interact library in the controller.

Step #2: Create an Ember controller

The controller runs as "code behind" and controls state. In this case our controller does a number of things:

2.1 Makes a call to the Interact library to make DOM objects "interactive" (i.e. draggable)

this.draggableCards = interact('.draggable-card');

this.draggableCards.draggable({
    origin: 'self',
    inertia: false,
    listeners: {
        start: this.dragStart,
        move: this.dragMove,
        end: this.dragEnd
    }
});

This makes all "draggable-card" elements draggable as well as creating drag handlers for dragStart, dragMove and dragEnd.

2.2 Create a dragStart event handler

@action
dragStart(event) {
    this.isDraggingCard = true;

    // modify dom to support dragging the element
    event.target.style.position = 'relative';
    event.target.style.touchAction = 'none';
    event.target.style.userSelect = 'none';       
    event.target.style.left = '0px';
    event.target.style.top = '0px';

    // used to track position from start of drag
    this.dragCardPositionDelta = { dx: 0, dy: 0 };     
};

2.3 Create a dragMove event handler

@action
dragMove(event) {
    this.dragCardPositionDelta.dx += event.dx;
    this.dragCardPositionDelta.dy += event.dy;

    event.target.style.transform =
        `translate(
            ${this.dragCardPositionDelta.dx}px,
            ${this.dragCardPositionDelta.dy}px
        )`;
};  

As far as I understand things, (event.dx, event.dy) provides the number of pixels the element has been moved since the last call to dragMove. I keep track of (dragCardPositionDelta.dx, and dragCardPositionDelta.dy) which tracks the pixels the element has moved since the start of the drag.

Setting this up makes the element draggable, but (event.dx, event.dy) doesn't seem to be calculating correctly as I drag. The result is that the div jumps around the place. I also notice that the div doesn't move consistently with the pointer. It's all very strange and given how simple the example on the website is I'm not sure what's going wrong. I can only suspect that for some (event.dx, event.dy) is not being calculated correctly.

I've setup a similar example with another library: Draggabilly (https://draggabilly.desandro.com) and it pretty much worked out of the box but I've temporarily abandoned it due to some issues, thus trying out Interact.js.

Any help would be appreciated.

Thanks,

Dave




EmberJS 3.19 performance issues with large amount of data

So I'm currently trying to debug some major performance issues we're having with our app. Once some more data is loaded (~1000 in the store, ~30 rendered) the app tends to get slowed down by a lot. Firefox is telling me, the tab is using ~100MB memory.Which isn't optimal, but I have tabs that use more and aren't problematic.

Interesting to note is, that I use pretty much one single route template for all our routes. The thing that differs between the routes is the model, but not the template. The slowdowns happen most notably when transitioning between routes. It's also noticeable on UI events though.

It's very hard for me to pinpoint the problem and show you some code. The whole source is public though so feel free to look into it. https://github.com/puzzle/cryptopus/tree/master/frontend

Do you have any advice for me? Debugging performance issues in EmberJS over all or even for my specific problem? I'm thankful for any inputs.




samedi 5 décembre 2020

Click on ember.js enabled element using Selenium

I am trying to click on the following button on a linkedin page using selenium:

<button id="ember607" class="share-actions__primary-action artdeco-button artdeco-button--2 artdeco-button--primary ember-view" data-control-name="share.post"><!---->
<span class="artdeco-button__text">
    
        Post
    
</span></button>

I have tried to use:

  • driver.find_element_by_id, but the id of the button seems to keep changing number
  • driver.find_element_by_xpath, but this contains the button number, so also fails
  • driver.find_element_by_class_name('share-actions__primary-action artdeco-button artdeco-button--2 artdeco-button--primary ember-view'), this fails even though the class name is correct ?

Basically, all methods generate the same error message:

Exception has occurred: NoSuchElementException
Message: no such element: Unable to locate element:{[*the_error_is_here*]}

I have also tried the xpath contains() method, but this does not find the button.

What would be the correct way to click on this button please ?

I am using python version 3.9 on windows with driver = webdriver.Chrome




vendredi 4 décembre 2020

Discourse (Ember.js?) issue using document.write

Having a problem getting my adserver working on Discourse via it's Ad Plugin. The script is called via link to the adserver's index.php file which generates the text below. However even though this text is in Discourse's encoded data for the page build it doesn't display. The same script call put into the themes </body> area works (just down at the bottom of the forum. But that part of the page HTML is not encoded, so I am guessing this is an Ember.js issue?

Here is the adserver output.

document.write('<div class="banner" style="width:728px;height:90px;overflow:hidden;margin-bottom:3px;"><a href="https://adserver.site.net/index.php?section=click&action=875"><img src="https://adserver.site.net/banners/L112320.jpg" class="adimage"></a></div>');

Anyone have any ideas how this can be worked around? I do have root access for the server but I have zero experience with Ruby or Ember. I can change the output of the adserver script if there is a better way, etc.

Thanks!




jeudi 3 décembre 2020

ember js access environment from ember-cli-build in the vendor file

In my ember-cli-build.js file I'm importing a vendor library called new-relic by using app.import('vendor/new-relic.js'), I would like to pass a parameter called env to the new-relic vendor file and use it in the new-relic.js file. I tried doing

app.import('vendor/new-relic.js', { env: 'production' });

When I try to console log env in the vendor file, it says undefined. Is there any way to pass the env to the vendor file?




mardi 1 décembre 2020

Getting properties of ember component from ember component-class

I have been trying to get the value of a propertie of a component from an action from its class. My main goal is to relate two objects: the "auction" passed into my component (shown in the code below)

new.hbs

<AuctionForm 
    @auction=
    @products=/>

with the selected product on a select tag inside the "AuctionForm" Component as so:

auction-form.hbs

<div class="row">
    <label for="product">Produto</label>
    <select name="product" onchange=>
        <option value="" selected='selected' disabled='disabled'>-------</option>
        
            <option value="" selected=></option>
        
    </select>
</div>

and I want to bind this two objects on the "selectProduct" action of the class:

auction-form.js

import Component from '@glimmer/component';
import { action } from '@ember/object';


export default class AuctionFormComponent extends Component {
    @action selectProduct(product) {
        this.get('auction').set('product', product); // this doesn't work on ember newest version
    }
    @action save(auction) {
        auction.save();
    }
}

Although, whenever I try to access its value on the component-class via "this.get()" function (just as I used to do on previous ember versions) I get an error saying that "this.get is not a function".

After digging a lot on the web I couldn't find a straight forward solution neither the official solution provided by the documentaion.

The closest I got to a solution was to declare "auction" as a computed propertie (https://api.emberjs.com/ember/3.22/classes/Component). But, I could not manage to implement it on a javascript file, once its structure (like the code below) only works on TypeScript files.

import Component from '@glimmer/component';
import { action } from '@ember/object';
import { computed } from '@ember/object';


export default class AuctionFormComponent extends Component {
    auction: computed('auction', function() {
        return this.auction;
    }
    @action selectProduct(product) {
        debugger;
        this.get('auction').set('product', product);
    }
    @action save(auction) {
        auction.save();
    }
}

Does anyone knows the correct way of performing such a task in ember 3.22?

Thank you very much.




Search bar will not reload when hitting button, but only on the actual search page

I am using Semantic UI, Ember, and a movie API to create a website. I am creating a search bar that allows someone to search through all the movies in the API. These movies are not stored on the webpage and so I call the API with the API key and the specific movie name which I pull from the search bar. The search bar is part of the Nav bar which is a part of all the pages in the website.

<div class="ui action input">
      <input type="text" id="myInput" placeholder="Search for movies...." title="Type in a movie" value="">
      <LinkTo @route="search">
        <button class="ui icon button"  type="submit" id="myBtn" onclick="myFunction1">
          <i class="search icon"></i>
        </button>
      </LinkTo>
    </div>

I have this placed in the Search.js file so that when the search button is hit, the word is taken and loaded into the page.

   async model(params) {
        //set up api  
        var x = document.getElementById("myInput").value; 
      
        const response = await fetch('https://api.themoviedb.org/3/search/movie?api_key=4517228c3cc695f9dfa1dcb4c4979152&language=en-US&query='
        + x + '&page=1&include_adult=false');
        const data = await response.json();

        //return results portion of json
        return data.results;
    }

My search page itself is just formatting the movies that show up, it works perfectly fine on every page except for the Search page after the movies are loaded in. It will not search again unless I travel outside the search page. I can't seem to figure a way out how to make this search bar work inside the search page.




lundi 30 novembre 2020

Map update periodically in forest admin using leaflet

I am using map to show riders while driving. Map is showing location as a marker on Map. But my map is not updating after data updated in mongodb. I am using forestadmin and node js. In forestadmin, I am using smartview where I will have to use ember.js. I am showing leaflet OpenStreetMap map.

here is the javascript I am using:

export default Component.extend(SmartViewMixin, {
  store: service(),

  tagName: "",

  map: null,
  loaded: false,

  init(...args) {
    this._super(...args);

    this.loadPlugin();
  },

  didInsertElement() {
    this.displayMap();
  },

  onRecordsChange: observer("records", function () {
    this.displayMap();
  }),

  loadPlugin() {
    scheduleOnce("afterRender", this, () => {
      $.getScript(
        "//cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.js",
        () => {
          $.getScript(
            "//cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.2/leaflet.draw.js",
            () => {
              this.set("loaded", true);
              this.displayMap();
            }
          );
        }
      );

      const headElement = document.getElementsByTagName("head")[0];
      const cssLeafletLink = document.createElement("link");
      cssLeafletLink.type = "text/css";
      cssLeafletLink.rel = "stylesheet";
      cssLeafletLink.href =
        "//cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.css";

      headElement.appendChild(cssLeafletLink);

      const cssDrawLink = document.createElement("link");
      cssDrawLink.type = "text/css";
      cssDrawLink.rel = "stylesheet";
      cssDrawLink.href =
        "//cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.2/leaflet.draw.css";

      headElement.appendChild(cssDrawLink);
    });
  },

  displayMap() {
    if (!this.loaded) {
      return;
    }

    if (this.map) {
      this.map.off();
      this.map.remove();
      this.map = null;
    }

    const markers_arr = [];

    this.records.forEach(function (record) {
      markers_arr.push([
        record.get("forest-latitude"),
        record.get("forest-longitude"),
        record.get("id"),
        record.get("forest-userId.forest-email"),
       
        record.get("forest-userId.forest-bikeModel"),
        record.get("forest-userId.forest-bikeRegNo"),
        record.get("forest-userId.forest-phone"),
      ]);
    });
    var map = L.map("map").setView(
      new L.LatLng(markers_arr[0][0], markers_arr[0][1]),
      7
    );

    const osmUrl =
      "https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png";
    const osmAttrib =
      '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>';
    const osm = new L.TileLayer(osmUrl, { attribution: osmAttrib });
    map.addLayer(osm);

    var markers = [];

    markers_arr.forEach(function (mark) {
      var foo = "ID: "+mark[2] + "\n <br>Email: " + mark[3]+ "\n <br>Phone: " + mark[6]+ "\n <br>Bike Model: " + mark[4] + "\n <br>Bike #: " + mark[5]
      var marker1 = L.marker([mark[0], mark[1]] )
        .addTo(map)
        .bindPopup(foo);
      markers.push(marker1);

      marker1.on("mouseover", function (ev) {
        marker1.openPopup();
      });
    });

    function markerFunction(id) {
      for (var i in markers) {
        var markerID = markers[i].options.title;
        if (markerID == id) {
          markers[i].openPopup();
        }
      }
    }
  },
});

and here is the HTML:

<style>
  #map {
    width: 100%;
    height: 100%;
    z-index: 4;
  }  
</style>
<div id="map"></div>

I also use fetchRecord in HTML but it not updating latest data.

<button >
  Refresh data
</button>

Help me 🙏🏻🙏🏻🙏🏻




vendredi 27 novembre 2020

How to use ember-2-legacy?

We have the post in the documentation for Ember 2.16 about addition deprecation ember-2-legacy:

Ember 2 Legacy until: 3.4 id: ember-2-legacy Ember provides ember-2-legacy which is an addon to help app with deprecations during the transition from the 2.x series to 3.x.

https://deprecations.emberjs.com/v2.x/#toc_ember-2-legacy

We also have some configuration in README:

In ember-cli-build.js you can specify a config for ember-2-legacy

https://github.com/emberjs/ember-2-legacy#what-deprecations-are-covered

So, as I understand, if we specify some flag with false, like this:

new EmberApp(defaults, {
  'ember-2-legacy': {
    'enumerable-contains': false

then this particular feature will be off in ember app.

Should my App raise some error or notify me by console warning? In general, I have a case of all flags false and all tests passed, so my question is: is it mean that my application has no those deprecations usage cases?

Shall I keep ember-2-legacy with config in ember-cli-build.js til Ember upgrade 3.0

or

case with no errors on CI build means that: my App already has no deprecation and I can remove this addon at all?




jeudi 26 novembre 2020

Ember required component arguments

How can I require a parameter in an ember component.

E.g.:

class MyComponent extends Component {
  get my_value() {
    return this.args.my_argument + 1
  }
}

I want the component to throw an error when the component is instantiated and not when the function is called.

The only way I can think of is like this:

class MyComponent extends Component {
  constructor(owner, args) {
    super(owner, args)
    assert(!!args.my_argument, "MyComponent requires my_argument")
  }
  ...
}

This however seems a bit tedious and does not look right :/

EDIT:

It would be even better if I could specify the type of the argument.




mercredi 25 novembre 2020

EmberJS: Injecting owner to native class from component

The thing i'm trying to do, is to inject owner to my JS native class in Ember(3.15.0). It looks something like this:

  component.ts

  export default class ClassOne extends Component {
    constructor() {
      super(...arguments);
      const myClass = new ClassTwo();
      ...
    }
  }

  ClassTwo.ts

  export default class ClassTwo {
    @service() someService: ServiceType;
    ...
  }
  

Because of that, on someService, i'm getting expectable Attempting to lookup an injected property on an object without a container, ensure that the object was instantiated via a container

I've seen similar questions that were solved by using getOwner(this).ownerInjection() but those were all based on Class.create() that was extended by Ember.Object.

Is there any way to do that?

Thanks in advance for any help.




lundi 23 novembre 2020

Timezone sensitive date comparisons in Javascript

I'm determining the difference between two calendar dates in Javascript in an Ember app. I'm currently using date-fns's differenceInCalendarDays.

Now that mostly provides the desired results, the only issue is that I need to handle calculating the difference between 2 dates that is sensitive to a timezone (not the local timezone to the browser).

As far as I'm aware JS Dates are tracked as UTC, with no timezone stored on the date object itself. Any timezone localization I've done in JS has been outputting a string. Is there a good library or way to accomplish differenceInCalendarDays while taking into account the timezone?

const daysAgo = this.intl.formatRelative(-differenceInCalendarDays(new Date(), someOtherDay), {
    unit: 'day', 
    numeric: 'auto', 
    timeZone: 'this.intl.timeZone
});

This is a small sample of what I'm doing, obviously differenceInCalendarDays will resolve to a number which won't take into account any timeZone. The docs for differenceInDays is timezone sensitive to the browser's local time (which is not helpful here), but differenceInCalendarDays makes no such mention. Any help would be greatly appreciated!




Ember JS 3.20 app with SailsJS 0.12.x backend and websocket connection

I am using sails 0.12.14 version back-end with EmberJS 3.20 front-end. I am currently dealing with a websocket connection problem in production.

Using "sails.io.js": "^1.1.0", "socket.io-client": "^1.4.5" for sails compatibility in Ember ( same goes for sails back-end ).

Both servers are on AWS. When i use app in development (localhost), everything is OK, socket is connected, messages are pushed from back-end to fron-end via socket. But when i deploy Ember app to production, i get this:

WebSocket connection to 'ws://{my-page-domain}/socket.io/?__sails_io_sdk_version=1.1.0&__sails_io_sdk_platform=node&__sails_io_sdk_language=javascript&EIO=3&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 400

Where is this comming from and why can't ember app access sails.io ? Back-end is running just fine.

Any idea what is happening ?

Any insight whatsoever is appreciated.




dimanche 22 novembre 2020

How to click on the ember.js enabled button using Selenium and Python

I have been trying to make this clickable and I just cannot understand what I am doing wrong. I am also trying to induce webdriverwait, so that it is clicked when it appears.

This is my code so far:

def order(k):
    driver = webdriver.Chrome(os.getcwd()+"\\webdriver\\chromedriver.exe") 
    driver.get("website.com/login-to-checkout")
    driver.find_element_by_id('i0116').send_keys(k["email"])
    driver.find_element_by_id('i0118').send_keys(k["password"])
    driver.find_element_by_id('idSIButton9').click()
    delay()
    #sign in button
    driver.find_element_by_id('idSIButton9').click()
    #Button below I cant get to be clicked
    with webdriver.Chrome() as driver:
        wait = WebDriverWait(driver, 7)
        wait.until(presence_of_element_located((By.CSS_SELECTOR, "#ember1053")))
        driver.find_element(By.id, "ember1053").click()

this is the source code for the button that I am trying to make clickable:

<div id="ember1037" class="btn-group m-b-lg m-t-lg order-call-to-action ember-view"><!---->        <!--biBehavior 80 means place order Place Order-->

<button aria-live="polite" type="button" tabindex="0" data-m="{&quot;aN&quot;:&quot;shoppingCart&quot;,&quot;cN&quot;:&quot;PlaceOrder&quot;,&quot;bhvr&quot;:80}" id="ember1053" class="btn theme-default btn-primary cli-purchase ember-view"><!---->            Place order

</button></div>



How trigger a function inside component whenever arguments change in Emnber octane

so i have a parent in controller like this

import Controller from '@ember/controller';

export default class IndexController extends Controller {
@service firebaseApp;
@service fastboot;
@tracked user =false;

async init(){
 super.init(...arguments);
 if (!this.fastboot.isFastBoot){
  const auth =  await this.firebaseApp.auth();
  auth.onAuthStateChanged((user)=>{
     if(user){
       this.user = true
     } else {
       this.user = false
     }
      })
     }
   }

then call a component loadData like this <LoadData @user=/>

the question is how to execute a function inside component loadData when @user change?




vendredi 20 novembre 2020

is it possible to identify a value being changed by server in ember?

is there any attribute in the ember model which indicates the value being altered by the server?. I don't want to observe the value in that model as it will get triggered when the user changes also. so I was wondering if there is any attribute like isSaving, hasDirtyAttributes like that to indicate the value is changed by the server for a short moment of time like how isLoading and isLoaded in ember does.




jeudi 19 novembre 2020

ember hasDirtyAttributes do not work with object (json)

I have a model:

export default Model.extend({
  title: attr('string'),
  attributes: attr('jsonb')
});

Where attributes is a custom json filed stored as jsonb in Postgres.

let say:

{
"name":"Bob",
"city":""
}

So I can easily manipulate attributes using template
<form.element .. @property="attributes.city"/> or model.set('attributes.city','city name')

Problem: hasDirtyAttributes do not changing because technically we have old object. But when I try to copy object let say JSON.parse(JSON.stringify(this.get('attributes')) hasDirtyAttributes works as expected

So how to write some Mixin for a Model or other workaround which on the change of any attribute property will mark hasDirtyAttributes as true. I will update whole object so doesn't matter which property actually was changed.

Same problem: https://discuss.emberjs.com/t/hasdirtyattributes-do-not-work-with-nested-attributes-json-api/15592

existing solution doesn't work for me at all:

  • ember-dirtier
  • ember-data-relationship-tracker
  • ember-data-model-fragments (a lot of changes under the hood and broke my app)



Error: 'ReferenceError: pauseTest is not defined' in integration tests with moduleForComponent syntax

The pauseTest() function from ember-qunit does not work as expected in Integration tests with the old syntax

import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('my-component, 'Integration | Component | MyComponent', {
  integration: true
});

test('it renders', function(assert) {
  return pauseTest();
  this.render(hbs`/>`);
  ...
}

Failed:

Died on test #1     at Module.callback (http://localhost:4200/assets/tests.js:118959:24)
at Module.exports (http://localhost:4200/assets/vendor.js:111:32)
at requireModule (http://localhost:4200/assets/vendor.js:32:18)
at EmberExamQUnitTestLoader.<anonymous> (http://localhost:4200/assets/test-support.js:29031:11)
  at EmberExamQUnitTestLoader.require (http://localhost:4200/assets/test-support.js:29021:27)
at http://localhost:4200/assets/test-support.js:29545:90
  at Array.forEach (<anonymous>): pauseTest is not defined@ 698 ms
  Source:
  ReferenceError: pauseTest is not defined
  at Object.<anonymous> (http://localhost:4200/assets/tests.js:118960:5)
    at runTest (http://localhost:4200/assets/test-support.js:20889:30)
    at Test.run (http://localhost:4200/assets/test-support.js:20875:6)
    at http://localhost:4200/assets/test-support.js:21096:12
    at advanceTaskQueue (http://localhost:4200/assets/test-support.js:20488:6)
    at Object.advance (http://localhost:4200/assets/test-support.js:20469:4)
    at begin (http://localhost:4200/assets/test-support.js:22241:20)
    at http://localhost:4200/assets/test-support.js:21483:6

It's working fine in Acceptance tests, because of:

// ./tests/helpers/start-app.js
export default function startApp(attrs) {
  ...
    application.injectTestHelpers();
  ...
}

How to make it works in Integration tests?

Note: In modern syntax, it's working fine too:

import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';

module('Integration | Component | MyComponent', function(hooks) {
  test('it renders', async function(assert) {
    return this.pauseTest();
    await render(hbs`/>`);
  });
}



Ember The Resource from 'path' was blocked due to MIME type error with blank screen

I'm working on an Ember application with a .NET backend. In building the ember app, it complies into the proper directory. My directory structure looks like below:

myProjectRoot
   |
   |-> NETProject
   |       |
   |        -> Compiled-Ember 
   |
    -> Ember project

I currently have it running as an IIS application pointing to NETProject, though if I run via ember serve I get the same results. All the IIS config is proper and works. The issue is trying to load the page I get the following errors, one for each vender.css, vendor.js, projectName.js, and projectName.css:

The resource from “http://localhost/404.aspx?404origin=%2fcompiled-ember%2fassets%2fprojectName.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff)

The title and favicon load, but the rest of the page is blank. It should be noted that the app will redirect to a 404 page upon not finding the requested URL.

Now the resources do exist where they are supposed to, the project builds without issue and all compiled files exist in compiled-ember. Now I have seen that this is a common issue with the path, I have messed with the path in the compiled index.html file (which is where it sources from as changing the path here changes the error to match). I've gotten no other results, than the error above. Here is the index.html file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>ProjectName</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="icon" type="image/x-icon" href="https://hostedimagelocation.com">
    <base href="/" />

    
<meta name="projectName/config/environment" />
    <link integrity="" rel="stylesheet" href="/compiled-ember/assets/projectName.css">

    
</head>
<body>


<script src="/compiled-ember/assets/vendor.js"></script>
<script src="/compiled-ember/assets/projectName.js"></script>


</body>
</html>

The index.html file is located directly in compiled-ember. I have tried switching the paths to be like assets/vendor.js and others to no avail. Any help to solving this error would be very helpful. Thank you




After bump ember-data from 2.13 to 2.14 the request payload not contain hasMany relations when the relation model had empty relation

with ActiveModelSerializer usage after the ember-data upgrade, the values of has_many case on the request payload had changed when the model has no records by relation, for example:

// app/models/user.js
import Model from 'ember-data/model';
import { hasMany } from 'ember-data/relationships';

export default Model.extend(Validations, {
  posts: hasMany('post'),
...
}
// app/models/post.js
import Model from 'ember-data/model';
import { belongsTo } from 'ember-data/relationships';

export default Model.extend(Validations, {
  user: belongsTo('user'),
...
}

so, if User has no posts, previously was sent [] into BE, but after ember-data bump to 2.14.11 no key-values sent, for example: (request payload)

Before:

user: { id: 1, post_ids: [] }

After:

user: { id: 1 }

Note:

"active-model-adapter": "2.2.0"
"ember-data": "2.14.11"



Is it necessary to migrate from ember-data/active-model-adapter to DS.JSONAPISerializer for ember 3?

Documentation for DS.ActiveModelAdapter is exists only for 1.13 (for 2 - 404: https://api.emberjs.com/ember-data/1.13/classes/DS.ActiveModelAdapter So, it looks like it's moved out from DS: https://github.com/ember-data/active-model-adapter

We have ember-data 2.13.2 and it's working fine with active-model-adapter But we got some issues with the bump to ember-data 2.14.11 with nested behavior

The big issue here is to rewrite the backend part. We also may use RESTAdapter: https://www.emberscreencasts.com/posts/113-restadapter-vs-jsonapiadapter-vs-activemodeladapter but it looks like ember way is JSONAPIAdapter way: https://api.emberjs.com/ember-data/release/classes/JSONAPIAdapter

So, generally, the question is: what way is better for ember-upgrade?

  • keep backend API and maintain active-model-adapter
  • rewrite backend API and migrate to JSONAPIAdapter (with data/relationships approach)
  • rewrite backend API and migrate to RESTAdapter
  • keep backend API and implement custom serializer to change on the fly input/output to use JSONAPIAdapter or RESTAdapter (pick best) logic on FE (maybe it's some crazy way, but it's just to ask)

Note: backend API on RubyOnRails




Command like "ember s" gets stuck and not loading

I’ve been following Getting started https://guides.emberjs.com/release/getting-started/quick-start/.

I did:

npm install -g ember-cli ember new ember-quickstart cd ember-quickstart ember serve

After ember serve or server or ember s It just keeps loading and never load server.

Thank you for your help.




mercredi 18 novembre 2020

How do I update data in the service store in Ember?

I created a service where I declared the store:

store.js:

import Service from '@ember/service';

export default class StoreService extends Service {
  store = {
    lang: 'EN'
  }
}

I also got access to the store from the route:

first.js:

import Route from '@ember/routing/route';
import { inject } from '@ember/service';

export default Route.extend({
  store: inject(),
  model() {
    console.log(this.store);
    return this.store;
  }
});

And the template. first.hbs:

<div class="wrapper">
  <h3>First</h3>
  <hr class="gold">
  <p><button type="button">CN</button></p>
  
</div>


Please tell me how you can change the data in the storage from the route by pressing the "CN" button?

Regards.




Unwanted two-way data binding when passing data to Ember Octane component

I'm following the Full Stack Ember with Rails course on Embercasts. As they don't use Octane yet, I change the code where necessary to work with Ember 3.22. I'm stuck in video 22 where I need to pass data to a component. This data should only be passed to the component, but when updating a value inside it, I don't want to see the change in other places.

In the video, this is taken care of in a didReceiveAttrs() handler, but this is not available in Octane. Instead, the Ember docs describe one way data flow as what happens automatically. In my case, it doesn't:



<h3>Editing: ,  </h3>
<AuthorForm @autor= />



<div class="field">
  <label for="first">First name</label>
  <Input @id="first" type="text" placeholder="First name" @value=/>
</div>  

<div class="field">
  <label for="last">Last name</label>
  <Input @id="last" type="text" placeholder="Last name" @value=/>
</div>

The h3 updates whenever I change the value in one of the component's inputs. What's wrong here?




Not able to bind data in posts.hbs

templates/posts.hbs

<h2>Posts</h2>
    
      <div>
        <h3></h3>
        <h3></h3>
        <h3></h3>
        <h4></h4>
      </div>
    
    

serializers/posts.js

import DS from 'ember-data';

export default DS.JSONAPISerializer.extend({
  normalizeResponse(store, primaryModelClass, payload, id, requestType){
    console.log(payload); //in console getting data here properly
    return this._super(store, primaryModelClass, payload, id, requestType);
  }
});

routes/posts.js

import Ember from 'ember';

export default Ember.Route.extend({
  model(){
    return this.store.findAll('post');
  }
});

Getting data from backend API point and printing data in console properly. Everything fine. But not binding in handlebars (posts.hbs). Can someone help me with this? New to ember Js.




mardi 17 novembre 2020

ember install ember-modifier-manager-polyfill ERROR: RangeError: Maximum call stack size exceeded

After install addon: ember install ember-modifier-manager-polyfill Got failed testing suite on CI only (if run each particular test alone locally - test passed)

Here is the issue in status open about it: https://github.com/ember-polyfills/ember-angle-bracket-invocation-polyfill/issues/110 but in my case I have no similar case in templates:


  

So, it's something different... coz the failed are different tests (Integration/Acceptance) in different parts of the system

Notes:

ember-source: 2.14.1
ember-angle-bracket-invocation-polyfill: 2.0.2
jquery: 3.5.1
ember-modifier-manager-polyfill: 1.2.0

it's not a duplicate of this: What could be reason of the error 'Maximum call stack size exceeded' inside Ember Data? or this: Ember Uncaught RangeError: Maximum call stack size exceeded but the error with the same message

Output example:

stack: >
                at DOMAssertions.exists (http://0.0.0.0:4200/assets/test-support.js:24416:16)
                at DOMAssertions.exists (http://0.0.0.0:4200/assets/test-support.js:24737:18)
                at Object._callee$ (http://0.0.0.0:4200/assets/tests.js:141899:45)
                at tryCatch (http://0.0.0.0:4200/assets/vendor.js:6235:40)
                at Generator.invoke [as _invoke] (http://0.0.0.0:4200/assets/vendor.js:6509:22)
                at Generator.prototype.<computed> [as next] (http://0.0.0.0:4200/assets/vendor.js:6268:21)


browser log: |
            ERROR: RangeError: Maximum call stack size exceeded
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72303:51)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)

Appreciate any help




Is it possible to access sessionStorage from handlebars?

<h4 id="logout_button" >Logout Sign Up Login

above code throwing error




lundi 16 novembre 2020

EmberJS testing: target id created from each loop

I used an each loop to create a unique id for every input that's created. Ex: id='amount0', id='amount1', etc.. but I can't target them during testing, it says the element is not found.

Error

Promise rejected during "Amount input works": Element not found when calling `fillIn('#amount0')`.

HBS file:


<p output-test-info>
    <button onclick=>-</button>
    
    <input id="amount" onchange=>
</p>

Test file:

test('Amount input works', async function(assert){
    const itemList = document.queryCommandValue('output-test-info');
    this.set('tempName', [{name: 'bobby'}, {name: 'peter'}]);
    this.set('tempAct', [{activity: 'dinner'}, {activity: 'movies'}])
    await render(hbs`<Output @userinfo= @userAct=/>`);

    await fillIn('#amount0', '20');
  })



dimanche 15 novembre 2020

While starting ember server I'm getting this error like SyntaxError: Unexpected identifier async postBuild()

While starting ember server I'm getting this error What could be the reason for this error?

Unexpected identifier
/Users/chraju/Desktop/sites/blog-front-end/node_modules/ember-cli-typescript/js/addon.js:47
    async postBuild() {
          ^^^^^^^^^

SyntaxError: Unexpected identifier
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:549:28)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/chraju/Desktop/sites/blog-front-end/node_modules/ember-cli-typescript/index.js:9:20)






mercredi 11 novembre 2020

Get the value of an Ember Component in the controller

Lets say I have a custom component called X.

<X>my value</X>

I now want to access the "my value" in the controller of X. How can I do that?




mardi 10 novembre 2020

How to setup JsonApiSerializer as default input and output seriliazers C# .NET Core 3+

I've been trying to setup JsonApiSerializer (https://github.com/codecutout/JsonApiSerializer) as the default serializer for both input and output so I can have an json:api compliant .NET server for an Ember application with Ember Data.

I have succesfully setup the output serializer by writing the following code to the Startup.cs file:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext<Context>(options => options.UseSqlServer(Configuration.GetConnectionString("myDb")));

            var sp = services.BuildServiceProvider();
            var logger = sp.GetService<ILoggerFactory>();
            var objectPoolProvider = sp.GetService<ObjectPoolProvider>();

            services.AddMvc(opt =>
            {
                var serializerSettings = new JsonApiSerializerSettings();
**
                var jsonApiFormatter = new NewtonsoftJsonOutputFormatter(serializerSettings, ArrayPool<Char>.Shared, opt);
                opt.OutputFormatters.RemoveType<NewtonsoftJsonOutputFormatter>();
                opt.OutputFormatters.Insert(0, jsonApiFormatter);
**
                var mvcNewtonsoftSettings = new MvcNewtonsoftJsonOptions();

                var jsonApiInputFormatter = new NewtonsoftJsonInputFormatter(logger.CreateLogger<NewtonsoftJsonInputFormatter>(), serializerSettings, ArrayPool<Char>.Shared, objectPoolProvider, opt, mvcNewtonsoftSettings);
                opt.InputFormatters.RemoveType<NewtonsoftJsonInputFormatter>();
                opt.InputFormatters.Insert(0, jsonApiInputFormatter);
                //opt.InputFormatters.OfType<NewtonsoftJsonInputFormatter>().FirstOrDefault().SupportedMediaTypes.Add("application/vnd.api+json");

            }).AddNewtonsoftJson();
        }

But the Input part isn't working yet!

I've been triyng to receive code from a Ember application that follows this structure:

{
  "data": 
  {
    "type": "manufacturer",
    "name": "Fabricante 1",
    "relationships": {
      "products": {
        "data": [
          {
            "type": "product",
            "id": "1"
          },
          {
            "type": "product",
            "id": "2"
          }
        ]
      }
    }
  }
}

The binding model of the .NET server for POSTing a manufacturer is like this:

public class CreateManufacturerBindingModel
    {
        public string Type { get; set; } = "manufacturer";
        public string Name { get; set; }
        public AssignProductBidingModel[] Products { get; set; }
    }

public class AssignProductBidingModel
    {
        public string Type { get; set; } = "product";
        public int Id { get; set; }
    }

I've been trying out some variations of those codes for a while and all I can get is Null values for "Name" and "Products" attributes of the CreateManufacturerBindingModel

Does anyone has any clue of why I keep on getting null values at the .NET server?

Thank you for your attention!




jeudi 5 novembre 2020

Yield not stopping the flow in ember concurrency task

if (isEmpty(contact) || isEmpty(get(contact, 'emails'))) {
  contact = yield store.findRecord('contact', contactId);
}

if (isEmpty(contact) || isEmpty(get(contact, 'emails'))) {
  flashMessages.danger(i18n.t('email.cpq_document_email_missing'));
  return false;
}

The second block runs when the promise is running and Im getting an error. Shouldn't it stop the flow until the promise is resolved.

The promise runs fine and it works the next time




Facing issue after update ember from 3.0.0 to 3.22.0

After updating ember from 3.0.0 to 3.22.0 using ember-cli-update and install npm packges. And finally hit ember s it throws the bellow error.

Build Error (SourceMapConcat)
ENOENT: no such file or directory, open '/var/folders/wm/w121z2bs7yngf13gc_qbsn_w0000gn/T/broccoli-51053YM0PSytfuMoE/out-881-broccoli_debug_debug_5_vendor_js/vendor/simple-module/lib/module.js'

Stack Trace and Error Report: /var/folders/wm/w121z2bs7yngf13gc_qbsn_w0000gn/T/error.dump.a86e097d39858aa6e4eacea11b04401c.log

Here is the full log file

ERROR Summary:

  - broccoliBuilderErrorStack: Error: ENOENT: no such file or directory, open '/var/folders/wm/w121z2bs7yngf13gc_qbsn_w0000gn/T/broccoli-51053YM0PSytfuMoE/out-881-broccoli_debug_debug_5_vendor_js/vendor/simple-module/lib/module.js'
    at Object.openSync (fs.js:439:3)
    at Object.readFileSync (fs.js:344:35)
    at FSMerger.handleOperation (/Applications/MAMP/htdocs/pm-client/node_modules/fs-merger/dist/index.js:82:32)
    at SourceMap.addFile (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/node_modules/fast-sourcemap-concat/lib/source-map.js:78:38)
    at headerFiles.forEach.file (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/concat.js:203:18)
    at Array.forEach (<anonymous>)
    at Concat.concat.end.concat (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/concat.js:201:26)
    at /Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/node_modules/fast-sourcemap-concat/lib/source-map.js:432:14
    at new Promise (<anonymous>)
    at SourceMap.end (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/node_modules/fast-sourcemap-concat/lib/source-map.js:419:12)
  - code: [undefined]
  - codeFrame: ENOENT: no such file or directory, open '/var/folders/wm/w121z2bs7yngf13gc_qbsn_w0000gn/T/broccoli-51053YM0PSytfuMoE/out-881-broccoli_debug_debug_5_vendor_js/vendor/simple-module/lib/module.js'
  - errorMessage: ENOENT: no such file or directory, open '/var/folders/wm/w121z2bs7yngf13gc_qbsn_w0000gn/T/broccoli-51053YM0PSytfuMoE/out-881-broccoli_debug_debug_5_vendor_js/vendor/simple-module/lib/module.js'
        at SourceMapConcat (Package /assets/vendor.js)
-~- created here: -~-
    at new Plugin (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/node_modules/broccoli-plugin/dist/index.js:45:33)
    at new Concat (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/concat.js:28:5)
    at module.exports (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/index.js:28:10)
    at importPaths.map (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/default-packager.js:1312:14)
    at Array.map (<anonymous>)
    at DefaultPackager.packageVendorJs (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/default-packager.js:1306:35)
    at DefaultPackager.packageJavascript (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/default-packager.js:1182:27)
    at EmberApp._legacyPackage (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/ember-app.js:1613:48)
    at EmberApp.toTree (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/ember-app.js:1659:27)
    at module.exports (/Applications/MAMP/htdocs/pm-client/ember-cli-build.js:30:14)
-~- (end) -~-
  - errorType: Build Error
  - location:
    - column: [undefined]
    - file: [undefined]
    - line: [undefined]
    - treeDir: [undefined]
  - message: ENOENT: no such file or directory, open '/var/folders/wm/w121z2bs7yngf13gc_qbsn_w0000gn/T/broccoli-51053YM0PSytfuMoE/out-881-broccoli_debug_debug_5_vendor_js/vendor/simple-module/lib/module.js'
        at SourceMapConcat (Package /assets/vendor.js)
-~- created here: -~-
    at new Plugin (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/node_modules/broccoli-plugin/dist/index.js:45:33)
    at new Concat (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/concat.js:28:5)
    at module.exports (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/index.js:28:10)
    at importPaths.map (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/default-packager.js:1312:14)
    at Array.map (<anonymous>)
    at DefaultPackager.packageVendorJs (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/default-packager.js:1306:35)
    at DefaultPackager.packageJavascript (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/default-packager.js:1182:27)
    at EmberApp._legacyPackage (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/ember-app.js:1613:48)
    at EmberApp.toTree (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/ember-app.js:1659:27)
    at module.exports (/Applications/MAMP/htdocs/pm-client/ember-cli-build.js:30:14)
-~- (end) -~-
  - name: Error
  - nodeAnnotation: Package /assets/vendor.js
  - nodeName: SourceMapConcat
  - originalErrorMessage: ENOENT: no such file or directory, open '/var/folders/wm/w121z2bs7yngf13gc_qbsn_w0000gn/T/broccoli-51053YM0PSytfuMoE/out-881-broccoli_debug_debug_5_vendor_js/vendor/simple-module/lib/module.js'
  - stack: Error: ENOENT: no such file or directory, open '/var/folders/wm/w121z2bs7yngf13gc_qbsn_w0000gn/T/broccoli-51053YM0PSytfuMoE/out-881-broccoli_debug_debug_5_vendor_js/vendor/simple-module/lib/module.js'
    at Object.openSync (fs.js:439:3)
    at Object.readFileSync (fs.js:344:35)
    at FSMerger.handleOperation (/Applications/MAMP/htdocs/pm-client/node_modules/fs-merger/dist/index.js:82:32)
    at SourceMap.addFile (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/node_modules/fast-sourcemap-concat/lib/source-map.js:78:38)
    at headerFiles.forEach.file (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/concat.js:203:18)
    at Array.forEach (<anonymous>)
    at Concat.concat.end.concat (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/concat.js:201:26)
    at /Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/node_modules/fast-sourcemap-concat/lib/source-map.js:432:14
    at new Promise (<anonymous>)
    at SourceMap.end (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/node_modules/fast-sourcemap-concat/lib/source-map.js:419:12)

=================================================================================

Can anyone give me an answer why this is happening and how should I resolve this?




mardi 3 novembre 2020

Get current route name from corresponding loading route in ember

As per ember document If any model hook in routes taking time to fetch data from server, ember will insert loading route. for example test-loading, at that time if we try to get current route name like this, it returns only the loading route. for example if sample route is getting too much of time to load, ember will transition into sample-loading until sample route resolved. Then again it will change to sample route. So at the time of sample-loading getCurrentRoute is returns the sample-loading. In my case I need to know the actual route name which is changed into -loading. I can't find any documentation in internet for doing this. If anyone know the way or idea to implement kindly share with me..




lundi 2 novembre 2020

ember-qunit-notifications bower package is not working for node version 6.9.2, but working for latest node versions

When I try to execute some bower packages in my laptop (hp- Intel(R) Core(TM) i7-1065G7 - 10th gen) for older node versions(6.9.2) it shows SSL certification error like in this image. and not with the latest versions(14.15.0). But this issue is not related to other computers and works all bower packages with any node versions. enter image description here




Is there any way to listen to eventbus from an ember-modal dialog?

The scenario is to listen to an eventbus notification when the ember modal is open, refresh the route page while closing the modal, as i am not able to subscribe to the event from ember modal, unable to do the conditional refresh.




vendredi 30 octobre 2020

Ember Octane (3.22+) why use instead of onclick=

So in Ember Octane there are two ways of attaching a function to an event in an hbs file.

The EmberJS way:

Classic HTML way: onclick=

Here they suggest using the prior syntax

However I don't see a reason why to use that syntax unless we have due reason to do so.

What are the reasons I would use the former over the latter?




jeudi 29 octobre 2020

How do you disable tooltips in ember-cli-chart?

I am using ember-cli-chart which is a wrapper for chart js. I am trying to disable the tooltips.

I have tried the following code but it does nothing:

chartData: computed('model', function() {
    return {
      labels: ['1', '2'],
      datasets: [{
          label: 'Example Label',
          data: [this.model.example1, this.model.example2],
          options: {
            tooltips: {
              enabled: false,
            }
          }
      }]
    }
  }),

Why does this not disable the tooltips?




Deploying Ember.js app to AWS Elastic Beanstalk

I have tried and search how I and deploy emberjs app on AWS Elastic Beanstalk but I can not find a way. I am using EB CLI for deployment and configuration.

If anyone has an experience in deployment of ember app to Elastic Beanstalk please share.




mercredi 28 octobre 2020

Ember.js - extending a Bootstrap plugin's function

I am trying to extend the hide method of the Bootstrap modal plugin. I have many modals throughout the application and I would like to have a blanket solution to close the modal when a user hits the browser back button (instead of having to add the function to each modal instance in the application)

I know in Ember JS, you can override a component by importing it, calling the super method and adding your own customization. How can I do this with a Bootstrap modal plugin? I am not familiar with how to import the node_modules file in this scenario.

Essentially, what I want to do is this as a solution for all modals in the application:

 $(window).on('popstate', function() {
   $('.modal').modal('hide');
 });



lundi 26 octobre 2020

Appending a DOM element in Ember Octane

I am currently converting some code from older Ember style to Ember Octane, so I'm a bit new to Octane. At the heart of the problem, I'd like to use this.element.appendChild to append a div when the element is inserted, and then select and append an SVG to the div and modify it from there. However, Ember Octane doesn't allow for lifecycle hooks. What's the best way to do this?

For some more detail, this component utilizes D3 to render a graph, so it initializes the setup for the graph by creating a div with the id svg and then selects it and appends an SVG to it, and continues to do D3 stuff to it to render a graph.

I've looked into ember-render-modifiers, but this seems like a bit of a workaround and a copout from refactoring the code, so I was wondering if there was a better way than this.




from `Ember Serve`, how to run lint on each new build

I encountered this problem while upgrading from Ember 3.12 to Ember 3.20. Originally, whenever ember serve was running, any changes to the code would also trigger the linting scripts to re-run. I've looked at some Ember pull requests and it seems some of the linting libraries were swapped which may have had an adverse side-effect of not causing the linting tool to run on either ember serve, or ember test. Instead, linting must be called manually through the command line. This is the PR that I think maybe related to this side-effect.

https://github.com/ember-cli/ember-cli/pull/9009

Is there a way to work around this? To be clear, I want the linters to ideally run with ember serve rather than as a separate command. It's not a huge deal to me, but it is a little inconvenient to have to manually run linting now.




jeudi 22 octobre 2020

How can i run Ember test using node-webkit in an docker container

I have created an ember application and i am running that application on node-webkit. In my application i have used node objects also like process object. So when i am trying to run my ember test "ember test --server --module='Unit | Route | application'" it runs the test in chrome which gives error that process is not defined. And when i open http://localhost:7375/ in node-webkit it works fine. So how can i run my ember test case in a headless node-webkit. I mean i have to run my ember test in an docker container, so how can i achieve this by using node-webkit and get the test report.

And is there any way we can provide nw option in testem.js file

module.exports = {
 test_page: 'tests/index.html?hidepassed',
 disable_watching: true,
 launch_in_ci: [
  'Chrome'
 ],
 launch_in_dev: [
    'Chrome'
 ],
 browser_args: {
 Chrome: {
 ci: [
   // --no-sandbox is needed when running Chrome inside a container
   process.env.CI ? '--no-sandbox' : null,
   '--headless',
   '--disable-dev-shm-usage',
   '--disable-software-rasterizer',
   '--mute-audio',
   '--remote-debugging-port=0',
   '--window-size=1440,900'
 ].filter(Boolean)
 }
}   };



mp4 not playing on any browser on iOS only

I have a video section in my ember application using the following component

<video class="className" >
    <source = type="video/mp4" >
</video>

This video works in any desktop browser, and on Android. However on iOS (any browser) it doesn't load at all, just leaving a blank, white container.

I'm familiar with iOS videos needing the network response as a 206 code, and that has already been taken care of.

Are there any other weird things with iOS browser video that I'm missing or need to include?




ember-composable-helpers checkbox not checking

I'm using composable helpers in Ember. When I click the parent checkbox, all of the children checkboxes check and uncheck, but the parent never shows a checkmark. What am I missing here?

Parent: <input type="checkbox" checked= >

Children: <input type="checkbox" checked=>




mercredi 21 octobre 2020

How to fix Broccoli Builder ran into an error with `UglifyWriter` plugin in Ember application

I am using ember framework for my frontend application, It wors fine till last week now when I tried to build the application getting below issue,

Build failed.
Build Canceled: Broccoli Builder ran into an error with `UglifyWriter` plugin. 💥
SyntaxError: Unexpected token: name (v)
Error
    at new JS_Parse_Error (eval at <anonymous> (/Users/vad/dev/book-frontend/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:1545:18)
    at js_error (eval at <anonymous> (/Users/vad/dev/book-frontend/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:1553:11)
    at croak (eval at <anonymous> (/Users/vad/dev/book-frontend/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2092:9)
    at token_error (eval at <anonymous> (/Users/vad/dev/book-frontend/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2100:9)
    at unexpected (eval at <anonymous> (/Users/vad/dev/content-frontend/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2106:9)

Please find the below package.json for your reference

{
  "name": "book-content",
  "version": "0.0.0",
  "description": "Book management platform",
  "private": true,
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "build": "ember build",
    "start": "ember server",
    "test": "ember test"
  },
  "repository": "",
  "engines": {
    "node": ">= 0.10.0"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "broccoli-asset-rev": "^2.2.0",
    "broccoli-funnel": "^1.0.2",
    "broccoli-merge-trees": "^1.1.1",
    "bson": "^4.0.4",
    "ember-ajax": "0.7.1",
    "ember-aupac-typeahead": "3.1.0",
    "ember-browserify": "^1.2.2",
    "ember-can": "^0.8.1",
    "ember-cli": "2.13.0",
    "ember-cli-app-version": "^1.0.0",
    "ember-cli-autocomplete-input": "1.1.0",
    "ember-cli-babel": "^5.1.5",
    "ember-cli-dependency-checker": "^1.2.0",
    "ember-cli-htmlbars": "^1.0.1",
    "ember-cli-htmlbars-inline-precompile": "^0.3.1",
    "ember-cli-inject-live-reload": "^1.3.1",
    "ember-cli-moment-shim": "^3.7.1",
    "ember-cli-pace": "0.1.0",
    "ember-cli-pagination": "2.2.2",
    "ember-cli-qunit": "^1.2.1",
    "ember-cli-release": "0.2.8",
    "ember-cli-sass": "^7.1.7",
    "ember-cli-sri": "^2.1.0",
    "ember-cli-uglify": "^1.2.0",
    "ember-composable-helpers": "2.1.0",
    "ember-concurrency": "0.8.21",
    "ember-data": "2.7.0",
    "ember-disable-proxy-controllers": "^1.0.1",
    "ember-export-application-global": "^1.0.4",
    "ember-get-helper": "1.1.0",
    "ember-load-initializers": "^0.5.0",
    "ember-lodash": "4.17.1",
    "ember-moment": "^7.8.0",
    "ember-plupload": "1.13.18",
    "ember-power-select-typeahead": "0.7.1",
    "ember-query-params-reset": "2.0.0",
    "ember-resolver": "^2.0.3",
    "ember-rl-month-picker": "^0.2.0",
    "ember-rl-year-picker": "^0.2.0",
    "ember-slide-push-menu": "1.0.0",
    "ember-truth-helpers": "1.2.0",
    "ember-uploader": "1.0.0",
    "ember-validations": "v2.0.0-alpha.5",
    "express": "^4.13.4",
    "glob": "^4.5.3",
    "loader.js": "^4.0.0",
    "morgan": "^1.7.0",
    "uglify-js": "2.7.1"
  },
  "dependencies": {
    "minimist": "^1.2.0"
  }
}

I see some of the dependencies pulled the latest version of uglify:3.11.3 which could cause an issue but I don't know how to instruct them to use version 2.7.0 or the one which is not causing an issue. I don't know how to override nested dependency.

Could anyone please guide me to fix the issue?




vendredi 16 octobre 2020

How to use ember-maybe-in-element addon?

I have a scenario where I want to append child component say child-component to a different component dynamically. example - I want to achieve

<div class="container">
  <div class="content">
    <child-component></child-component>
   </div>
</div>

I am using document.querySelector('.container .content').appendChild('this.element.querySelector('[data-child-content]')) in child-component.js file.

I want to use https://github.com/DockYard/ember-maybe-in-element addon to achieve this appendChild. Any suggestions on how to achieve this in the above scenario?




What is the difference between let todos = this.args; and let { todos } = this.args; in JavaScript? [duplicate]

I am learning Ember.js. I was working on a component class

Here my code:

import Component from '@glimmer/component';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
import { tracked } from '@glimmer/tracking'

export default class TodoListComponent extends Component {
  @service todoData;

  @tracked canToggle = true;

  get areAllComplete() {
    let  **{todos}**  = this.args;
    
    return todos.every(todo => {
      return todo.isCompleted;
    });
  }
} 

Can anyone tell me What is the difference between let todos = this.args; and let { todos } = this.args; in JavaScript ?




Access DOM inside iFrame using Javascript

I am trying to access a DOM element from my main page and want to update the CSS. I use the following;

var myIframeContainerEl = $('#myIframeContainerEl');
myIframeContainerEl.contents().find(".required").css("color", "#f0f0f0");

This is not working for some reason. While it is able to find "myIframeContainerEl", for some reasons, "myIframeContainerEl.contents()" shows a length of 0. Is the above not the correct way of doing it?

Also, just to add, I am using this in my Ember project and use it within didTransition hook and inside "afterRender" So the element is present when I am trying to access.




jeudi 15 octobre 2020

How to pass data from action in controller, to the handlebar template in Ember

My application.js controller has @actions for sending POST requests, and I want to take the json payload response from one of these actions, and use that json payload in my .hbs file called application.hbs.

@action async myFunctionn() {
    let response = await fetch(url, {
        method: 'POST',
        headers:{'Content-Type':'application/vnd.api+json'},
    },
    body:JSON.stringify(payload)});

    let json = await response.json();
    return;


}

How can I most simply do this.




How to create global variable in Ember Controller

I have my applicationController where I have the following

@action getTable(){
//code to get info when button is pressed
}

@action getRequest(){
    //logic
    let my-expression = aria + bob;
}

I want to capture the my-expression variable so that I can use it in another action decorated function. How can I do that in the most simplest way, in the same controller?




How to set custom response json in ember-data when dealing with errors

I'm using now:

  • ember: 3.8.1
  • ember-data: 3.10.0

I'm trying to send an error response from Grails API with some additional data. It looks something like this:

respond(
    status: HttpStatus.UNPROCESSABLE_ENTITY, 
    errors: errors
    additionalData: someMap
)

On the frontend side with Ember I'm trying to catch it with:

object.save().then(function () {
    // (...)
}).catch((response) => {
    // Here I want to access "response.additionalData"
    // (...)
});

Now, I know that ember-data has it's own way to handle and bind errors response (https://davidtang.io/2016/01/09/handling-errors-with-ember-data.html) but in ember-data: 2.10.0 I was able to catch and handle errors with additional data in catch with response.additionalData.

In version I'm using response.additionalData is always undefined and I can't get it in any way. It's coming from backend because I can see it in browser dev tools in response.

How can I achieve this in newest ember-data? I did try to write adapter and override handleResponse function but even my own CustomErrorClass still was like native one.

Any help would be appreciated. Thanks in advance!