Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: Make ion-input counter formatter more beginner-friendly #28694

Closed
3 tasks done
johannesvollmer opened this issue Dec 13, 2023 · 8 comments
Closed
3 tasks done

feat: Make ion-input counter formatter more beginner-friendly #28694

johannesvollmer opened this issue Dec 13, 2023 · 8 comments
Labels

Comments

@johannesvollmer
Copy link

johannesvollmer commented Dec 13, 2023

Prerequisites

Describe the Feature Request

We suggest that the counterFormatter attribute on ion-input can be passed an interface, in addition to a callback. This will avoid a potential pitfall, thus making ionic more beginner friendly.

We added internationalization to our ion input counter formatter. But the current design is inconvenient, as it requires the use of bind or an unidiomatic arrow function in the class.

Describe the Use Case

The example in the documentation is error-prone:

<ion-input
  [counter]="true"
  maxlength="20"
  [counterFormatter]="customCounterFormatter"
></ion-input>
@Component(...)
export class ExampleComponent {
  customCounterFormatter(inputLength: number, maxLength: number) {
    return `${maxLength - inputLength} characters remaining`;
  }
}

As soon as you add a class member, the code breaks, as the function looses the this context. It's not beginner friendly, and results in combersome code.

For example, when adding internationalization:

export class ExampleComponent {
  translated: string = "characters remaining" // probably injected dynamically

  customCounterFormatter(inputLength: number, maxLength: number) {
    return `${maxLength - inputLength} {this.translated}`;
  }
}

This now results in an error: Exception in provided 'counterFormatter', as this is not bound when ionic calls the formatter callback.

Describe Preferred Solution

Introduce an

interface CounterFormatter {
    format(current: number, limit: number): string
}

It should be possible to pass an object of type CounterFormatter to the counterFormatter attribute on the ion-input.
We prefer this solution because it is the most explicit one.

Describe Alternatives

Either

  • callback.bind(component) to the component before calling the callback inside the ion-input (100% backwards compatible, but not as explicit)
  • change the example to include a call bind or an arrow function

Related Code

No response

Additional Information

This change can also be applied to all callbacks, for example PinFormatter on ion-range, or ion-textarea.

@ionitron-bot ionitron-bot bot added the triage label Dec 13, 2023
@hakimio
Copy link

hakimio commented Dec 13, 2023

Another possibility could be to use <ng-template>:

<ion-input
  [counter]="true"
  maxlength="20"
>
    <ng-template 
        counterFormatter 
        let-maxLength="maxLength" 
        let-currentLength="currentLength"
    >
        <b>{{ maxLength - currentLength }}</b> {{ translated }}
    </ng-template>
</ion-input>

@liamdebeasi
Copy link
Contributor

Thanks for the report. Can you please provide a reproduction of the original issues you are seeing? In particular, I'd like to see what happens when you do not use bind.

@liamdebeasi liamdebeasi added the needs: reply the issue needs a response from the user label Dec 13, 2023
@ionitron-bot ionitron-bot bot removed the triage label Dec 13, 2023
@hakimio
Copy link

hakimio commented Dec 13, 2023

image

image

https://stackblitz.com/edit/angular-zvtvh7?file=src%2Fapp%2Fexample.component.ts

@ionitron-bot ionitron-bot bot added triage and removed needs: reply the issue needs a response from the user labels Dec 13, 2023
@liamdebeasi
Copy link
Contributor

Thanks for the additional information. While I understand this behavior is not desired, Ionic is working correctly here. The customCounterFormatter is being called in a difference scope outside of ExampleComponent, so it will not have access to the ExampleComponent scope by default. This is how this works in JavaScript.

I recommend reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this as it has a lot of helpful information regarding this behavior. In particular:

When a function is passed as a callback, the value of this depends on how the callback is called, which is determined by the implementor of the API.

Setting .bind(this) will work here as you are binding the value of this which will be ExampleComponent. Arrow functions also work because a new this binding is not created.

@liamdebeasi liamdebeasi closed this as not planned Won't fix, can't repro, duplicate, stale Dec 15, 2023
@johannesvollmer
Copy link
Author

johannesvollmer commented Dec 15, 2023

Sorry if the issue is not formulated clear enough. We understand how this works. This is not a bug in the ionic code, you're right with that. Instead it's a pitfall that everyone using ionic must account for, instead of it 'just working'.

When a function is passed as a callback, the value of this depends on how the callback is called, which is determined by the implementor of the API.

The one calling the callback is the ionic framework. Therefore it is the responsibility of ionic to call the callback with the appropriate this value. Currently, ionic does not set this on the callback.

One of the proposed solutions is that ionic binds the component to the callback. This would make the code above work automatically.

in ionic, some code is calling the user-provided callback:

