date-fns#subMonths TypeScript Examples

The following examples show how to use date-fns#subMonths. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GraphUtils.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
static reduceByAddingEmptyMonth(
        splitList: GraphSplit[],
        fromDate: Date,
        toDate: Date,
        key: string,
    ): GraphSplit[] {
        const result: GraphSplit[] = [];
        const startOfMonthFromDate = startOfMonth(fromDate);
        const toDateStartOfMonth = startOfMonth(toDate);
        let currentDate = toDateStartOfMonth;
        let index = 0;
        const ids = CashAccountUtils.extractKey(key);
        while (currentDate >= startOfMonthFromDate) {
            const currentSplit = splitList[index];
            if (currentSplit && isSameMonth(currentSplit.transactionDate, currentDate)) {
                result.push(currentSplit);
                index++;
            } else {
                result.push({
                    accountId: ids.accountId,
                    currencyId: ids.currencyId,
                    amount: 0,
                    transactionDate: currentDate,
                    originalCurrencyId: ids.currencyId,
                    originalAmount: 0,
                });
            }
            currentDate = subMonths(currentDate, 1);
        }
        return result;
    }
Example #2
Source File: MonthlyCalendar.tsx    From react-calendar with MIT License 6 votes vote down vote up
MonthlyNav = () => {
  let { locale, currentMonth, onCurrentMonthChange } = useMonthlyCalendar();

  return (
    <div className="rc-flex rc-justify-end rc-mb-4">
      <button
        onClick={() => onCurrentMonthChange(subMonths(currentMonth, 1))}
        className="rc-cursor-pointer"
      >
        Previous
      </button>
      <div
        className="rc-ml-4 rc-mr-4 rc-w-32 rc-text-center"
        aria-label="Current Month"
      >
        {format(
          currentMonth,
          getYear(currentMonth) === getYear(new Date()) ? 'LLLL' : 'LLLL yyyy',
          { locale }
        )}
      </div>
      <button
        onClick={() => onCurrentMonthChange(addMonths(currentMonth, 1))}
        className="rc-cursor-pointer"
      >
        Next
      </button>
    </div>
  );
}
Example #3
Source File: ProfilePage.tsx    From apps with GNU Affero General Public License v3.0 5 votes vote down vote up
after = subMonths(subDays(before, 2), 6)
Example #4
Source File: DateRangePicker.stories.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
StaticViewDates.args = {
  defaultViewDates: [subMonths(startOfToday(), 1), startOfToday()],
};
Example #5
Source File: PastTimePicker.stories.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
Absolute.args = {
  value: `abs:${getTime(subMonths(startOfToday(), 1))},${getTime(startOfToday())}`,
  onRangeSelect: (date: any, index: number) => console.log(date, index)
};
Example #6
Source File: AbsoluteRangePicker.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
function AbsoluteRangePicker({ disabledDate, timeRange, onSelect, onRangeSelect, onCancel }: RangePickerProps) {
  const [dates, setDates] = React.useState<[Date | undefined, Date | undefined]>(parseStartAndEndDate(timeRange));
  const prefixCls = usePrefixCls('range-panel__header');

  const locale = useLocale('StaticPastTimePicker');

  const { startDayText, endDayText, FromText, ToText } = {
    ...defaultLocale,
    ...locale,
  };

  const renderHeader = () => {
    const placeholder = [startDayText, endDayText];
    const dateString = formatDates(dates);
    const dateTexts = dateString?.split('-')?.map((d) => (d === ' ' ? undefined : d)) || [];
    const text = [dateTexts[0] ?? placeholder[0], dateTexts[1] ?? placeholder[1]];
    return <span className={`${prefixCls}__text`}>{`${FromText} ${text[0]} ${ToText} ${text[1]}`}</span>;
  };
  const handleDisabledDate = (current: Date) => disabledDate?.(current) || isAfter(current, startOfToday());
  const handleOnOK = () => {
    onSelect(`abs:${getTime(startOfDay(dates[0] as Date))},${getTime(endOfDay(dates[1] as Date))}`);
  };
  const handleOnSelect = (date: [Date, Date], index: number) => {
    setDates(date);
    onRangeSelect?.(date, index);
  }
  const endDay = dates[1] !== undefined && isValid(dates[1]) ? dates[1] : new Date();
  return (
    <InnerRangePanel
      disableOK={!isValid(dates[0]) || !isValid(dates[1])}
      header={renderHeader()}
      body={
        <StaticDateRangePicker
          defaultViewDates={[subMonths(startOfDay(endDay), 1), startOfDay(endDay)]}
          disabledDate={handleDisabledDate}
          onSelect={handleOnSelect}
          value={dates as [Date, Date]}
        />
      }
      onCancel={onCancel}
      onOK={handleOnOK}
    />
  );
}
Example #7
Source File: index.tsx    From apps with GNU Affero General Public License v3.0 4 votes vote down vote up
ProfilePage = ({ profile }: ProfileLayoutProps): ReactElement => {
  const { user, tokenRefreshed } = useContext(AuthContext);
  const fullHistory = useMedia([laptop.replace('@media ', '')], [true], false);
  const [selectedHistoryYear, setSelectedHistoryYear] = useState(0);
  const [before, after] = useMemo<[Date, Date]>(() => {
    if (!fullHistory) {
      const start = startOfTomorrow();
      return [start, subMonths(subDays(start, 2), 6)];
    }
    if (!selectedHistoryYear) {
      const start = startOfTomorrow();
      return [start, subYears(subDays(start, 2), 1)];
    }
    const selected = parseInt(dropdownOptions[selectedHistoryYear], 10);
    const startYear = new Date(selected, 0, 1);

    return [addDays(endOfYear(startYear), 1), startYear];
  }, [selectedHistoryYear]);
  const [readingHistory, setReadingHistory] =
    useState<ProfileReadingData>(null);

  const { data: remoteReadingHistory } = useQuery<ProfileReadingData>(
    ['reading_history', profile?.id, selectedHistoryYear],
    () =>
      request(`${apiUrl}/graphql`, USER_READING_HISTORY_QUERY, {
        id: profile?.id,
        before,
        after,
        version: 2,
        limit: 6,
      }),
    {
      enabled: !!profile && tokenRefreshed && !!before && !!after,
      refetchOnWindowFocus: false,
      refetchOnReconnect: false,
      refetchOnMount: false,
    },
  );

  useEffect(() => {
    if (remoteReadingHistory) {
      setReadingHistory(remoteReadingHistory);
    }
  }, [remoteReadingHistory]);

  const totalReads = useMemo(
    () =>
      readingHistory?.userReadHistory.reduce((acc, val) => acc + val.reads, 0),
    [readingHistory],
  );

  const { data: userStats } = useQuery<UserStatsData>(
    ['user_stats', profile?.id],
    () =>
      request(`${apiUrl}/graphql`, USER_STATS_QUERY, {
        id: profile?.id,
      }),
    {
      enabled: !!profile && tokenRefreshed,
    },
  );

  const isSameUser = profile?.id === user?.id;

  const commentsSection = (
    <CommentsSection
      userId={profile?.id}
      tokenRefreshed={tokenRefreshed}
      isSameUser={isSameUser}
      numComments={userStats?.userStats?.numComments}
    />
  );

  const postsSection = (
    <PostsSection
      userId={profile?.id}
      isSameUser={isSameUser}
      numPosts={userStats?.userStats?.numPosts}
    />
  );

  return (
    <div className="flex relative flex-col items-stretch">
      {readingHistory?.userReadingRankHistory && (
        <>
          <ActivityContainer>
            <ActivitySectionHeader
              title="Weekly goal"
              subtitle="Learn how we count"
              clickableTitle="weekly goals"
              link="https://docs.daily.dev/docs/your-profile/weekly-goal"
            >
              <Dropdown
                className="hidden laptop:block ml-auto w-32 min-w-fit"
                selectedIndex={selectedHistoryYear}
                options={dropdownOptions}
                onChange={(val, index) => setSelectedHistoryYear(index)}
                buttonSize="small"
              />
            </ActivitySectionHeader>
            <div className="grid grid-cols-5 tablet:grid-cols-3 tablet:gap-2 gap-x-1 gap-y-3 tablet:max-w-full max-w-[17rem]">
              {RANKS.map((rank) => (
                <RankHistory
                  key={rank.level}
                  rank={rank.level}
                  rankName={rank.name}
                  count={
                    readingHistory.userReadingRankHistory.find(
                      (history) => history.rank === rank.level,
                    )?.count ?? 0
                  }
                />
              ))}
            </div>
          </ActivityContainer>
          <ActivityContainer>
            <ActivitySectionHeader
              title="Top tags by reading days"
              subtitle="Learn how we count"
              clickableTitle="top tags"
              link="https://docs.daily.dev/docs/your-profile/weekly-goal"
            />
            <div className="grid grid-cols-1 tablet:grid-cols-2 gap-3 tablet:gap-x-10 tablet:max-w-full max-w-[17rem]">
              {readingHistory.userMostReadTags?.map((tag) => (
                <ReadingTagProgress key={tag.value} tag={tag} />
              ))}
            </div>
          </ActivityContainer>
          <ActivityContainer>
            <ActivitySectionTitle>
              Articles read in{' '}
              {getHistoryTitle(fullHistory, selectedHistoryYear)}
              {totalReads >= 0 && (
                <ActivitySectionTitleStat>
                  ({totalReads})
                </ActivitySectionTitleStat>
              )}
            </ActivitySectionTitle>
            <CalendarHeatmap
              startDate={after}
              endDate={before}
              values={readingHistory.userReadHistory}
              valueToCount={readHistoryToValue}
              valueToTooltip={readHistoryToTooltip}
            />
            <div className="flex justify-between items-center mt-4 typo-footnote">
              <div className="text-theme-label-quaternary">
                Inspired by GitHub
              </div>
              <div className="flex items-center">
                <div className="mr-2">Less</div>
                <div
                  className="mr-0.5 w-2 h-2 border border-theme-divider-quaternary"
                  style={{ borderRadius: '0.1875rem' }}
                />
                <div
                  className="mr-0.5 w-2 h-2 bg-theme-label-disabled"
                  style={{ borderRadius: '0.1875rem' }}
                />
                <div
                  className="mr-0.5 w-2 h-2 bg-theme-label-quaternary"
                  style={{ borderRadius: '0.1875rem' }}
                />
                <div
                  className="mr-0.5 w-2 h-2 bg-theme-label-primary"
                  style={{ borderRadius: '0.1875rem' }}
                />
                <div className="ml-2">More</div>
              </div>
            </div>
          </ActivityContainer>
        </>
      )}
      {userStats?.userStats && (
        <>
          <AuthorStats userStats={userStats.userStats} />
          {postsSection}
          {commentsSection}
        </>
      )}
    </div>
  );
}
Example #8
Source File: index.test.tsx    From gio-design with Apache License 2.0 4 votes vote down vote up
describe('Testing StaticDatePicker ', () => {
  it('without params', () => {
    const { container } = render(<StaticDateRangePicker />);
    expect(container.querySelector('div[class="gio-date-range-picker"]')).toBeTruthy();
  });

  it('onPanelChange has onPanelChange', () => {
    const { container } = render(
      <StaticDateRangePicker
        disabledDate={(current: Date) => current.getTime() > new Date().getTime()}
        defaultViewDates={[subMonths(startOfToday(), 1), startOfToday()]}
      />
    );

    fireEvent.click(
      container.querySelector('.gio-date-range-picker__left button[class="gio-picker-header-super-prev-btn"]')
    );

    expect(container.querySelector('div[class="gio-picker-cell-inner"]')).toBeTruthy();

    fireEvent.click(
      container.querySelector('.gio-date-range-picker__right button[class="gio-picker-header-super-next-btn"]')
    );

    expect(container.querySelector('div[class="gio-picker-cell-inner"]')).toBeTruthy();
  });

  it('left right', () => {
    const { container } = render(
      <StaticDateRangePicker defaultValue={[new Date('2022-03-01'), new Date('2022-04-01')]} />
    );

    fireEvent.click(container.querySelector('td[title="2022-04-02"] .gio-picker-cell-inner'));

    fireEvent.click(container.querySelector('td[title="2022-04-11"] .gio-picker-cell-inner'));

    expect(container.querySelector('div[class="gio-picker-cell-inner"]')).toBeTruthy();
  });

  it('has function', () => {
    const { container } = render(
      <StaticDateRangePicker
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        onDateMouseEnter={() => {}}
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        onDateMouseLeave={() => {}}
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        onSelect={() => {}}
        defaultValue={[new Date('2022-03-01'), new Date('2022-04-01')]}
      />
    );

    fireEvent.click(container.querySelector('td[title="2022-04-02"] .gio-picker-cell-inner'));

    fireEvent.mouseEnter(container.querySelector('td[title="2022-04-10"] .gio-picker-cell-inner'));

    fireEvent.mouseLeave(container.querySelector('td[title="2022-04-10"] .gio-picker-cell-inner'));

    fireEvent.click(container.querySelector('td[title="2022-04-11"] .gio-picker-cell-inner'));

    expect(container.querySelector('div[class="gio-picker-cell-inner"]')).toBeTruthy();
  });

  it('not function', () => {
    const { container } = render(
      <StaticDateRangePicker defaultValue={[new Date('2022-03-01'), new Date('2022-04-01')]} />
    );

    fireEvent.mouseEnter(container.querySelector('td[title="2022-04-10"] .gio-picker-cell-inner'));

    fireEvent.mouseLeave(container.querySelector('td[title="2022-04-10"] .gio-picker-cell-inner'));

    expect(container.querySelector('div[class="gio-picker-cell-inner"]')).toBeTruthy();
  });

  it('has defaultViewDates', () => {
    const { container } = render(
      <StaticDateRangePicker defaultValue={[new Date('2022-03-01'), new Date('2022-04-01')]} />
    );

    fireEvent.mouseEnter(container.querySelector('td[title="2022-04-10"] .gio-picker-cell-inner'));

    fireEvent.mouseLeave(container.querySelector('td[title="2022-04-10"] .gio-picker-cell-inner'));

    expect(container.querySelector('div[class="gio-picker-cell-inner"]')).toBeTruthy();
  });
});
Example #9
Source File: VisitorListAside.tsx    From ra-enterprise-demo with MIT License 4 votes vote down vote up
Aside: FC = () => (
    <Card>
        <CardContent>
            <FilterLiveSearch />
            <span id="persisted-queries">
                <SavedQueriesList />
            </span>
            <FilterList
                label="resources.customers.filters.last_visited"
                icon={<AccessTimeIcon />}
            >
                <FilterListItem
                    label="resources.customers.filters.today"
                    value={{
                        last_seen_gte: endOfYesterday().toISOString(),
                        last_seen_lte: undefined,
                    }}
                />
                <FilterListItem
                    label="resources.customers.filters.this_week"
                    value={{
                        last_seen_gte: startOfWeek(new Date()).toISOString(),
                        last_seen_lte: undefined,
                    }}
                />
                <FilterListItem
                    label="resources.customers.filters.last_week"
                    value={{
                        last_seen_gte: subWeeks(
                            startOfWeek(new Date()),
                            1
                        ).toISOString(),
                        last_seen_lte: startOfWeek(new Date()).toISOString(),
                    }}
                />
                <FilterListItem
                    label="resources.customers.filters.this_month"
                    value={{
                        last_seen_gte: startOfMonth(new Date()).toISOString(),
                        last_seen_lte: undefined,
                    }}
                />
                <FilterListItem
                    label="resources.customers.filters.last_month"
                    value={{
                        last_seen_gte: subMonths(
                            startOfMonth(new Date()),
                            1
                        ).toISOString(),
                        last_seen_lte: startOfMonth(new Date()).toISOString(),
                    }}
                />
                <FilterListItem
                    label="resources.customers.filters.earlier"
                    value={{
                        last_seen_gte: undefined,
                        last_seen_lte: subMonths(
                            startOfMonth(new Date()),
                            1
                        ).toISOString(),
                    }}
                />
            </FilterList>

            <FilterList
                label="resources.customers.filters.has_ordered"
                icon={<MonetizationOnIcon />}
            >
                <FilterListItem
                    label="ra.boolean.true"
                    value={{
                        nb_commands_gte: 1,
                        nb_commands_lte: undefined,
                    }}
                />
                <FilterListItem
                    label="ra.boolean.false"
                    value={{
                        nb_commands_gte: undefined,
                        nb_commands_lte: 0,
                    }}
                />
            </FilterList>

            <FilterList
                label="resources.customers.filters.has_newsletter"
                icon={<MailIcon />}
            >
                <FilterListItem
                    label="ra.boolean.true"
                    value={{ has_newsletter: true }}
                />
                <FilterListItem
                    label="ra.boolean.false"
                    value={{ has_newsletter: false }}
                />
            </FilterList>

            <FilterList
                label="resources.customers.filters.group"
                icon={<LocalOfferIcon />}
            >
                {segments.map(segment => (
                    <FilterListItem
                        label={segment.name}
                        key={segment.id}
                        value={{ groups: segment.id }}
                    />
                ))}
            </FilterList>
        </CardContent>
    </Card>
)