mercredi 29 novembre 2023

unshiftObject method is not working in ember

I have the array of Objects and want to concat only the list property of all objects and create a new array. So I have a "combinedList" getter in the below code to combine the list if array length is greater than 1 else just return the 1st items list property. This returned array will be used in the template file to display. If any new item is added, the addComment function will be called with the newly added item and push that to the "combinedList" array.

The problem here is, if the objArr length is less than 1, the newItem is pushed to the "combineList". But, if it is greater than 1, newItem is not pushed to the "combinedList" array.

Can anyone please help me to figure out the cause for this issue?

export default class YourComponent extends Component {
  objArr = [ {id:1, list:[1,2,3]}, {id:2, list:[3,4]} ];

  get combinedList() {
    if (this.objArr.length > 1) {
      let list = [];
      this.objArr.forEach((item) => {
        list.push(...item.list);
      });
      return list;
    }
    return this.objArr[0].list;
  }

  // Call this method when adding a new item
  addComment(newItem) {
    this.combinedList.unshiftObject(newItem);
  }
}



lundi 27 novembre 2023

Ember 4.x (Octane) - replacement for Observers?

I am nearly done upgrading a very old Ember.js project from 2.13 all the way up to the latest LTS release, 4.12. Along the way I've been coming to grips with the changes that the Octane release brought about, and one area I'm struggling to adapt is our use of observers.

We use observers in two files to fire function calls when an observed value changes. I understand that Observers are discouraged in Octane, so if possible I'd like to migrate away from them.

My understanding is that tracked properties are the end-all be-all now; they're largely meant to replace computed properties, and I assume other state-based functions like observers, but I'm not really sure how to apply them in this use case, or if it's even possible.

My question is: Is there a preferred replacement for Observers in Ember Octane (4.x+)?




dimanche 19 novembre 2023

Ember JS Reserved Attribute/model names

TLDR: will naming a model/relationship "type-info" work?

I'm trying to use an included relationship in ember that's named "type" in my backend. I realize that's probably a reserved keyword in ember so I named it type-info in my ember app. I can see the model in the store inspector but I can't access it as a property of other models.

This is the relationship if that helps at all:

  @belongsTo('type-info', { async: false })
    declare typeInfo: TypeInfoModel;

I tried renaming the model to "denomination-type" which didn't work and then just "denomination" which worked. Am I missing something here or should I just find a different name? I would rename it to avoid whatever issue is going on but I think "type should be in the name in some way.




jeudi 16 novembre 2023

ember js - service usage to show data

I am new to ember js and trying to write my first app...

I have :

service app/service/event_handler.js

import Service from '@ember/service';

export default class EventHandlerService extends Service {

    eventList = [
        {
            EventName: 'test event 1',
            EventDesc: 'test event 1 desc',
            StartDate: '16.11.2023',
            EndDate: '05.02.2024',
            EventType_ID: 1,
        },
        {
            EventName: 'test event 2',
            EventDesc: 'test event 2 desc',
            StartDate: '17.11.2023',
            EndDate: '15.02.2024',
            EventType_ID: 2,
        },
        {
            EventName: 'test event 3',
            EventDesc: 'test event 3 desc',
            StartDate: '13.10.2023',
            EndDate: '01.01.2024',
            EventType_ID: 1,
        }
    ];
}

controller app/controllers/event-controller.js

import Controller from '@ember/controller';
import { getOwner } from '@ember/application';
import { service } from '@ember/service';
export default class EventControllerController extends Controller {
    // @service eventHandler;

    get events() {
        console.log("loading events");
        return getOwner(this).lookup('service:event-handler')
    }
}

and my hbs file that has a code block

<table>
                <thead>
                    <tr>
                        <th>Event name</th>
                        <th>Event Date Start</th>
                        <th>Event Date End</th>
                    </tr>
                </thead>
                <tbody>

                    
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr>
                    
                </tbody>
            </table>

the table is empty and i dont know what am i doing wrong :c I tried looking some tutorials and asking ai but I am still having issues...




mercredi 15 novembre 2023

How to transfer an object to an component in ember.js

Ember.js is completely new to me. (Current version 5.4)
I would like to build a small WebUI. The login and the menu navigation work great. But I have problems with the loop and visualizing information from the single loop in the component.

I have a "main-axis" component. I make an each loop in this template. Now I want to install a component in each loop and enter various information from the object in the template of this component. Titles, values etc.

main-axis.hbs

<div class="row">
 
    <div class="col-12 col-lg-6">
      <LinearAxis />
    </div>
 
</div>

main-axis.js

import Component from "@glimmer/component";

export default class MainAxis extends Component {
  exampleArray = [
        {title: 'foo', id:7},
        {title: 'bar', id:42}
    ];
}

example template "linear-axis.hbs"

<div class="card">
  <div class="card-header">
    Axis 
  </div>
  <div class="card-body">
    <p class="card-text">Number: </p>
    <button type="button" class="btn btn-primary btn-sm">Click</button>
  </div>
</div>

the empty js class inside app/components "linear-axis.js

import Component from '@glimmer/component';

export default class LinearAxis extends Component {
// how i get informations from the loop and provide them into the individual template instance
}

I have spent a lot of time with the documentation of Ember.js and am not really getting any further.




lundi 6 novembre 2023

Hot to scroll to window-top on route load in Emberjs 5.4

In Ember 5.4, when a new route is loaded, and the last view was scrolled, the scroll position remains. I want it to scroll to top of the window instantly if the url/route changed.

I made it work with this code in app/routes/application.js:

import Route from '@ember/routing/route';
import { action } from '@ember/object';

export default class ApplicationRoute extends Route {
    @action
    didTransition() {
        setTimeout (() => window.scrollTo ({top: 0, left: 0, behavior: 'instant'}), 1);
    }
}

But using setTimeout with 1 millisecond seems bad style and maybe error-prone to me. Nevertheless just using window.scrollTo ({top: 0, left: 0, behavior: 'instant'}) without timeout does not work, it does not scroll the window to the top.