private renderCounter() {
const { counter, maxlength, counterFormatter, value } = this;
if (counter !== true || maxlength === undefined) {
return;
}
return <div class="counter">{getCounterText(value, maxlength, counterFormatter)}</div>;
}

instead, ionic should bind the appropriate this value:

getCounterText(value, maxlength, counterFormatter?.bind(componentModel))

Because the official ionic docs show us that the formatter should be located in the component model, it only makes sense to bind that component model as the callback's this. Most likely, the bind call should already happen when the callback is first retrieved from the element attributes. This way, ionic doesn't need to carry around a reference to the element.

If this is not possible, the interface could accept an interface instead of a contextless function, which would automatically use the correct this value. And if this is not possible, at least the documentation can be changed to point out this behaviour.
Example:

<ion-input label="Default counter" labelPlacement="floating" [counter]="true" maxlength="20"></ion-input>

<ion-input
  id="custom-input"
  label="Custom Counter Format"
  labelPlacement="floating"
  [counter]="true"
  maxlength="20"
  [counterFormatter]="customCounterFormatter.bind(this)"
></ion-input>

Can you re-open the issue or should we create a new one?

@liamdebeasi
Copy link
Contributor

When a function is passed as a callback, the value of this depends on how the callback is called, which is determined by the implementor of the API.

The one calling the callback is the ionic framework. Therefore it is the responsibility of ionic to call the callback with the appropriate this value. Currently, ionic does not set this on the callback.

How the callback is called is determined by the implementer of the API, not the callback caller. I'll use the MDN example to clarify:

function logThis() {
  "use strict";
  console.log(this);
}

[1, 2, 3].forEach(logThis); // undefined, undefined, undefined

The API is forEach, and the implementer is the person writing the code and passing logThis. That person would be responsible for setting .bind(this) (or using an arrow function). All forEach does is call the function that it was passed.

In the context of Ionic, the API is counterFormatter, and the implementer is the application developer. All counterFormatter does is call the function that it was passed. Ionic has no way of knowing about the calling context (the Angular component's class) unless it's provided by the developer. Doing counterFormatter?.bind(this) inside of ion-input would cause this to refer to the ion-input class, not the Angular component's class.


In any event, I think it's worth updating the documentation to clarify this behavior. I can work on getting a PR up to note this.

@johannesvollmer
Copy link
Author

I just think it's stupid that Angular forces you to use classes, but at the same time doesn't bind instance methods automatically.

In this angular code:

<ion-input
[counterFormatter]="customCounterFormatter"
></ion-input>

@Component(...)
export class ExampleComponent {
  customCounterFormatter(...) { ... }
}

The custom counter formatter is looked up from the typescript component - but it's not automatically bound to the component. This seems stupid to me, because Angular does look into our ExampleComponent instance either way, but then doesn't go all the way.

If Angular worked like this: formatter="this.formatter", then it would be obvious that the caller needs to bind manually.

I see it's the fault of Angular, and I understand if ionic doesn't want to fix their issues.

github-merge-queue bot pushed a commit that referenced this issue Dec 19, 2023
Issue number: N/A

---------

<!-- Please do not submit updates to dependencies unless it fixes an
issue. -->

<!-- Please try to limit your pull request to one type (bugfix, feature,
etc). Submit multiple pull requests if needed. -->

## What is the current behavior?
<!-- Please describe the current behavior that you are modifying. -->

In #28694 there was
some confusion around how to access `this` inside of a callback function
passed to a property on Ionic components. The root issue was due to how
the `this` context is determined with developers being responsible for
setting the appropriate `this` context.

## What is the new behavior?
<!-- Please describe the behavior or changes that are being added by
this PR. -->

- While this isn't an Ionic bug, I think it's worth calling out this
behavior so developers are aware of how to account for it.

## Does this introduce a breaking change?

- [ ] Yes
- [x] No

<!--
  If this introduces a breaking change:
1. Describe the impact and migration path for existing applications
below.
  2. Update the BREAKING.md file with the breaking change.
3. Add "BREAKING CHANGE: [...]" to the commit description when merging.
See
https://github.com/ionic-team/ionic-framework/blob/main/.github/CONTRIBUTING.md#footer
for more information.
-->


## Other information

<!-- Any other information that is important to this PR such as
screenshots of how the component looks before and after the change. -->


Note: The link in the docs will not work until
ionic-team/ionic-docs#3333 is merged.

---------

Co-authored-by: Amanda Johnston <[email protected]>
Copy link

ionitron-bot bot commented Jan 15, 2024

Thanks for the issue! This issue is being locked to prevent comments that are not relevant to the original issue. If this is still an issue with the latest version of Ionic, please create a new issue and ensure the template is fully filled out.

@ionitron-bot ionitron-bot bot locked and limited conversation to collaborators Jan 15, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

3 participants