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(date-picker, input-date-picker): add numberingSystem property #5488

Merged
merged 20 commits into from
Oct 22, 2022
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/components/date-picker-day/date-picker-day.e2e.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
import { disabled } from "../../tests/commonTests";
import { newProgrammaticE2EPage } from "../../tests/utils";
import { numberStringFormatter } from "../../utils/locale";

describe("calcite-date-picker-day", () => {
it("can be disabled", async () => {
numberStringFormatter.numberFormatOptions = {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this needed for the disabled test?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah numberFormatOptions needs to be set at some point with the way the class is currently configured because all of the initialization happens in its setter.

numberFormatOptions is always set in components (or their parents in the case of date-picker-day) with the values of the lang/numberingSystem props.

I could add a constructor to the class to initialize values with the default numberingSystem/lang, but that's just an extra iteration we don't need in the actual components. What do you think?

Copy link
Member Author

@benelan benelan Oct 21, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or I could just return the localize/delocalize methods' params if numberFormatOptions isn't set, which would effectively assume lang === "en && numberingSystem === "latn". e.g.

localize = (numberString: string) =>
    Object.keys(this._numberFormatOptions).length
      ? doFormattyStuff()
      : numberString;

It would be the equivolent outcome as adding a constructor and actually populating the internal properties based on defaults, but without the extra formatter creations.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went with my second comment ☝️

Now numberStringFormatter.numberFormatOptions only needs to be set when the lang and numberingSystem props are not their default values ("en" and "latn" respectively). This means that for a good portion of our users, we won't be initializing a formatter at all.

That's down from 10+ formatters created/destroyed for each character typed in calcite-input alone 🚀

locale: "ar",
numberingSystem: "arab",
useGrouping: false
};

const page = await newProgrammaticE2EPage();
await page.evaluate(() => {
const dateEl = document.createElement("calcite-date-picker-day") as HTMLCalciteDatePickerDayElement;
dateEl.active = true;
dateEl.day = 3;
dateEl.localeData = { numerals: "0123456789" } as HTMLCalciteDatePickerDayElement["localeData"];
document.body.append(dateEl);
});
await page.waitForChanges();
Expand Down
13 changes: 3 additions & 10 deletions src/components/date-picker-day/date-picker-day.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ import {
} from "@stencil/core";

import { getElementDir } from "../../utils/dom";
import { DateLocaleData } from "../date-picker/utils";
import { Scale } from "../interfaces";
import { CSS_UTILITY } from "../../utils/resources";
import { InteractiveComponent, updateHostInteraction } from "../../utils/interactive";
import { isActivationKey } from "../../utils/key";
import { numberStringFormatter } from "../../utils/locale";

@Component({
tag: "calcite-date-picker-day",
Expand All @@ -38,7 +38,7 @@ export class DatePickerDay implements InteractiveComponent {
//--------------------------------------------------------------------------

/** Day of the month to be shown. */
@Prop() day: number;
@Prop() day!: number;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎉


/** Date is outside of range and can't be selected */
@Prop({ reflect: true }) disabled = false;
Expand Down Expand Up @@ -67,10 +67,6 @@ export class DatePickerDay implements InteractiveComponent {
/** Date is actively in focus for keyboard navigation */
@Prop({ reflect: true }) active = false;

/** CLDR data for current locale */
/* @internal */
@Prop() localeData: DateLocaleData;

/** specify the scale of the date picker */
@Prop({ reflect: true }) scale: Scale;

Expand Down Expand Up @@ -123,10 +119,7 @@ export class DatePickerDay implements InteractiveComponent {
//
//--------------------------------------------------------------------------
render(): VNode {
const formattedDay = String(this.day)
.split("")
.map((i) => this.localeData.numerals[i])
.join("");
const formattedDay = numberStringFormatter.localize(String(this.day));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!

const dir = getElementDir(this.el);
return (
<Host onClick={this.onClick} onKeyDown={this.keyDownHandler} role="gridcell">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,14 @@ import {
Watch,
Fragment
} from "@stencil/core";
import {
dateFromRange,
nextMonth,
prevMonth,
localizeNumber,
parseNumber,
getOrder
} from "../../utils/date";
import { dateFromRange, nextMonth, prevMonth, getOrder } from "../../utils/date";

import { DateLocaleData } from "../date-picker/utils";
import { Scale } from "../interfaces";
import { HeadingLevel, Heading } from "../functional/Heading";
import { BUDDHIST_CALENDAR_YEAR_OFFSET } from "./resources";
import { isActivationKey } from "../../utils/key";
import { numberStringFormatter } from "../../utils/locale";

@Component({
tag: "calcite-date-picker-month-header",
Expand Down Expand Up @@ -224,15 +218,17 @@ export class DatePickerMonthHeader {
const { localeData } = this;
const buddhistCalendar = localeData["default-calendar"] === "buddhist";
const yearOffset = buddhistCalendar ? BUDDHIST_CALENDAR_YEAR_OFFSET : 0;
return localizeNumber(year + yearOffset, localeData);

return numberStringFormatter.localize((year + yearOffset).toString());
}

private parseCalendarYear(year: string): string {
const { localeData } = this;
const buddhistCalendar = localeData["default-calendar"] === "buddhist";
const yearOffset = buddhistCalendar ? BUDDHIST_CALENDAR_YEAR_OFFSET : 0;

return localizeNumber(parseNumber(year, localeData) - yearOffset, localeData);
const parsedYear = Number(numberStringFormatter.delocalize(year)) - yearOffset;
return numberStringFormatter.localize(parsedYear.toString());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick: using template literals can be more concise. Up to you.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah you're right template literals are cleaner here. I use toString() out of habit because I love method chaining lol. Fixing!

}

private onYearChange = (event: Event): void => {
Expand Down Expand Up @@ -283,8 +279,8 @@ export class DatePickerMonthHeader {
localizedYear: string;
offset?: number;
}): Date {
const { min, max, activeDate, localeData } = this;
const parsedYear = parseNumber(localizedYear, localeData);
const { min, max, activeDate } = this;
const parsedYear = Number(numberStringFormatter.delocalize(localizedYear));
const length = parsedYear.toString().length;
const year = isNaN(parsedYear) ? false : parsedYear + offset;
const inRange =
Expand Down
1 change: 0 additions & 1 deletion src/components/date-picker-month/date-picker-month.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,6 @@ export class DatePickerMonth {
endOfRange={this.isEndOfRange(date)}
highlighted={this.betweenSelectedRange(date)}
key={date.toDateString()}
localeData={this.localeData}
onCalciteDaySelect={this.daySelect}
onCalciteInternalDayHover={this.dayHover}
range={!!this.startDate && !!this.endDate && !sameDate(this.startDate, this.endDate)}
Expand Down
24 changes: 14 additions & 10 deletions src/components/date-picker/date-picker.stories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,24 +137,22 @@ export const simple = stepStory(
(): string => html`<div style="width: 400px">${create("calcite-date-picker", createAttributes())}</div>`,

createSteps("calcite-date-picker")
.snapshot("Default")

.executeScript(
setKnobs({
story: "components-controls-datepicker--simple",
knobs: [{ name: "dir", value: "rtl" }]
knobs: [{ name: "value", value: "2000-01-01" }]
})
)
.snapshot("Default RTL")
.snapshot("Default")

.executeScript(
setKnobs({
story: "components-controls-datepicker--simple",
knobs: []
knobs: [{ name: "dir", value: "rtl" }]
})
)
.executeScript(setTheme("dark"))
.snapshot("Dark")
.snapshot("Dark Theme RTL")

.executeScript(setTheme("light"))
.executeScript(
Expand Down Expand Up @@ -218,18 +216,24 @@ export const simple = stepStory(
.executeScript(
setKnobs({
story: "components-controls-datepicker--simple",
knobs: [{ name: "locale", value: "ru" }]
knobs: [
{ name: "locale", value: "ar" },
{ name: "numbering-system", value: "arab" }
]
})
)
.snapshot("ru locale")
.snapshot("ar locale/numberingSystem")

.executeScript(
setKnobs({
story: "components-controls-datepicker--simple",
knobs: [{ name: "locale", value: "th" }]
knobs: [
{ name: "locale", value: "th" },
{ name: "numbering-system", value: "thai" }
]
})
)
.snapshot("th locale (Buddhist calendar)")
.snapshot("th locale/numberingSystem (Buddhist calendar)")

.executeScript(
setKnobs({
Expand Down
26 changes: 25 additions & 1 deletion src/components/date-picker/date-picker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,13 @@ import { HeadingLevel } from "../functional/Heading";

import { DateRangeChange } from "./interfaces";
import { HEADING_LEVEL, TEXT } from "./resources";
import { connectLocalized, disconnectLocalized, LocalizedComponent } from "../../utils/locale";
import {
connectLocalized,
disconnectLocalized,
LocalizedComponent,
NumberingSystem,
numberStringFormatter
} from "../../utils/locale";

@Component({
assetsDirs: ["assets"],
Expand Down Expand Up @@ -145,6 +151,12 @@ export class DatePicker implements LocalizedComponent {
*/
@Prop() locale?: string;

/**
* Specifies the Unicode numeral system used by the component for localization. This property cannot be dynamically changed.
*
*/
@Prop({ reflect: true }) numberingSystem?: NumberingSystem;

/** specify the scale of the date picker */
@Prop({ reflect: true }) scale: "s" | "m" | "l" = "m";

Expand Down Expand Up @@ -233,6 +245,12 @@ export class DatePicker implements LocalizedComponent {
if (this.max) {
this.maxAsDate = dateFromISO(this.max);
}

numberStringFormatter.numberFormatOptions = {
numberingSystem: this.numberingSystem,
locale: this.effectiveLocale,
useGrouping: false
};
}

disconnectedCallback(): void {
Expand Down Expand Up @@ -345,6 +363,12 @@ export class DatePicker implements LocalizedComponent {
return;
}

numberStringFormatter.numberFormatOptions = {
numberingSystem: this.numberingSystem,
locale: this.effectiveLocale,
useGrouping: false
};

this.localeData = await getLocaleData(this.effectiveLocale);
}

Expand Down
27 changes: 19 additions & 8 deletions src/components/input-date-picker/input-date-picker.stories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,17 +69,28 @@ export const flipPlacements_TestOnly = (): string => html`
</script>
`;

export const laoNumberingSystem_TestOnly = (): string => html`
<div dir="rtl" style="width: 400px">
<calcite-input-date-picker
scale="m"
value="1/1/1"
min="2016-08-09"
max="2023-12-18"
lang="zh-CN"
numbering-system="laoo"
></calcite-input-date-picker
</div>`;

export const darkThemeRTL_TestOnly = (): string => html`
<div dir="rtl" style="width: 400px">
<calcite-input-date-picker
scale="${select("scale", ["s", "m", "l"], "m")}"
value="${text("value", "2020-12-12")}"
min="${text("min", "2016-08-09")}"
max="${text("max", "2023-12-18")}"
lang="${select("locale", locales, "en")}"
intl-next-month="${text("intl-next-month", "Next month")}"
intl-prev-month="${text("intl-prev-month", "Previous month")}"
range="${boolean("range", false)}"
scale="m"
value="2020-12-12"
min="2016-08-09"
max="2023-12-18"
lang=en"
intl-next-month="Next month"
intl-prev-month="Prevoius month"
></calcite-input-date-picker
</div>
`;
Expand Down
Loading