So I think I maybe am using the wrong event(/action), but I cant find a better one in the docs (e.g. here: https://api.emberjs.com/ember/5.4/classes/Route).

This problem is already addressed in some other stackoverflow-questions (e.g. here: Emberjs scroll to top when changing view) but for older versions of ember or an other style of defining the route - where, to be honest, I'm not sure what exactly in applicable, because I am new to ember and was not able to find my way through the jungle of versions and deprecations docs and different styles in different versions to get an answer to this question.




samedi 4 novembre 2023

Why does ember data store share tokens between 2 webb apps iny domain?

0

I have 2 differents applications in ember.js both connect to the same api: "host1:3000/appA" and "host2:3001/appB". I use nginx so that the client can access appA and appB through a single domain, that is: "mydomain.com/appA" and "mydomain.com/appB". Everything is correct but the applications are sharing "store" ember objects. So if I login into appA, I also login into appB. How can I prevent session sharing between applications?.

I used this code from nginx, but does't work:

location /appA {
  proxy_pass http://host1:3000;
  proxy_cookie_path /appA /appA;
}

location /appB {
  proxy_pass http://host2:3001;
  proxy_cookie_path /appB /appB;
}



vendredi 3 novembre 2023

Uncaught Error: Could not find module `@ember/application` imported from `web-app/app`

What might be the reason for this error?

Please can anyone help? This is how my app-boot.js looks

      if (!runningTests) {
        require("web-app/app")["default"].create({"name":"web-app","version":"0.0.0+9380b4bc"});
      }
    

I have been upgrading my ember version. My whole app is stuck




ember-component-css in production env on ember 5.3.0 have no styleNamespace

When I am using ember-component-css in development env - everything works fine, I got class prefix in each style when i am using .

Example:

<div class=''> // <div class='hjsdf6_class-name-from-component'>
</div>

But when I am using my app with production env i got:

<div class='hjsdf6_ '>
</div>

In component.js:

import podNames from 'ember-component-css/pod-names'

  get styleNamespace() {
    return podNames['class-name-from-component']
  }

So, may be it is not a bug. May be it is a feature?...




mercredi 18 octobre 2023

how to get the previous routename in ember 2.16 to used in back button

i have a analytic route in ember this can be accessed from two routes (example user page and profile page) the below code is used to redirect to the analytic route

The problem is that i have a back button in the analytic page i want to send the user to the page from where the call is originated (i.e) if the user got to the analytic page from user page the back button should go to user page and if the user got to analytic page from profile page the back button should lead to profile page.

i dont want to mess the current code so i will be glad if the solution is in the form of action which returns the string of previous page. so that i could just call the action in place where i could give the dest page name.




samedi 14 octobre 2023

Ember-cli not using global version

This might actually more npm/node than just an EmberJS question.

Simply speaking I ran npm install -g ember-cli. However, when I check the version using ember --version, it shows me

ember-cli: 3.10.1
node: 18.18.2
os: darwin x64

That is definitely not the version I installed, because if i do npm ls -g --depth=0 to check my global packages, I get:

├── corepack@0.19.0
├── ember-cli@5.3.0
└── npm@10.2.0

To sanity check, i ran npm uninstall -g ember-cli and running npm ls -g --depth=0 again got

├── corepack@0.19.0
└── npm@10.2.0

So now, confirming that the global package is removed, I ran ember --version expecting the system to say ember is not installed, but instead i still get:

ember-cli: 3.10.1
node: 18.18.2
os: darwin x64

This leads me to believe there is some other installation of Ember on this computer and it's being used instead of the global version and I'd really like to just remove it - how do I find and remove it?

Useful context may be: I use NVM and Brew, although even in the past I didn't attempt to install ember with anything but the official installation direction of npm install -g ember-cli.




mardi 19 septembre 2023

How to create Ember Service that fetches data from Apollo GraphQL Server

I successfully fetched data from Apollo GraphQL Server in Amber route using ember-apollo-client. I tried the same approach to have a service fetching data but I'm getting Uncaught TypeError: this.apollo.query is not a function from app/services/nav-categories.js.

Minimal Working Example

Start a new app using

$ ember new super-rentals --lang en
$ ember generate service nav-categories

Configure Apollo end point in config/environment.js:

module.exports = function (environment) {
  const ENV = {
    ...

    apollo: {
      apiURL: 'http://localhost:4000',
    }
  };

app/gql/queries/allCategories.graphql:

query AllCategories {
  categories {
    name
  }
}

app/services/nav-categories.js:

import Service from '@ember/service';
import { queryManager } from "ember-apollo-client";
import allCategories from "super-rentals/gql/queries/allCategories.graphql";

export default class NavCategoriesService extends Service {
  constructor() {
    super();
    this.apollo = queryManager();
    this.categories = this.apollo.query({ query: allCategories });
  }
}

app/components/my-header.js:

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

export default class CartContentsComponent extends Component {
  // Will load the service defined in: app/services/nav-categories.js
  @service navCategories;
}

app/components/my-header.hbs:

<ul>

  <li></li>

</ul>

app/templates/application.hbs:

<MyHeader></MyHeader>




mercredi 23 août 2023

Unable to close module dropdown of parent application on clicking anywhere in child application UI screen rendered in Ifaram

I am facing problem to close module dropdown on clicking anywhere in child application UI screen.
I am not be able to handle click Outside functionality for dropdown elements defined in Parent application after clicking on the IFrame which loads child application inside Parent application as I have an application built using Ember JS. Inside that I have another application plugin using IFrame created using React JS. I wanted to hide the rendered dropdown from the parent application by clicking inside the IFrame where the child application is presented.
Can anyone provide a solution to achieve it?




dimanche 20 août 2023

Is there a way to call an Ember Octane component method with parameters and have it return the text without implementing a helper?

On Ember Octane versions, how would I call a method in the component.js so that it simply returns the string value into the hbs template (without creating a helper)?

For example, I want for each item in the list, pass the index value as a parameter into the randomColorClass() method in order to generate a random number between 0 and index value. I understand I could implement a new helper for it, but is there a way to simply do it direct in the component.js?

The reason I'm hesitant to use a helper is because helpers are "global" naturally and this color class is unique to and defined in this component only.

Component.js

randomColorClass(max) {
  const rand = Math.random() * max;
  return `color-${Math.floor(rand)}`;
}

Template.hbs


  <div class=>
    Hi, my name is 
  </div>




jeudi 17 août 2023

Ember application runtime error uncaught referenceerror ember is not defined vendor.js

I'm trying to upgrade the ember from 3.* to 4.12.2. I'm not getting any compilation issues but when I run my application I'm getting "uncaught referenceerror ember is not defined" inside the vendor.js file.

Any help appreciated, Thank you in advance.

Regards

I tried removing deprecated libraries, tried using auto import still getting this same issue




lundi 31 juillet 2023

Accessing Ember.js services from browser extension in versions ≥4.0

In Ember 4.0 and up, access to the Ember global object is deprecated. We have a browser plugin for internal debugging/support purposes that would gather some variables from an ember service using this global object and generate a text report that first-line support personel could use when investigating an issue.

Below is a part of the report generator script for Ember 3.28. This will normally be injected by the extension using chrome.scripting.executeScript with world 'MAIN', but pasting in the console will have the same effect for reproduction purposes. In Ember 4.0 and up, this will throw a TypeError since window.Ember is undefined.

var namespace = window.Ember.Namespace.NAMESPACES.find(ns => ns.name === 'acmecorp');
var sessionService = namespace.__container__.lookup('service:session');
var applicationAdapter = namespace.__container__.lookup('adapter:application');
var user = sessionService.get('user');
var userId = sessionService.get('user.id');
var userType = sessionService.get('user.type');
var userTypePath = applicationAdapter.pathForType(userType ?? 'user');

Following our upgrade to Ember 4.0 and up, is there any way to access this information from a browser extension?




mardi 25 juillet 2023

Ember 5.1 with ember-cli-stencil and third party components not working

I'm stuck. Perhaps someone is able to point me in the right direction to solve my problem.

I am trying to use third party stencil components in my ember app. Build is ok, but when i visit the app, this error is thrown:

Uncaught TypeError: (0 , _loader.applyPolyfills) is not a function
    at Module.callback (auto-import-stencil-collections.js:10:1)

I created a new and empty Ember-App, so nothing else is in it. I am using:

My package.json:

{
  "name": "desi-test-app",
  "version": "0.0.0",
  "private": true,
  "description": "Small description for desi-test-app goes here",
  "repository": "",
  "license": "MIT",
  "author": "",
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "build": "ember build --environment=production",
    "lint": "concurrently \"npm:lint:*(!fix)\" --names \"lint:\"",
    "lint:css": "stylelint \"**/*.css\"",
    "lint:css:fix": "concurrently \"npm:lint:css -- --fix\"",
    "lint:fix": "concurrently \"npm:lint:*:fix\" --names \"fix:\"",
    "lint:hbs": "ember-template-lint .",
    "lint:hbs:fix": "ember-template-lint . --fix",
    "lint:js": "eslint . --cache",
    "lint:js:fix": "eslint . --fix",
    "start": "ember serve",
    "test": "concurrently \"npm:lint\" \"npm:test:*\" --names \"lint,test:\"",
    "test:ember": "ember test"
  },
  "devDependencies": {
    "@babel/eslint-parser": "^7.22.5",
    "@babel/plugin-proposal-decorators": "^7.22.5",
    "@ember/optional-features": "^2.0.0",
    "@ember/string": "^3.1.1",
    "@ember/test-helpers": "^3.1.0",
    "@glimmer/component": "^1.1.2",
    "@glimmer/tracking": "^1.1.2",
    "@my-secret-thirdparty-components": "^2.7.0",
    "broccoli-asset-rev": "^3.0.0",
    "concurrently": "^8.2.0",
    "ember-auto-import": "^2.6.3",
    "ember-cli": "^5.1.0",
    "ember-cli-app-version": "^6.0.1",
    "ember-cli-babel": "^7.26.11",
    "ember-cli-clean-css": "^2.0.0",
    "ember-cli-dependency-checker": "^3.3.2",
    "ember-cli-htmlbars": "^6.2.0",
    "ember-cli-inject-live-reload": "^2.1.0",
    "ember-cli-sri": "^2.1.1",
    "ember-cli-stencil": "^1.0.0",
    "ember-cli-terser": "^4.0.2",
    "ember-data": "~5.1.0",
    "ember-fetch": "^8.1.2",
    "ember-load-initializers": "^2.1.2",
    "ember-modifier": "^4.1.0",
    "ember-page-title": "^7.0.0",
    "ember-qunit": "^7.0.0",
    "ember-resolver": "^10.1.1",
    "ember-source": "~5.1.1",
    "ember-template-lint": "^5.11.0",
    "ember-welcome-page": "^7.0.2",
    "eslint": "^8.43.0",
    "eslint-config-prettier": "^8.8.0",
    "eslint-plugin-ember": "^11.9.0",
    "eslint-plugin-n": "^16.0.1",
    "eslint-plugin-prettier": "^4.2.1",
    "eslint-plugin-qunit": "^8.0.0",
    "loader.js": "^4.7.0",
    "prettier": "^2.8.8",
    "qunit": "^2.19.4",
    "qunit-dom": "^2.0.0",
    "stylelint": "^15.9.0",
    "stylelint-config-standard": "^33.0.0",
    "stylelint-prettier": "^3.0.0",
    "tracked-built-ins": "^3.1.1",
    "webpack": "^5.88.2"
  },
  "engines": {
    "node": "16.* || >= 18"
  },
  "ember": {
    "edition": "octane"
  }
}

My ember-cli-build:

'use strict';

const EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function (defaults) {
  const app = new EmberApp(defaults, {
    // Add options here
    autoImport: {
      alias: {
        '@my-secret-thirdparty-components/loader': '@my-secret-thirdparty-components/dist/cjs/index.cjs',
      },
    }
  });


  return app.toTree();
};



dimanche 23 juillet 2023

persisting data in local storage using ember.js

I have some feature flags listed on the config file,

module.exports = function(environment) {
  let ENV = {
      featureFlags: {
        featureA: true, 
        featureB: false, 
        featureC: false,
        featureD: true,
      }
    }
  };

  return ENV;
};

and all the feature flags are shown as a card in a page.

    <UI::Card as |card| >
    <card.header @heading="Feature Flags" />
    <card.body as |body|>
        <div class="justify-content-between card-section">
            <ul class="list-group list-group-flush">
                
                    <li class="list-group-item justify-content-between align-items-center">
                      <div class="card-row flexbox">
                        <div class="card-left">
                          
                        </div>
                        <div class="card-right">
                            <UI::Switch
                            @value=
                            class="flex-grow-1"
                            @onClick=
                            />
                        </div>
                      </div>
                    </li>   
                
            </ul>
        </div>
    </card.body>
</UI::Card>

I am working with ember-tracked-local-storage library to connect the flags to the local storage.

@trackedInLocalStorage({ defaultValue: config.featureFlags }) featureFlags;

In the card whenever a feature flag is toggled I want to save that particular feature flag as an object to the local storage. If another flag is toggles it will get added on that object. And those particular feature flags should be shown as the saved value in local storage, and the other feature flags should be shown from the config file. There are less documentation on ember-tracked-local-storage. So, I am kinda lost on how I should go forward with this implementation.




mercredi 19 juillet 2023

Ember.js computed property not waiting for asynchronous RSVP promise

