initial commit

This commit is contained in:
Evert Prants 2022-07-18 21:41:35 +03:00
commit 5cc2d6eb54
Signed by: evert
GPG Key ID: 1688DA83D222D0B5
24 changed files with 29030 additions and 0 deletions

23
.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

6
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,6 @@
{
"editor.formatOnSave": true,
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
}

46
README.md Normal file
View File

@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

28374
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

44
package.json Normal file
View File

@ -0,0 +1,44 @@
{
"name": "icy-calendar",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.11.45",
"@types/react": "^18.0.15",
"@types/react-dom": "^18.0.6",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"sass": "^1.53.0",
"typescript": "^4.7.4",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

43
public/index.html Normal file
View File

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

BIN
public/logo192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
public/logo512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

25
public/manifest.json Normal file
View File

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

3
public/robots.txt Normal file
View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

0
src/App.scss Normal file
View File

16
src/App.tsx Normal file
View File

@ -0,0 +1,16 @@
import React, { useState } from 'react';
import './App.scss';
import { AppCalendar } from './components/calendar/Calendar';
function App() {
const [date, setDate] = useState(new Date());
return (
<AppCalendar
date={date}
setDate={(newDate) => setDate(new Date(newDate))}
></AppCalendar>
);
}
export default App;

View File

@ -0,0 +1,73 @@
.calendar {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
&__header {
display: flex;
flex-direction: row;
justify-content: space-between;
font-size: 2rem;
}
&__month {
padding: 1rem;
}
&__button {
width: 4.25rem;
appearance: none;
border: none;
background: #ddd;
font-size: 2rem;
cursor: pointer;
}
&__inner {
display: grid;
height: 100%;
grid-template-areas:
"weekday weekday weekday weekday weekday weekday weekday"
"day day day day day day day";
grid-template-rows: 32px auto;
& > * {
border-top: 1px solid #ddd;
border-left: 1px solid #ddd;
}
}
&__weekday {
grid-template: 'weekday';
display: flex;
align-items: center;
justify-content: center;
}
&__day {
display: flex;
justify-content: flex-end;
align-items: flex-start;
grid-template: 'day';
padding: 1rem;
appearance: none;
background: transparent;
border-right: none;
border-bottom: none;
&--outside {
color: rgb(148, 148, 148);
}
&--today {
background-color: rgb(220, 235, 255);
font-weight: bold;
}
&--selected {
outline: 2px solid black;
}
}
}

View File

@ -0,0 +1,73 @@
import { useState } from 'react';
import { Calendar } from '../../lib/calendar';
import './Calendar.scss';
export const AppCalendar = ({
date,
setDate,
}: {
date: Date;
setDate: (date: Date) => void;
}) => {
const [viewDate, setViewDate] = useState(new Date(date));
const calendar = new Calendar(viewDate);
calendar.generateMonth();
return (
<div className="calendar">
<div className="calendar__header">
<button
className="calendar__button calendar__button--previous"
onClick={() => {
calendar.previousMonth();
setViewDate(new Date(calendar.currentDate));
}}
>
&lt;
</button>
<div className="calendar__month">
{calendar.monthName} {calendar.year}
</div>
<button
className="calendar__button calendar__button--next"
onClick={() => {
calendar.nextMonth();
setViewDate(new Date(calendar.currentDate));
}}
>
&gt;
</button>
</div>
<div className="calendar__inner">
{calendar.dayNames.map((day, index) => (
<span className="calendar__weekday" key={'dn' + index}>
{day}
</span>
))}
{calendar.weeks?.map((week, index) =>
week.map((dateBtn, dindex) => (
<button
key={'d' + dindex + index}
onClick={() => setDate(dateBtn!)}
className={
'calendar__day' +
(calendar.isOutOfMonth(dateBtn!)
? ' calendar__day--outside'
: '') +
(calendar.isToday(dateBtn!) ? ' calendar__day--today' : '') +
(calendar.dateEquals(dateBtn!, date)
? ' calendar__day--selected'
: '')
}
>
{dateBtn?.getDate()}
</button>
))
)}
</div>
</div>
);
};

18
src/index.css Normal file
View File

@ -0,0 +1,18 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
html, body, #root {
width: 100%;
height: 100%;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

19
src/index.tsx Normal file
View File

@ -0,0 +1,19 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

View File

@ -0,0 +1,165 @@
import {
getMonthNames,
getRealDay,
getWeekDays,
getWeekNumber,
} from './dateutil';
export type Week = (Date | null)[];
export class Calendar {
public weeks?: Week[];
public monthNames = getMonthNames(this.locale);
public dayNames = getWeekDays(this.locale);
constructor(public currentDate: Date, private locale = 'en-US') {}
public setDate(date: Date) {
this.currentDate = date;
this.generateMonth();
}
public set year(year: number) {
this.currentDate.setFullYear(year);
this.generateMonth();
}
public get year() {
return this.currentDate.getFullYear();
}
public set month(month: number) {
this.currentDate.setMonth(month);
this.generateMonth();
}
public get month() {
return this.currentDate.getMonth();
}
public get monthName() {
return this.monthNames[this.currentDate.getMonth()];
}
public set day(day: number) {
this.currentDate.setDate(day);
this.generateMonth();
}
public get day() {
return this.currentDate.getDate();
}
public get date() {
return this.currentDate;
}
public get firstOfMonth() {
return new Date(
Date.UTC(this.currentDate.getFullYear(), this.currentDate.getMonth(), 1)
);
}
public get lastOfMonth() {
return new Date(
Date.UTC(
this.currentDate.getFullYear(),
this.currentDate.getMonth() + 1,
0
)
);
}
public get weekNumbers() {
return this.weeks!.map(([first]) => getWeekNumber(first!));
}
public get weekCount() {
return Math.ceil(
((this.firstOfMonth.getDay() || 7) - 1 + this.lastOfMonth.getDate()) / 7
);
}
public nextMonth() {
this.currentDate?.setMonth(this.currentDate.getMonth() + 1);
this.generateMonth();
}
public previousMonth() {
this.currentDate?.setMonth(this.currentDate.getMonth() - 1);
this.generateMonth();
}
public isOutOfMonth(date: Date) {
return date.getMonth() !== this.currentDate.getMonth();
}
public dateEquals(date: Date, target: Date) {
return (
date.getDate() === target.getDate() &&
date.getFullYear() === target.getFullYear() &&
date.getMonth() === target.getMonth()
);
}
public isToday(date: Date) {
const today = new Date();
return this.dateEquals(date, today);
}
public static populatePartialWeeks(weeks: Week[]) {
// This reducer fills the first and/or last week of the month
// with dates from previous/next month
weeks.forEach((week, weekIndex) => {
if (week.includes(null)) {
const dir = weekIndex === 0 ? -1 : 1;
const reducer = (
previous: Date | null,
current: Date | null,
index: number
) => {
if (!current && previous) {
week[index] = new Date(
Date.UTC(
previous.getFullYear(),
previous.getMonth(),
previous.getDate() + dir
)
);
}
return week[index];
};
const start = dir === -1 ? week[6] : week[0];
dir < 0
? week.reduceRight(reducer, start)
: week.reduce(reducer, start);
}
});
return weeks;
}
public generateMonth() {
const year = this.currentDate.getFullYear();
const month = this.currentDate.getMonth();
// Create week arrays, fill with nulls
const weeks = Array.from({ length: this.weekCount }, (k, i) =>
new Array(7).fill(null)
);
// Starting offset of the dates in this month
let offset = getRealDay(this.firstOfMonth);
// Create dates for each day of the week
for (let ci = 1; ci <= this.lastOfMonth.getDate(); ci++, offset++) {
const iterDate = new Date(Date.UTC(year, month, ci));
const weekOfMonth = Math.floor(offset / 7);
weeks[weekOfMonth][getRealDay(iterDate)] = iterDate;
}
// Populate dates that are in previous or next month
Calendar.populatePartialWeeks(weeks);
this.weeks = weeks;
return weeks;
}
}

View File

@ -0,0 +1,53 @@
// https://stackoverflow.com/a/6117889
export function getWeekNumber(date: Date) {
// Copy date so don't modify original
const d = new Date(
Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())
);
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
d.setMilliseconds(0);
// Get first day of year
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
// Calculate full weeks to nearest Thursday
const weekNo = Math.ceil(
((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7
);
// Return week number
return weekNo;
}
export function getRealDay(date: Date) {
return (date.getDay() || 7) - 1;
}
export function getWeekDays(
locale = 'en-US',
format: 'long' | 'short' | 'narrow' | undefined = 'long'
) {
const baseDate = new Date(Date.UTC(2022, 0, 3));
return Array.from({ length: 7 }, () => {
const val = baseDate.toLocaleDateString(locale, { weekday: format });
baseDate.setDate(baseDate.getDate() + 1);
return val;
});
}
export function getMonthNames(
locale = 'en-US',
format:
| 'long'
| 'short'
| 'narrow'
| 'numeric'
| '2-digit'
| undefined = 'long'
) {
const baseDate = new Date(Date.UTC(2022, 0, 1));
return Array.from({ length: 12 }, () => {
const val = baseDate.toLocaleDateString(locale, { month: format });
baseDate.setMonth(baseDate.getMonth() + 1);
return val;
});
}

View File

@ -0,0 +1,2 @@
export * from './dateutil';
export * from './calendar';

1
src/react-app-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="react-scripts" />

15
src/reportWebVitals.ts Normal file
View File

@ -0,0 +1,15 @@
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

5
src/setupTests.ts Normal file
View File

@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

26
tsconfig.json Normal file
View File

@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}