Skip to content

Commit

Permalink
Introduce percentage field
Browse files Browse the repository at this point in the history
  • Loading branch information
richardhjtan committed Dec 13, 2024
1 parent dc962f1 commit 38c1b78
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"alice@email.com",
"dan@email.com"
],
"percentage": 100.159393,
"contactLink": {
"label": "Email",
"value": "alice@email.com"
Expand Down
2 changes: 2 additions & 0 deletions packages/experiments-realm/experiments_fields_preview.gts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { PhoneField } from './phone';
import { UrlField } from './url';
import { WebsiteField } from './website';
import { Address as AddressField } from './address';
import { PercentageField } from './percentage';
import {
CardDef,
field,
Expand All @@ -27,6 +28,7 @@ export class ExperimentsFieldsPreview extends CardDef {
@field email = contains(EmailField);
@field emails = containsMany(EmailField);
@field phone = contains(PhoneField);
@field percentage = contains(PercentageField);
@field contactLink = contains(ContactLinkField);
@field contactLinks = containsMany(ContactLinkField);
@field featuredImage = contains(FeaturedImageField);
Expand Down
43 changes: 43 additions & 0 deletions packages/experiments-realm/percentage.gts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Component } from 'https://cardstack.com/base/card-api';
import NumberField from 'https://cardstack.com/base/number';

import PercentageIcon from '@cardstack/boxel-icons/square-percentage';

const nearestDecimal = (num: number, decimalPlaces: number) => {
// https://stackoverflow.com/questions/11832914/how-to-round-to-at-most-2-decimal-places-if-necessary
const factorOfTen = Math.pow(10, decimalPlaces);
return Math.round(num * factorOfTen + Number.EPSILON) / factorOfTen;
};

const displayPercentage = (num: number) => {
return `${nearestDecimal(num, 2)}%`;
};

export class PercentageField extends NumberField {
static icon = PercentageIcon;
static displayName = 'Percentage';

static isolated = class Isolated extends Component<typeof PercentageField> {
<template>
{{#if @model}}
{{displayPercentage @model}}
{{/if}}
</template>
};

static atom = class Atom extends Component<typeof PercentageField> {
<template>
{{#if @model}}
{{displayPercentage @model}}
{{/if}}
</template>
};

static embedded = class Embedded extends Component<typeof PercentageField> {
<template>
{{#if @model}}
{{displayPercentage @model}}
{{/if}}
</template>
};
}

0 comments on commit 38c1b78

Please sign in to comment.