I have an Ember.js component where I'm trying to use a computed property to determine its visibility based on the result of an asynchronous RSVP promise. However, it seems like the computed property is not waiting for the promise to resolve, resulting in the count object being undefined.

Here's an excerpt from my component code:

import Component from '@ember/component';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
import RSVP from 'rsvp';

export default Component.extend({
    classNames: ['count'],
    countService: service('count'),

    getCount: computed(function () {
        debugger;
        RSVP.all([
            this.get('countService').getCount()
        ]).then(([count]) => {
            return Number(count);
        });
    }),

    isVisible: computed('getCount', function () {
        debugger;
        let count = this.get('getCount');
        return count !== undefined && count > 0;
    }),
});

As you can see, the getCount computed property is calling a method getCount() on the countService injected service. This method returns a promise that resolves with the count value.

In the isVisible computed property, I'm trying to access the count value returned by the getCount computed property. However, when I log the value of count during debugging, it shows up as undefined, even though the promise should have resolved by that point.

I'm not sure why the computed property is not waiting for the promise to resolve before trying to access the value. Am I missing something in my implementation? Is there a better way to handle asynchronous dependencies in Ember.js computed properties?

Any help or insights would be greatly appreciated!




lundi 17 juillet 2023

Not able to trigger event of parent application on click of Child application plugged-in using IFrame

I have One application created using Ember JS. Inside that I have plugined another application using IFrame created using react JS. I wanted to hide dropdown rendered from parent application by clicking inside IFrame where Child Application is rendered.

I tried one way in which I added 'click' event on the Document of the child element and using CSS I am able to hide the dropdown but not able to switch the flag state of the dropdown component of the parent application. I have added code snippet of the useEffect which i have added inside the child appliaction where I am handling click event.

As in this way I am not able to maintain consistency for Flag states of parent application through which Dropdown component is conditionally rendered.

Can anyone provide a feasible solution to achieve this scenario so that I an manage ClickOutside event applied on the dropdown component of the parent application and can able to manage show and hide feature even on the click of Child application rendered inside Iframe.

useEffect(() => { document.body.addEventListener('click', (e) => { const popup = window.parent.document.querySelector('.popover.bs-popover-top.show');

        console.log(window.parent);

        if (popup) {
            popup.style.display = 'none';
        }
    });
});

}

Added this useEffect inside child Application so that to handle click event for Child application.




samedi 15 juillet 2023

How to add a multi-line text field to a Discourse Community signup page?

I would like to add a multi-line text field to my Discourse community’s signup page, but I am not sure how. Am I able to edit the source code to do this, add a file to the source code, or use a plugin that enables this? Either way, I am unsure how to accomplish this task.

I tried using the default settings first and was only presented with single-line text field, confirmation, drop-down, and multi-select field options.




jeudi 13 juillet 2023

Triggering live-reloading when developing an Ember addon

I'm developing a private Ember addon for my team that will contain a few branded UI components that we will reuse in a bunch of different apps, such as a <BrandHeader /> and <BrandFooter />.

Is there an standard for creating a development environment that allows you to get live-reloading previews of your components as you build them? If there's not a standard, does anyone have a workflow that you've created that works well for you?

I tried using the strategy of creating an addon with the ember-cli ember addon <name> and then npm linking to an Ember app where I call the components, but with that method I need to rebuild the ember app every time I make a change in to the addon.




vendredi 7 juillet 2023

How to implement dynamic filtering in Ember.js dropdowns?

I'm working on an Ember.js application and I need to implement two dropdowns where the options in the second dropdown are filtered based on the selected value in the first dropdown. I have the following requirements:

The second dropdown should fetch its options from an API endpoint. Whenever a value is selected in the first dropdown, the options in the second dropdown should be filtered accordingly. The filtering should happen dynamically without a page refresh. I have tried implementing this functionality, but I'm facing some issues. The second dropdown does not update its options when a new value is selected in the first dropdown. How can I achieve this dynamic filtering behavior?

Here's a simplified version of the code I currently have: I have a parent and then 2 dropdown components inside it. I send the slected value of first dropdown from parent to the second dropdown. But the issue is that the new data is not filtered based on the value of first dropdown (namely: this.SelectedBU (injected from parent)). The component is very complex, thus I am only posting the index.js and index.hbs for the second dropsown.

second_dropdown.hbs



<h3></h3>
<div data-test-product-select>
  
    
      <Inputs::BadgeDropdownList
        @items=
        @listIsOrdered=true
        @onItemClick=
        @selected=
        @placement=
        @isSaving=
        @renderOut=
        @icon=
        class="w-80 product-select-dropdown-list"
        ...attributes
      >
        <:item as |dd|>
          <dd.Action data-test-product-select-badge-dropdown-item>
            <Inputs::TeamSelect::Item
              @product=
              @selected=
            />
          </dd.Action>
        </:item>
      </Inputs::BadgeDropdownList>
    
      <X::DropdownList
        @items=
        @listIsOrdered=true
        @onItemClick=
        @selected=
        @placement=
        @isSaving=
        @renderOut=
        class="w-[300px] product-select-dropdown-list"
        ...attributes
      >
        <:anchor as |dd|>
          <dd.ToggleAction
            class="x-dropdown-list-toggle-select product-select-default-toggle hds-button hds-button--color-secondary hds-button--size-medium"
          >
            <FlightIcon @name= />

            <span
              class="product-select-selected-value
                "
            >
              
            </span>

            
              <span class="product-select-toggle-abbreviation">
                
              </span>
            

            <FlightIcon @name="caret" class="product-select-toggle-caret" />
          </dd.ToggleAction>
        </:anchor>
        <:item as |dd|>
          <dd.Action class="pr-5">
            <Inputs::TeamSelect::Item
              @product=
              @selected=
              @abbreviation=
            />
          </dd.Action>
        </:item>
      </X::DropdownList>
    
  
    <FlightIcon data-test-product-select-spinner @name="loading" />
  
    <div
      class="absolute top-0 left-0"
      
    ></div>
  
</div>

and

second_dropdown.ts

import { assert } from "@ember/debug";
import {action, computed} from "@ember/object";
import { inject as service } from "@ember/service";
import { Placement } from "@floating-ui/dom";
import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
import { task } from "ember-concurrency";
import FetchService from "hermes/services/fetch";
import getProductId from "hermes/utils/get-product-id";

interface InputsTeamSelectSignature {
  Element: HTMLDivElement;
  Args: {
    selectedBU: string | null;
    selected?: string;
    onChange: (value: string, attributes?: TeamArea) => void;
    formatIsBadge?: boolean;
    placement?: Placement;
    isSaving?: boolean;
    renderOut?: boolean;
  };
}

type TeamAreas = {
  [key: string]: TeamArea;
};

export type TeamArea = {
  abbreviation: string;
  perDocDataType: unknown;
  BU: string
};

export default class InputsTeamSelectComponent extends Component<InputsTeamSelectSignature> {
  @service("fetch") declare fetchSvc: FetchService;

  @tracked selected = this.args.selected;

  @tracked teams: TeamAreas | undefined = undefined;
  @tracked selectedBU: string | null = null;

  @computed('args.selectedBU')
  get ReFetchTeams() {
    this.selectedBU = this.args.selectedBU;
    return this.fetchteams.perform();
  }

  get icon(): string {
    let icon = "folder";
    if (this.selected && getProductId(this.selected)) {
      icon = getProductId(this.selected) as string;
    }
    return icon;
  }

  get selectedProductAbbreviation(): string | null {
    if (!this.selected) {
      return null;
    }
    const selectedProduct = this.teams?.[this.selected];
    assert("selected Team must exist", selectedProduct);
    return selectedProduct.abbreviation;
  }

  @action onChange(newValue: any, attributes?: TeamArea) {
    this.selected = newValue;
    this.args.onChange(newValue, attributes);
  }

  // @action onBUChange(){
  //   this.selectedBU = this.args.selectedBU;
  //   this.fetchteams.perform();
  // }

  // protected fetchProducts = task(async () => {
  //   try {
  //     let products = await this.fetchSvc
  //       .fetch("/api/v1/products")
  //       .then((resp) => resp?.json());
  //     this.products = products;
  //   } catch (err) {
  //     console.error(err);
  //     throw err;
  //   }
  // });
    protected fetchteams = task(async () => {
      try {
        // Filter the teams based on the selected business unit
        console.log("parent injected value is: ",this.args.selectedBU)
        let teams = await this.fetchSvc
            .fetch("/api/v1/teams")
            .then((resp) => resp?.json());

        // Filter the teams based on the selected business unit
        const filteredTeams: TeamAreas = {};

        for (const team in teams) {
          if (Object.prototype.hasOwnProperty.call(teams, team)) {
            const teamData: TeamArea | undefined = teams[team];
            if (teamData && teamData.BU  === this.args.selectedBU) {
              filteredTeams[team] = teamData;
            }
          }
        }
        console.log("the filtered teams are: ",filteredTeams);
        this.teams = filteredTeams;
          console.log(this.teams);
        } catch (err) {
          console.error(err);
          throw err;
        }
      });

}

declare module "@glint/environment-ember-loose/registry" {
  export default interface Registry {
    "Inputs::TeamSelect": typeof InputsTeamSelectComponent;
  }
}

Any, sort of guidance will be highly appreciated! Thanks!

I have tried using @traked, @did-update etc, but nothing seems to work, even if I remove the "did-insert" the dropdown disappears completely.




mercredi 5 juillet 2023

How to set a a unique id to the elements of a DOM in ember.js

To add more context, I would like to incorporate Product Fruits to our ember app. The service that we will use is the Tours of Product Fruits. When creating a tour, product fruits target the element of client app with using id of an element. Ember generates ID for every element of the DOM. For example, if you have a button, the ID can be id="priority-navbar-item-ember110". However, if you refresh the page, the ID changes.

