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.