Question: Besides using data-test selectors, how can I have a unique id and will not change after refreshing the page or revisiting the app?




mardi 4 juillet 2023

How to properly restore a session on reload using ember simple auth custom authenticator's restore() function?

I have followed this YouTube tutorial on getting started with ember simple auth: https://www.youtube.com/watch?v=bSWN4_EbTPI&t=908s

I have everything working properly except for when refreshing the page. The custom authenticator I am using is supposed to use its restore() method on a refresh and grab the user token from the cookieStore, however when my code does this it gets the passed parameter, data which is an empty object upon console logging it. It's like it doesn't know to look in the cookieStore to fill out data with. I have tried messing with some settings in config/environment.js but can't find anywhere online with solid documentation on how to configure simple-auth. I am using v5.0.0

I can see the cookie being created when the app is loaded and filled out when I log in. For reference, here is what it looks like after logging in:

ember-simple-auth-session=%7B%22authenticated%22%3A%7B%22authenticator%22%3A%22authenticator%3Atoken%22%7D%2C%22token%22%3A%22secret%20token%22%7D

Here it is decoded:

{"authenticated":{"authenticator":"authenticator:token"},"token":"secret token"}

Here is my custom authenticator - app/authenticators/token.js

import Base from 'ember-simple-auth/authenticators/base';
import { inject as service } from '@ember/service';

export default class CustomAuthenticator extends Base {
  @service router;
  @service session;

  restore(data) {
    console.log('Restore');
    console.log(data);
    const { token } = data;

    if(token) {
      return data;
    }
    else {
      throw 'no valid session data';
    }
  }

  async authenticate(userData) {
    let response = await fetch('http://localhost:5000/users/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(userData),
    });

    if(response.ok) {
      response.json().then((data) => {
        const { token } = data;
        this.session.set('data.token',token);

        console.log(this.session);
        this.router.transitionTo('user', data.id);
      });
    } 
    else {
      let error = await response.text();
      throw new Error(error);
    }
  }

  invalidate() {
    return new Promise((resolve, reject) => {
      resolve();
    });
  }
}

And this is all I have in session-stores/application.js

import CookieStore from 'ember-simple-auth/session-stores/cookie';

export default class ApplicationSessionStore extends CookieStore {}

I'm trying to just extract the token field from the cookie which by my understanding should be getting passed into restore(data) but when I do console.log(data) I get {} which is just an empty object. If I try console.log(data.token) I get undefined. I've been stuck on this for a really long time now and I am sure it's something silly on my end. Any help is appreciated.




set variable in hbs template using ember.js

I have an array of data and I need to iterate over it in my hbs template:


  <th>
    
  </th>



  <th>
    
  </th>

How do I declare a variable and increase it to replace the hardcoded value?

I tried to wrap with but that did not worked:


  
    <th>
      
    </th>
  

I'm using ember 2.13.




how to update controller after RSVP.allSettled

After all rsvp promises are done in ember controller, how can I save all error status in controller and update DOM? I got undefined 'this', controller no longer accessible.

export default class someController extends Controller {
  @tracked errorlist = [];

  @action someAction {
    RSVP.allSettled(prommises).then(function(retarray){
      retarray.forEach((retstate) => {
        if (retstate.state == 'rejected') {
          this.errorlist.push(stateRet.reason);   
          //'this' undefined, how to update errlist?
        }
      });
    })
  }
}



vendredi 30 juin 2023

EMBER: Render div block only if component has yielded

I have the following hbs snippet:

<div class='photo-viewer-control' local-class='leftbar'>
  
</div>

I want to render the div only if leftbar has yielded.

I already tried the following:


  <div class='photo-viewer-control' local-class='leftbar'>
    
  </div>

I added the has-block but the div is still rendering when there is no leftbar.




jeudi 29 juin 2023

ember data 3.28 rollback after save

Is there any way to rollback model after model.save or model.destroyRecord failed

try {
  await testModel.save();
} catch (error) {
  // How to rollback testModel here?
}



dimanche 25 juin 2023

Ember JS Issues With Trying To Pass an Action Into a Named Block

I'm trying to make a modal component from scratch in ember js and I'm running into an issue with the button to open the modal. I want to allow the open button to be passed to the component using a block called <:buttonContent></:buttonContent> and pass in the function to open the modal. For some reason with this approach the open action only works once and then the button does nothing when clicking it. I can see that the button state is correct and it works as expected if I use a button directly in the modal component.


<Modal>
    <:buttonContent as |action|>
        <Button::Basic @action=>
            AddCoin
        </Button::Basic>
    </:buttonContent>
    <:default>
    </:default>
</Modal>



    



    <div class="curtain">
    </div>



    <div class=  >
        <Button::Icon @icon="close" @action= class="close-button"></Button::Icon>
        <div class="modal-content">
            
        </div>
    </div>

// component controller

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

export default class ModalComponent extends Component {

    @tracked isOpen= false;

    focusTrapOptions = {
        allowOutsideClick: this.clickOutside
    }

    @action clickOutside(): boolean {
        this.close();
        return false;
    }
    
    @action open(): void {
        this.isOpen = true;
    }

    @action close(): void {
        this.isOpen = false;
    }
}

I tried putting in a debugger breakpoint on the action and can see that it gets hit on the first call but all subsequent calls don't trigger it. I can also tell that other buttons still work on the page even though the open modal button doesn't.




mercredi 21 juin 2023

How to use downloadFile using the Capacitor?

I am using ember.js and one of the functionality of my component is to download a file. I'm trying to use the Capacitor to download a file.

Issue: Whenever the code below triggers, I am getting this error message on my xcode -> [error] - {"errorMessage":"Unable to download file","message":"Unable to download file","code":"DOWNLOAD"}. I only receive error when using native apps, it works really well for web app.

/components/component.js

import Component             from '@glimmer/component';
import { action }            from '@ember/object';
import { Plugins, FilesystemDirectory, CapacitorHttp, Diretory } from '@capacitor/core';
import { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
import { Http } from '@capacitor-community/http'

export default class ExportLink extends Component {
  @action
  async onClick() {
    this.isRequesting = true;

    try {
      // Fetch the download url, since a download has no Authentication information
      const urlResponse = await this.store
        .fetch('signed_urls', { type: 'post', body: { request_url: this.requestUrl } });
      const options = {
        url: urlResponse.url,
        filePath: `${this.fileName}.${this.args.extension}`,
        fileDirectory: Directory.Documents,
      };
      const response = await Http.downloadFile(options);
      const blob     = await response.blob;
      const downloadResponse = new Response(blob, {
        status: response.status,
        headers: (new Headers(response.headers))
      })

      if (!downloadResponse.ok) {
        throw downloadResponse.statusText
      }

      // create a new download link. Add the content of the download, so the download prompt is immediatly invoked
      const link             = document.createElement('a');
      const objectUrl        = URL.createObjectURL(blob);

      link.setAttribute('href', objectUrl);
      link.setAttribute('download', `${this.fileName}.${this.args.extension}`);
      link.setAttribute('rel', 'noopener noreferrer');
      link.setAttribute('target', '_blank'); // fallback if a direct download isnt supported

      link.dispatchEvent(new MouseEvent('click'));

      URL.revokeObjectURL(objectUrl);
    }
    catch(e) {
      console.error({e: e});
      this.notifications.add(this.intl.t('general.forms.unknown_error'), { type: 'warning' });
    }
    finally {
      this.isRequesting = false;
    }

    return false;
  }
}

Additional Question: What should be the filePath for the android or Ios? Or my question is irrelevant to the issue?




jeudi 15 juin 2023

how to access dom in ember 4.12 controller

I have a input box in DOM, and monitor the input value in controller, and there's another button, if the input value is changed, I want to change the button title or properties accordingly, how can I do this in controller?

test.hbs

<input type="text" value="somevalue" />
<button type="button" id="test">test</button>

test.js

  @action
  updatevalue(value) {
    //how to access test button, and change its title?
  }



dimanche 11 juin 2023

Ember upgrade Why can't the module be found

I'm trying to upgrade my ember Project to be specific i want to upgrade ember-auto-import to 2.x. But This requires at least ember 4.x so i upgraded every depencency in my package.json thats related to ember itself (ember-source, ember.data etc.). So after i upgraded everything this is my package.json. But as soon i start the application i get this error.

After a little interogation i realized that even the required package is in the package.json of the dependency, it doesnt get downloaded inside the node_moduels folder of the package. So i tried to import the missing package in the package.json of the application itself but that didn't help. But what i found is that if i remove the package that throws the error an other package throws an error that looks almost the same, so u think it's not an error whith the package itself but an error with ember auto import or my config. Does anybody know this kind of error and know how to solve it?




mercredi 7 juin 2023

strict mode template error when using component

I defined a test component in emberjs, expect it output each value of testOpts, but got below error when rendering the page, how should I define the component ?

Uncaught (in promise) Error: Attempted to resolve a value in a strict mode template, but that value was not in scope: testOpts
    at encodeOp (opcode-compiler.js:2160:1)
    at pushOp (opcode-compiler.js:2067:1)
    at opcode-compiler.js:468:1
    at Compilers.compile (opcode-compiler.js:417:1)
    at expr (opcode-compiler.js:587:1)
    at CompilePositional (opcode-compiler.js:657:1)
    at SimpleArgs (opcode-compiler.js:633:1)
    at Call (opcode-compiler.js:719:1)
    at opcode-compiler.js:436:1
    at resolveHelper (opcode-compiler.js:229:1)

components/helper/test.hbs:

<div>

  testOpt: 
  
</div>

components/helper/test.js:

import Component from '@glimmer/component';

export default class TestComponent extends Component {
  get testOpts() {
    return ['a', 'b'];
  }
}

application.hbs

<Helper::Test />

if I don't use the output is fine, but I'm wondering how should I get to work.




Passing data from controller to component in ember js

I have situation where a have component that with send a function to the controller and the data is computed in controller.Again I need to send the resultant of the function to the component and do the rest of the computation.As a beginner Im encountering it .Is it possible to do so?

I tried it to pass as a variable but it is getting a empty list




lundi 5 juin 2023

Build Error (CreateEmberL10nFastBootAssetMap) when starts an Ember Project

I'm trying to create my built folder for an emberJS project, but I get this error when I run the command yarn start

Build Error (CreateEmberL10nFastBootAssetMap)

ENOENT: no such file or directory, scandir '/var/folders/2z/169nvw1959q444m88mg24prc0000gn/T/broccoli-10881ZqfXS0rWIq4v/out-861-broccoli_merge_trees//var/folders/2z/169nvw1959q444m88mg24prc0000gn/T/broccoli-10881ZqfXS0rWIq4v/out-861-broccoli_merge_trees'


Stack Trace and Error Report: /var/folders/2z/169nvw1959q444m88mg24prc0000gn/T/error.dump.027ea1cdeb583673f9f08a5e2e797c1b.log



samedi 3 juin 2023

Upgrading EmberJS project to Node 16 with yarn results in node-sass conflicts. How to fix it?

I'm trying upgrade to Node 16 enviroment on my emberJS project using yarn.

package.json:

{

  "devDependencies": {
    "@babel/core": "^7.22.1",
    "@babel/plugin-proposal-object-rest-spread": "^7.17.3",
    "@babel/plugin-transform-block-scoping": "^7.21.0",
    "@ember/jquery": "^2.0.0",
    "@ember/optional-features": "^2.0.0",
    "@ember/render-modifiers": "^2.0.5",
    "@glimmer/component": "^1.1.2",
    "@glimmer/tracking": "^1.1.2",
    "@open-event/theme": "^0.2.2",
    "@sentry/browser": "^6.19.7",
    "@sentry/integrations": "^6.19.7",
    "@sentry/tracing": "^6.19.7",
    "@types/ember": "^4.0.0",
    "@types/ember-data": "^3.16.15",
    "@types/ember-data__model": "^3.16.1",
    "@types/ember-qunit": "^3.4.15",
    "@types/ember__test-helpers": "^2.6.1",
    "@types/lodash-es": "^4.17.6",
    "@types/moment": "^2.13.0",
    "@types/qunit": "^2.19.5",
    "@types/rsvp": "^4.0.4",
    "@types/url-parse": "^1.4.8",
    "@typescript-eslint/eslint-plugin": "^5.23.0",
    "@typescript-eslint/parser": "^5.59.8",
    "async": "^3.2.3",
    "babel-eslint": "^10.1.0",
    "broccoli-asset-rev": "^3.0.0",
    "broccoli-persistent-filter": "^3.1.3",
    "croppie": "^2.6.5",
    "css-loader": "^5.2.7",
    "dompurify": "^3.0.3",
    "ember-ajax": "5.1.2",
    "ember-auto-import": "^1.12.2",
    "ember-classic-decorator": "^3.0.0",
    "ember-cli": "~4.12.1",
    "ember-cli-accounting": "^2.1.0",
    "ember-cli-app-version": "^5.0.0",
    "ember-cli-autoprefixer": "2.0.0",
    "ember-cli-babel": "^7.26.11",
    "ember-cli-cjs-transform": "^2.0.0",
    "ember-cli-clipboard": "^0.16.0",
    "ember-cli-code-coverage": "^2.0.0",
    "ember-cli-dependency-checker": "^3.3.1",
    "ember-cli-deploy": "^1.0.0",
    "ember-cli-deploy-build": "^2.0.0",
    "ember-cli-deploy-git": "^1.3.4",
    "ember-cli-deploy-html-manifest": "0.0.6",
    "ember-cli-deploy-revision-data": "^2.0.0",
    "ember-cli-deprecation-workflow": "^2.1.0",
    "ember-cli-document-title-northm": "^1.0.3",
    "ember-cli-dotenv": "^3.1.0",
    "ember-cli-fastboot": "^4.1.1",
    "ember-cli-flash": "^2.2.0",
    "ember-cli-head": "^2.0.0",
    "ember-cli-html-minifier": "^1.1.0",
    "ember-cli-htmlbars": "^6.0.1",
    "ember-cli-ifa": "^0.10.0",
    "ember-cli-inject-live-reload": "^2.1.0",
    "ember-cli-moment-shim": "^3.7.1",
    "ember-cli-nouislider": "^1.2.1",
    "ember-cli-pace": "devotox/ember-cli-pace#master",
    "ember-cli-qunit": "^4.4.0",
    "ember-cli-sass": "^11.0.1",
    "ember-cli-scss-lint": "^2.4.1",
    "ember-cli-shims": "^1.2.0",
    "ember-cli-string-helpers": "^6.1.0",
    "ember-cli-stripe": "^3.0.0",
    "ember-cli-typescript": "^5.2.1",
    "ember-cli-typescript-blueprints": "^3.0.0",
    "ember-cli-uglify": "^3.0.0",
    "ember-composable-helpers": "^5.0.0",
    "ember-config-service": "^1.0.0",
    "ember-cookies": "^0.5.2",
    "ember-data": "3.14.1",
    "ember-data-has-many-query": "^0.3.1",
    "ember-data-storefront": "^0.18.1",
    "ember-decorators": "^6.1.1",
    "ember-drag-drop": "^0.8.2",
    "ember-exam": "^6.1.0",
    "ember-export-application-global": "^2.0.1",
    "ember-fetch": "8.1.1",
    "ember-fullcalendar": "^1.8.0",
    "ember-h-captcha": "^2.5.1",
    "ember-href-to": "5.0.0",
    "ember-infinity": "^2.3.0",
    "ember-l10n": "^4.3.1",
    "ember-leaflet": "^5.0.1",
    "ember-link-action": "2.0.4",
    "ember-load-initializers": "^2.1.2",
    "ember-math-helpers": "^3.0.0",
    "ember-maybe-import-regenerator": "^1.0.0",
    "ember-metrics": "^1.5.0",
    "ember-moment": "^8.0.2",
    "ember-notify": "^6.0.3",
    "ember-power-select": "^5.0.4",
    "ember-print-this": "^2.0.0",
    "ember-qunit": "^4.6.0",
    "ember-resolver": "^8.0.3",
    "ember-route-action-helper": "^2.0.8",
    "ember-router-scroll": "^3.3.7",
    "ember-simple-auth": "^4.2.2",
    "ember-simple-auth-token": "^5.3.0",
    "ember-source": "3.20.3",
    "ember-table": "^2.2.3",
    "ember-template-lint": "^2.21.0",
    "ember-truth-helpers": "^3.1.1",
    "ember-uuid": "^2.1.0",
    "eslint": "^7.32.0",
    "eslint-plugin-ember": "^10.6.1",
    "eslint-plugin-ember-suave": "^2.0.1",
    "eslint-plugin-node": "^11.1.0",
    "fastboot-app-server": "^4.1.1",
    "google-material-color": "^1.3.1",
    "http-status": "^1.6.2",
    "leaflet": "^1.8.0",
    "loader.js": "^4.7.0",
    "lodash-es": "^4.17.21",
    "mini-css-extract-plugin": "^2.7.6",
    "moment-timezone": "^0.5.31",
    "npm-run-all": "^4.1.5",
    "object-to-formdata": "^4.5.1",
    "paypal-checkout": "^4.0.338",
    "pre-commit": "^1.2.2",
    "query-string": "^7.1.1",
    "qunit-dom": "^2.0.0",
    "sass": "^1.62.1",
    "semantic-ui-calendar": "^0.0.8",
    "semantic-ui-ember": "3.0.5",
    "string_decoder": "^1.3.0",
    "style-loader": "^2.0.0",
    "tinyColorPicker": "https://github.com/PitPik/tinyColorPicker#1.1.1",
    "torii": "^0.10.1",
    "typescript": "^5.0.4",
    "url-parse": "^1.5.10",
    "webpack-bundle-analyzer": "^4.5.0",
    "wysihtml": "^0.5.5",
    "xgettext-template": "^4.1.2"
  },
  "engines": {
    "node": ">= 12.x <17",
    "yarn": ">= 1.2.0"
  },
  "private": true,
  "dependencies": {
    "@stripe/stripe-js": "^1.53.0",
    "ua-parser-js": "^1.0.35"
  },
  "ember": {
    "edition": "octane"
  },
  "ember-addon": {
    "paths": [
      "lib/cache-updater",
      "lib/start-title"
    ]
  },
  "fastbootDependencies": [
    "crypto",
    "node-fetch",
    "ua-parser-js"
  ]
}

I run the below command to switch to node 16

nvm use 16

Then run the below command to upgrade all dependencies to node 16

yarn upgrade

Result as below:

1 error generated.
make: *** [Release/obj.target/binding/src/binding.o] Error 1
gyp ERR! build error 
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit ([PROJECT_PATH]/node_modules/node-gyp/lib/build.js:262:23)
gyp ERR! stack     at ChildProcess.emit (node:events:513:28)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:293:12)
gyp ERR! System Darwin 21.6.0
gyp ERR! command "[USERS_PATH]/.nvm/versions/node/v16.20.0/bin/node" "[PROJECT_PATH]/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd [PROJECT_PATH]/node_modules/node-sass
gyp ERR! node -v v16.20.0

Tried to remove node-sass then upgrade, but the problem stays the same.




lundi 29 mai 2023

single-spa consume shared utility module in ember

I want to use single-spa with react and ember apps that will need to share data between them, I would like to use https://single-spa.js.org/docs/module-types/#utilities utility module for exposing observable data.

In react project utility module is consumed via webpacks externals option

reacts webpack:

module.exports = (webpackConfigEnv, argv) => {
  const defaultConfig = singleSpaDefaults({
    orgName: "company",
    projectName: "react-app",
    webpackConfigEnv,
    argv,
  });

  return merge(defaultConfig, {
      externals: {
        "react": "react",
        "react-dom": "react-dom",
        // utility module 
        "@company/utility": "@company/utility"
      }
  });
};

And it works just fine in react, but ember uses ember-cli/broccoli for building an app and I don't know how to consume utility package, is it even possible? Or the only way to use package is to publish it via npm or expose functionality via props when registering ember mf in root-config for example:

registerApplication(
  "ember",
  () => {
    const appName = "ember";
    const appUrl = `${domain}/ember/assets/ember.js`;
    const vendorUrl = `${domain}/ember/assets/vendor.js`;
    console.log({ appName, appUrl, vendorUrl });
    return loadEmberApp(appName, appUrl, vendorUrl);
  },
  (location) => {
    console.log(location.pathname.startsWith("/ember"))
    return location.pathname.startsWith("/ember");
  },
  { // all data from utility module should be exposed here }
);



vendredi 26 mai 2023

How can I troubleshoot a router.js:958 error while processing route: item in Ember.js?

Any thoughts as to how this can be fixed -- I have not a clue! It works fine until an upgrade is done. I have tried multiple times with various versions but no go.

post-upgrade: router.js:958 Error while processing route: item You must provide a param idPath. and
jquery.min.js:2 Uncaught Error: You must provide a param idPath.

bower.json original { "name": "shepherd", "private": true, "dependencies": { "bootstrap": "~3.3.2", "ember": "~1.10.0", "handlebars": "~3.0.0", "jquery": "~1.11.3" } } # updated(attempt) { "name": "shepherd", "private": true, "ignore": [ "**/.*", "node_modules", "bower_components", "test", "tests" ], "dependencies": { "jquery": "^3.7.0", "bootstrap": "^5.2.3", "handlebars": "^4.7.7", "ember": "^2.0" } }

# tab config  index.html: <script src="config.js"></script>
# consumed by app.js
<script src="app.js"></script>
var config = {}
config.title = 'TABS Title'
config.items = [
  {name: 'T1', items: [
    {name: "NDC-A", items: [
      {name: "T1-NDCA:Z1 Stats", url: "<LINK>"},
      {name: "T1-NDCA:Z1 Graphs", url: "<LINK>"},
      {name: "T1-NDCA:Z2 Stats", url: "<LINK>"},
      {name: "T1-NDCA:Z2 Graphs", url: "<LINK>"},
    ]},
    {name: "NDC-B", items: [
      {name: "T1-NDCB:Z1 Stats", url: "<LINK>"},
      {name: "T1-NDCB:Z1 Graphs", url: "<LINK>"},
      {name: "T1-NDCB:Z2 Stats", url: "<LINK>"},
      {name: "T1-NDCB:Z2 Graphs", url: "<LINK>"},
    ]},
   ]},
]

FYI: tabs sample as generated via above config # app.js index.html:

    var App = Ember.Application.create({
    })
    
    App.initializer({
        name: 'config',
        initialize: function(container, app) {
            app.config = Ember.copy(config)
        },
    })
    
    App.Router.map(function() {
        this.resource('item', {path: '/*idPath'})
    })
    
   // fails here
    
    App.ItemRoute = Ember.Route.extend(App.TitleHandler, App.ItemFactory, {
        model: function(params) {
            var items = this.getItems(App.config.items)
            var item = this.getItem(items, params.idPath)
            **// 'item' and 'items' are both populated as expected**
            if (!item) {
                return this.transitionTo('item', '')
            }
            this.setTitle(item.title)
            return item
            **// FAILS HERE 'port return'**
        },
    })
    
    



jeudi 25 mai 2023

How to install ember-cli 4.12.1

When I use npm to install ember-cli 4.12.1 by below command

#npm install -g ember-cli@4.12.1

The install is successful, but I see ember-cli version is 3.27.0

#ember --version
Browserslist: caniuse-lite is outdated. Please run:
  npx update-browserslist-db@latest
  Why you should do it regularly: https://github.com/browserslist/update-db#readme
WARNING: Node v18.16.0 is not tested against Ember CLI on your platform. We recommend that you use the most-recent "Active LTS" version of Node.js. See https://git.io/v7S5n for details.
ember-cli: 3.27.0
node: 18.16.0
os: linux x64

The version is available from npm, so how can I install ember-cli 4.12.1?

#npm view ember-cli
ember-cli@4.12.1 | MIT | deps: 93 | versions: 315Command line tool for developing ambitious ember.js appshttps://cli.emberjs.com/release/
......

I also manually download tarball from https://registry.npmjs.org/ember-cli/-/ember-cli-4.12.1.tgz and installed the tarball, but the version still is 3.27.0




mercredi 24 mai 2023

Why am I losing JSDoc type definitions when importing a React library into an Ember app in a monorepo?

I have two packages in a single repo, charts is for all of the charts and is built in React, while ui is for the rest of the UI and built in Ember.

Because the charts library is quite complicated, I decided to add JSDoc to each chart to expose the expected parameters to the UI library. To make this simpler, each chart is exported, then imported into a index.js file in the React app, which is then imported into the Ember app and consumed there.

The issue I'm facing is that I can see the type definition everywhere in the React app, but as soon as I import it into the Ember app, I lose all of the type definition on hover

I tried following the steps here to no avail




lundi 22 mai 2023

Adding custom text below categories image in discourse

In discourse categories page have one class i can target to add custom text using content on class::after but this function create text on all the images because all have same class .category-logo.aspect-image img , i want to add unique text below all categories , i have written this code but it only works after reloading the page. please support

    <script>
  document.addEventListener("DOMContentLoaded", function() {
    $(function() {
      var categories = [
        {
          logoUrl: "/uploads/",
          line1: "ATALANTA, USA",
          line2: "<a href='https://example.com' style='color: #646464;'>WWW.ATALANTA.COM</a>"
        },
        {
          logoUrl: "/uploads", // Replace with actual image URL for Category 2
          line1: "Denver, United States",
          line2: "<a href='https://example.com' style='color: #646464;'>WWW.ATALANTA.COM</a>"
        },
        // Add more objects for other categories
        {
          logoUrl: "/uploads", // Replace with actual image URL for Category 2
          line1: "Dowman Drive, Atalanta",
          line2: "<a href='https://example.com' style='color: #646464;'>WWW.ATALANTA.COM</a>"
        },
        {
          logoUrl: "/uploads", // Replace with actual image URL for Category 2
          line1: "ATALANTA, USA",
          line2: "<a href='https://example.com' style='color: #646464;'>WWW.ATALANTA.COM</a>"
        },
        {
          logoUrl: "/uploads", // Replace with actual image URL for Category 2
          line1: "ATALANTA, USA",
          line2: "<a href='https://example.com' style='color: #646464;'>WWW.ATALANTA.COM</a>"
        },
        {
          logoUrl: "/uploads", // Replace with actual image URL for Category 2
          line1: "ATALANTA, USA",
          line2: "<a href='https://example.com' style='color: #646464;'>WWW.ATALANTA.COM</a>"
        },
      ];

      $(".category-heading").each(function(index) {
        var category = categories[index];
        var $logoElement = $(this).find(".category-logo img");
        var $descriptionElement = $("<p>")
          .html(category.line1 + "<br>" + category.line2)
          .addClass("custom99"); // Add your custom class name here

        $logoElement.after($descriptionElement);
      });
    });
  });
</script>



vendredi 12 mai 2023

Having trouble with QUnit test in ember because of Toast-ui-Editor, cannot find the solution

I'm currently working on an emberJS project, and I have a random global failure whenever I'm running tests (QUnit). We've been working on it since few days with a colleague, and we found out that it's coming from the Toast UI editor made for ember (https://github.com/evocount/ember-tui-editor) It hasn't been updated since 7 months, but we have no idea what to do to solve the problem :/

we tried to add a later() method to wait (like a set Timeout) and it's not working when we comment the willDestroy ember hook inside the TUI component, tests are running completely. There is no coherent pattern to find out what the problem exactly is! ^^'




lundi 8 mai 2023

Parent route's model gets fired when transition to child route in ember

Having parent route with dynamic segment and queryparam and child route with dynamic segment. From parent route tried to transition to child route, but parents model hook is also getting triggered again.

Example:

From Route: parent/:parent_id? Qp=sample To Route: Parent/:parent_id/child/:child_id? Qp=sample

Currently in "From Route" And trying to transition to "To Route". But parent's model hook getting called again.

I don't want the parent route to triggered again. Please help me how to solve this issue.




npm - same dependency version getting different dependencies tree

In my two projects, I have defined devDependencies for optional-features as

"@ember/optional-features": "^1.3.0",

But when I do npm ls after npm install in both projects, I get different dependency tree.

One has

├─┬ @ember/optional-features@1.3.0
│ └─┬ inquirer@7.1.0
│   └── lodash@4.17.15  deduped

Second one has :

├─┬ @ember/optional-features@1.3.0
│ └─┬ inquirer@7.3.3
│   └── lodash@4.17.21  deduped

In ember/option-features, inquirer is defined as "inquirer": "^7.0.1",

I have verified that I am using same nvm version for both the projects.

Why npm is not getting same inquirer@7.3.3 for both projects? Is there something I am missing?




jeudi 20 avril 2023

my data from different adapters is stored in a single model how do i store them in different models

Ember Data: cli 4.12

I have created 2 modles user and repo and 2 adapters with same name user and repo also 2 serializers with same names.

I am calling store.findAll 2 times in a single route's model hook for both repo and user and returning the data.

when I check ember data in ember inspector I only see one model name ie user with repo data appended at bottom for same attribute names and undefined for others.

I want to know how to set models for different calls.

I dont have any code available to paste right now ask me if you dont understand this query, thank you.

i tried asking chatGPT turns out its not great for ember framework and keeps givng me weired codes probably of older cli and new ones mixed




mercredi 12 avril 2023

caught TypeError: requireNode is not a function at window.require

''' ( function (win) => { const { requireNode, require: requireAMD } = win; if (requireAMD) { win.require = (...args) => { try { return requireAMD(...args); } catch(error) { if (error.toString().includes('Error: Could not find module')) { return requireNode(...args); } console.error(error); } }; Object.assign(win.require, requireNode, requireAMD); } else {win.require = requireNode;` } })(window); '''

Facing error for requireNode as 'requireNode is not defined' in catch block return requireNode(...args);.




lundi 10 avril 2023

How to implement infinite scroll in columns?

Here I have a work scenario where I need to add columns based on Dates and granularities (last 48 hrs - 15 mins).

In this case, I need to create - 2 Columns (eg- 10/04/2023 and 09/04/2023) and 192 Children columns (96 children each (15min x 4 x 24))

So all the above 192 columns will get created dynamically based on user selection.

So here our problem comes into the picture while creating 192 columns at once definitely my screen will get freeze for a while.

To make it efficient I want to implement infinite scrollable columns so that it doesn't need to render a large number of columns at once.

Any suggestions will be appreciated!!




dimanche 2 avril 2023

Nothing is getting displayed on webpage while using ember.js

I am building a simple web application using ember.js ,but in the webpage ,nothing is displayed ,in the console the following error is being displayed.I am using mirage as the back end

rsvp.js:26 Uncaught TypeError: Cannot read properties of undefined (reading 'sentence')
    at Temp.title (post.js:10:1)
    at eval (mirage-esm.js:485:24)
    at Array.forEach (<anonymous>)
    at sortAttrs (mirage-esm.js:481:22)
    at Factory.build (mirage-esm.js:388:16)
    at EmberServer.build (mirage-esm.js:7325:24)
    at EmberServer.create (mirage-esm.js:7397:30)
    at EmberServer.createList (mirage-esm.js:7466:31)
    at Object._default [as default] (default.js:9:1)
    at EmberServer.config (mirage-esm.js:7152:37

I am adding some files code here for the understanding , application.hbs


<div class ="jumbo">
<h2 id="title">
    My ember blog
    
</h2>
</div>


posts.js under templates



<ul>
  
    <li>
      
    </li>
  
</ul>

post.js under model folder in app

import Model, { attr } from '@ember-data/model';

export default class PostModel extends Model {
  @attr title;
  @attr body;
  @attr('date') publishedAt;
}

posts under routes in app folder

import Route from '@ember/routing/route';

export default class PostsRoute extends Route {
  model() {
    return this.store.findAll('post');
  }
}

posts.js under factories under mirage folder

import { Factory } from 'miragejs';

import faker from '@faker-js/faker';

export default Factory.extend({
  title() {
    return faker.lorem.sentence();
  },

  body() {
    return faker.lorem.paragraph();
  },

  publishedAt() {
    return faker.date.past();
  },
});

So these are the files that I have used in this project .and if you know the structure of emp app ,you will be able to understand these files. My ember-cli version is 3.24.0 node: 14.21.3 os: linux x64 Please help me in resolving this ,I am beginner in ember




mercredi 22 mars 2023

Ember-ace not works on clear ember project with ember-infinity installs as dependency

Can someone explain why ? I have no warnings in console. So, i need ember-infinity for my project, but don't know how to force to work ember-infinity with ember-ace.

Using ember-infinity: 2.3.0 and ember-ace: 3.0.0. Ember-cli version: 4.10.0

if I remove ember infinity from the project, then everything is ok




mardi 21 mars 2023

In Ember, in resetController function, why is transition undefined sometimes?

I am using Ember 3.16

I have an Ember application which has multiple routes.

For one of the routes, let's call it route x, I need it to reset only when it leaves the page. So I use resetController and only reset when isExiting and transition is true, like below:

resetController(controller, isExiting, transition) { if (isExiting && transition) {...} },

I need to check transition because I have pagination so when it goes to the next page, it refreshes the route.

The problem is when I navigate to some of the routes, transition is undefined so when I come back to route x, it does not reset. I need it to reset every time we go to a different page.

I do not understand why transition is defined when navigating to some routes and not others, anyone have any insights?

I tried comparing the routes where transition is defined to the ones they are not defined. I could not find a pattern. For some of the differences I even tried making them similar to see if it fixes it. It did not work.

I used Ember Inspector to see the routes change, and the routes always change. When transition is defined or undefined, I see routes changing.




mercredi 1 mars 2023

How do I successfully use jquery in emberjs

I'm attempting to change the value of an ember 'Input Helper' whenever a separate 'Input Helper' is clicked. The array of js objects is displayed in a child component as is the two Input Helpers the user interacts with. I have the actions bubble up into the template controller and handle and changes to the data there, where I would have thought the tracked objects array would update to show the new 'Input Helper' value. That isn't the case however.

I've moved onto installing the @ember/jquery add-on with

ember install @ember/jquery

and importing into my project with

import jQuery from 'jquery';

I even enabled Ember's jquery integration, even though I'm fairly certain it has been deprecated, according to this: https://rfcs.emberjs.com/id/0705-deprecate-jquery-optional-feature/After all of this is said and done, ember throws the following error:

TypeError: requireNode is not a function

Here is the full error stack:

Navigated to http://10.0.0.69:4200/add-cards
DEBUG: ------------------------------- index.js:170
DEBUG: Ember      : 4.10.0 index.js:170
DEBUG: Ember Data : 4.9.1 index.js:170
DEBUG: ------------------------------- index.js:170
GEThttp://10.0.0.69:4200/favicon.ico
[HTTP/1.1 404 Not Found 0ms]



Error occurred:

- While rendering:
  -top-level
    application
      add-cards

runtime.js:4985
Uncaught (in promise) TypeError: requireNode is not a function
    require wrap-require.js:12
    Ember 13
    resolveComponent opcode-compiler.js:194
    encodeOp opcode-compiler.js:2126
    pushOp opcode-compiler.js:2067
    <anonymous> opcode-compiler.js:1715
    compile opcode-compiler.js:417
    compileStatements opcode-compiler.js:2070
    maybeCompile opcode-compiler.js:2049
    compile opcode-compiler.js:2032
    <anonymous> runtime.js:2973
    evaluate runtime.js:1052
    evaluateSyscall runtime.js:4214
    evaluateInner runtime.js:4185
    evaluateOuter runtime.js:4178
    next runtime.js:5009
    _execute runtime.js:4996
    execute runtime.js:4971
    sync runtime.js:5054
    runInTrackingTransaction validator.js:138
    sync runtime.js:5054
    Ember 3
    inTransaction runtime.js:4090
    Ember 5
    invoke backburner.js:284
    flush backburner.js:197
    flush backburner.js:360
    _end backburner.js:801
    _boundAutorunEnd backburner.js:525
    promise callback*buildNext/< backburner.js:26
    flush Ember
    _scheduleAutorun backburner.js:967
    _end backburner.js:807
    _boundAutorunEnd backburner.js:525
    promise callback*buildNext/< backburner.js:26
    flush Ember
    _scheduleAutorun backburner.js:967
    _end backburner.js:807
    _boundAutorunEnd backburner.js:525
    promise callback*buildNext/< backburner.js:26
    flush Ember
    _scheduleAutorun backburner.js:967
    _end backburner.js:807
    _boundAutorunEnd backburner.js:525
    promise callback*buildNext/< backburner.js:26
    flush Ember
    _scheduleAutorun backburner.js:967
    _end backburner.js:807
    _boundAutorunEnd backburner.js:525
    promise callback*buildNext/< backburner.js:26
    flush Ember
    _scheduleAutorun backburner.js:967
    _ensureInstance backburner.js:958
    schedule backburner.js:651
    <anonymous> Ember
    fulfill rsvp.js:383
    resolve$1 rsvp.js:363
    initializePromise rsvp.js:465
    Ember 2
    initializePromise rsvp.js:460
    Promise rsvp.js:916
    Ember 7
    invokeCallback rsvp.js:435
    then rsvp.js:492
    <anonymous> Ember
    invoke backburner.js:282
    flush backburner.js:197
    flush backburner.js:360
    _end backburner.js:801
    end backburner.js:592
    _run backburner.js:845
    run backburner.js:627
    Ember 7
wrap-require.js:12

I wasn't able to identify what the issue was or why this would occur. There isn't much that I found relating to this specific error.




mercredi 22 février 2023

Loader.js MissingModule at runtime after upgrading ember-auto-import to v2

My app is on v3.28 of Ember. After upgrading ember-auto-import from 1.12.0 to 2.6.0 (and adding webpack 5), I'm getting a missingModule error from loader.js for dependencies of my app's addons. I'm sure the issue is probably something that needs to be reconfiged in ember-cli-build, but i can't figure it out. Can somebody help point me in the right direction?

Instance of this error: Uncaught Error: Could not find module lodash.merge imported from ember-rollbar-client/services/rollbar

ember-rollbar-client: 0.9.0 -> lodash.merge: 4.6.1

Package versions: ember-cli: 3.28.6 node: 14.17.0 os: darwin arm64 ember-auto-import: 2.6.0 webpack: 5.75.0




mercredi 8 février 2023

CSS Images in EmberJS addons

I'd like to know the idiomatic way to reference css images (images linked in css through url(...) ) from within an Ember addon.

Ostensibly the addon public/ folder will get merged with dist/ in the final build and the css files will be merged with vendor.css

How can images therefore be linked i.e. if I have an image in /my-addon/public/images/icon.png how should I reference it in my CSS file? I've tried url(/my-addon/images/icon.png) and it doesn't respect the rootURL setting (only works if rootUrl = '/').

The only thing that seems to work is url(../my-addon/images/icon.png) but I've never heard mention that images should be linked with relative paths in this way.

Is there an established way to reference image assets from within addon css?

I've tried everything mentioned above but the only thing that works is relative paths. Am I correct to do so?




dimanche 5 février 2023

Cannot find module './transforms/babel-plugin-convert-existence-checks-to-macros'

I've recently updated ember-cli and my app to 4.10.0, and trying to build with:

ember serve

throws the following error:

Cannot find module './transforms/babel-plugin-convert-existence-checks-to-macros'

I've looked to see what module is missing. I came up with trying to install/reinstall ember-cli-babel and that didn't work either.




mardi 17 janvier 2023

ember-bootstrap with LESS -- application css not transpiling

I'm working on upgrading little-by-little an EmberJS Application that uses ember-bootstrap. Before moving to Ember 4 we are trying to move up to the Ember 3 LTS 3.28.6. However, we have ember-bootstrap using LESS in our project and things have fallen apart a bit because of some dependency mapping that pushes us to newer versions. To avoid migrating to SASS, I'm currently trying to use https://github.com/seanCodes/bootstrap-less-port to keep less for one last iteration. But a curious thing is happening in my local build: the application css is not being generated (.css) is nowhere to be found in dist/assets/ !

The build seems to go just fine (save the long list of deprecation errors).

Anyone have an idea why my appli.css is not generating ? How would I specify to ember-bootstrap to look for appli.less ? Is this possible ? If it is, it seems the code is here: https://github.com/ember-bootstrap/ember-bootstrap/blob/d98e054abd8ea172bbd47a81655ef300aeae7f87/blueprints/ember-bootstrap/index.js#L103 Maybe I'm being blocked here? https://github.com/ember-bootstrap/ember-bootstrap/blob/d98e054abd8ea172bbd47a81655ef300aeae7f87/blueprints/ember-bootstrap/index.js#L57

package.json

{
  "name": "appli",
  "version": "1.0.0",
  "private": true,
  "description": "Small description for appli goes here",
  "repository": "",
  "license": "MIT",
  "author": "",
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "build": "ember build",
    "lint:hbs": "ember-template-lint .",
    "lint:js": "eslint .",
    "start": "ember serve",
    "test": "ember test"
  },
  "devDependencies": {
    "@ember/jquery": "^1.1.0",
    "@ember/optional-features": "^2.0.0",
    "@ember/test-helpers": "^2.6.0",
    "@glimmer/component": "^1.0.4",
    "@glimmer/tracking": "^1.0.4",
    "babel-eslint": "^10.1.0",
    "bootstrap": "^4.6.0",
    "bootstrap-less-port": "^2.5.1",
    "bootstrap-datepicker": "1.4.0",
    "bootstrap-select": "1.7.4",
    "broccoli-asset-rev": "^3.0.0",
    "browserslist": "^4.21.0",
    "codemirror": "^5.50.2",
    "ember-ajax": "^5.0.0",
    "ember-auto-import": "^1.12.0",
    "ember-bootstrap": "^4.9.0",
    "ember-cli": "^3.28.6",
    "ember-cli-app-version": "^5.0.0",
    "ember-cli-babel": "^7.26.10",
    "ember-cli-dependency-checker": "^3.2.0",
    "ember-cli-file-saver": "^1.2.4",
    "ember-cli-htmlbars": "^5.7.2",
    "ember-cli-inject-live-reload": "^2.1.0",
    "ember-cli-sri": "^2.1.1",
    "ember-cli-terser": "^4.0.2",
    "ember-copy": "^2.0.1",
    "ember-data": "^3.28.6",
    "ember-export-application-global": "^2.0.1",
    "ember-fetch": "^8.1.1",
    "ember-load-initializers": "^2.1.2",
    "ember-maybe-import-regenerator": "^0.1.6",
    "ember-moment": "^9.0.1",
    "ember-page-title": "^6.2.2",
    "ember-qunit": "^5.1.5",
    "ember-resolver": "^8.0.3",
    "ember-source": "~3.28.8",
    "ember-template-lint": "^3.15.0",
    "ember-welcome-page": "^4.1.0",
    "eslint": "^7.32.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-ember": "^10.5.8",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-prettier": "^3.4.1",
    "eslint-plugin-qunit": "^6.2.0",
    "handlebars": "3.0.3",
    "loader.js": "^4.7.0",
    "moment-duration-format": "2.2.2",
    "npm-run-all": "^4.1.5",
    "prettier": "^2.5.1",
    "qunit": "^2.17.2",
    "qunit-dom": "^1.6.0",
    "select2": "4.0.4",
    "underscore": "1.9.1",
    "vis": "4.21.0"
  },
  "engines": {
    "node": "12.* || 14.* || >= 16"
  },
  "dependencies": {
    "datatables.net-dt": "^1.10.20",
    "datatables.net-plugins": "^1.10.20",
    "datatables.net-rowgroup-dt": "^1.1.1",
    "less": "^3.13.1"
  },
  "ember": {
    "edition": "octane"
  }
}

ember-cli-build.js

'use strict';

const EmberApp = require('ember-cli/lib/broccoli/ember-app');
var Funnel = require('broccoli-funnel');

module.exports = function(defaults) {
  let app = new EmberApp(defaults, {
    'ember-bootstrap': {
      bootstrapVersion: 4,
      importBootstrapCSS: false,

    },
    'lessOptions': {
      paths: ['node_modules/bootstrap/less'],
    }
  });

  ...

  return app.toTree([imgJquery]);

app.less

@import "bootstrap-less-port";
@import "theme";
@import "variables";
@import "panels";
@import (less) "style.css";
@import (less) "datatable.css";
@import (less) "charts.css";
@import (less) "select2.css";
@import (less) "timeline.css";
@import (less) "codemirror.css";
@import (less) "vis-helios.css";

Action: Running

npm run build

Expected: should generate the appli.css and vendor.css files within dist/assets

Observed: app.less and app.css.map are present vendor.css is present




vendredi 13 janvier 2023

Carousel between string and non-string version of package in my yarn.lock

I've had this issue for a long time and I'm finally done with it! I've got a single package in my app that, after each time yarn [install] is run it switches from the string version to the non-string version and vise versa in the yarn.lock file. If I check in the change and commit it, the next time I yarn, it switches back.

Here's the example

+ "ember-phone-input@github:cph/ember-phone-input#cph-modification":
- ember-phone-input@cph/ember-phone-input.git#cph-modification:

Anyone know of any settings to add to package.json do end this senseless psychic damage I'm taking 🙂




dimanche 8 janvier 2023

Mirage server GETs data but POST fails

I have the mirage models:

// mirage/models/country.js
import { Model, belongsTo, hasMany } from 'miragejs';

export default Model.extend({
    name: '',
    iso3166_1_alpha3: '',
    capitol_city: belongsTo('city', {inverse: null}),
    cities: hasMany('city', {inverse: 'country'})
});

and:

// mirage/models/city.js
import { Model, belongsTo } from 'miragejs';

export default Model.extend({
    name: '',
    country: belongsTo('country', {inverse: 'cities'})
});

and the serializer:

// mirage/serializers/application.js
import { camelize, capitalize, underscore } from '@ember/string';
import { JSONAPISerializer } from 'miragejs';

export default class ApplicationSerializer extends JSONAPISerializer
{
    alwaysIncludeLinkageData = true;

    keyForAttribute(attr) {
        return underscore(attr);
    };
    keyForRelationship(modelName) {
        return underscore(modelName);
    };
    typeKeyForModel(model) {
        return capitalize(camelize(model.modelName));
    };
};

When I run the tests:

import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import { setupMirage } from 'ember-cli-mirage/test-support';

module('Unit | Mirage | mirage models', function (hooks) {
  setupTest(hooks);
  setupMirage(hooks);

  test('it retrieves the country', async function (assert) {
    const server = this.server;
    let city = server.create('city', { id: '1', name: 'Paris' });

    server.create(
        'country',
        {
            id: 'FR',
            name: 'France',
            iso3166_1_alpha3: 'FRA',
            capitol_city: city
        }
    );

    let response = await fetch('/api/countries')
    assert.strictEqual(response.status, 200, "Should have created the model");
    let json = await response.json();
    assert.deepEqual(
        json,
        {
            data: [
                {
                    type: 'Country',
                    id: 'FR',
                    attributes: {
                        name: 'France',
                        iso3166_1_alpha3: 'FRA',
                    },
                    relationships: {
                        capitol_city: {data: {type: 'City', id: '1'}},
                        cities: {data: []},
                    }
                }
            ]
        }
    )
  });

  test('it creates the country', async function (assert) {
    const server = this.server;
    server.create('city', { id: '1', name: 'Paris' });

    let response = await fetch(
        '/api/countries',
        {
            method: 'POST',
            headers: {'Countent-Type': 'application/json'},
            body: JSON.stringify(
                {
                    data: {
                        id: 'FR',
                        type: 'Country',
                        attributes: {
                            iso3166_1_alpha3: 'FRA',
                            name: 'France',

                        },
                        relationships: {
                            capitol_city: { data: { type: 'City', id: '1'} },
                            cities: { data: [{ type: 'City', id: '1'}] }
                        }
                    }
                }
            )
        }
    );

    console.log((await response.json()).message);
    assert.strictEqual(response.status, 201, "Should have created the model");
  });
});

The first one passes and the second one fails with the message:

Mirage: You're passing the relationship 'capitol_city' to the 'country' model via a POST to '/api/countries', but you did not define the 'capitol_city' association on the 'country' model.

How can I get Mirage to recognise the capitol_city attribute on the model?