├── src ├── index.js ├── sass │ ├── index.scss │ ├── _common.scss │ └── _gallery.scss ├── images │ └── logo.png ├── templates │ └── gallery-cards.hbs ├── index.html ├── partials │ └── gallery.html └── js │ ├── UnsplashAPI.js │ └── gallery.js ├── .htmlnanorc ├── .sassrc ├── assets ├── status.png ├── how-it-works.png ├── repo-settings.png ├── actions-config-step-1.png └── actions-config-step-2.png ├── .posthtmlrc ├── .editorconfig ├── .prettierrc ├── .parcelrc ├── .github └── workflows │ └── deploy.yml ├── package.json ├── .gitignore ├── README.en.md ├── README.md ├── README.uk.md ├── README.pl.md └── README.es.md /src/index.js: -------------------------------------------------------------------------------- 1 | import './js/gallery' -------------------------------------------------------------------------------- /.htmlnanorc: -------------------------------------------------------------------------------- 1 | { 2 | "minifySvg": false 3 | } -------------------------------------------------------------------------------- /src/sass/index.scss: -------------------------------------------------------------------------------- 1 | @import './common'; 2 | @import './gallery'; 3 | -------------------------------------------------------------------------------- /.sassrc: -------------------------------------------------------------------------------- 1 | { 2 | "includePaths": [ 3 | "node_modules" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /assets/status.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IvanTymoshchuk/tui-pagination/HEAD/assets/status.png -------------------------------------------------------------------------------- /src/images/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IvanTymoshchuk/tui-pagination/HEAD/src/images/logo.png -------------------------------------------------------------------------------- /assets/how-it-works.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IvanTymoshchuk/tui-pagination/HEAD/assets/how-it-works.png -------------------------------------------------------------------------------- /assets/repo-settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IvanTymoshchuk/tui-pagination/HEAD/assets/repo-settings.png -------------------------------------------------------------------------------- /.posthtmlrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": { 3 | "posthtml-include": { 4 | "root": "./src" 5 | } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /assets/actions-config-step-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IvanTymoshchuk/tui-pagination/HEAD/assets/actions-config-step-1.png -------------------------------------------------------------------------------- /assets/actions-config-step-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IvanTymoshchuk/tui-pagination/HEAD/assets/actions-config-step-2.png -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 2 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = false 9 | 10 | 11 | [*.{json,md,yaml}] 12 | indent_size = 2 -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 80, 3 | "useTabs": false, 4 | "semi": true, 5 | "singleQuote": true, 6 | "trailingComma": "es5", 7 | "bracketSpacing": true, 8 | "arrowParens": "avoid", 9 | "proseWrap": "always" 10 | } 11 | -------------------------------------------------------------------------------- /src/templates/gallery-cards.hbs: -------------------------------------------------------------------------------- 1 | {{#each this}} 2 | 8 | {{/each}} -------------------------------------------------------------------------------- /.parcelrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "@parcel/config-default" 4 | ], 5 | "reporters": [ 6 | "...", 7 | "parcel-reporter-clean-dist" 8 | ], 9 | "transformers": { 10 | "*.hbs": [ 11 | "parcel-transformer-hbs" 12 | ] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Page title 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/partials/gallery.html: -------------------------------------------------------------------------------- 1 | 15 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Build and deploy to GitHub Pages 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | 7 | jobs: 8 | build-and-deploy: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout 🛎️ 12 | uses: actions/checkout@v2.3.1 13 | 14 | - name: Install and Build 🔧 15 | run: | 16 | npm ci 17 | npm run build 18 | 19 | - name: Deploy 🚀 20 | uses: JamesIves/github-pages-deploy-action@4.1.0 21 | with: 22 | branch: gh-pages 23 | folder: dist 24 | -------------------------------------------------------------------------------- /src/sass/_common.scss: -------------------------------------------------------------------------------- 1 | @import '~node_modules/modern-normalize/modern-normalize.css'; 2 | body { 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, 4 | sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji'; 5 | } 6 | 7 | img { 8 | display: block; 9 | max-width: 100%; 10 | height: auto; 11 | } 12 | 13 | h1, 14 | h2, 15 | h3, 16 | h4, 17 | h5, 18 | h6, 19 | p { 20 | margin-top: 0; 21 | margin-bottom: 0; 22 | } 23 | 24 | ul, 25 | ol { 26 | margin-top: 0; 27 | margin-bottom: 0; 28 | padding-left: 0; 29 | } 30 | 31 | .list { 32 | list-style: none; 33 | } 34 | 35 | .link { 36 | text-decoration: none; 37 | } 38 | 39 | .container { 40 | width: 1200px; 41 | padding-left: 15px; 42 | padding-right: 15px; 43 | margin-left: auto; 44 | margin-right: auto; 45 | } -------------------------------------------------------------------------------- /src/js/UnsplashAPI.js: -------------------------------------------------------------------------------- 1 | // https://unsplash.com/documentation#get-a-photo - посилання на сторінку 2 | //https: www.npmjs.com/package/tui-pagination - пагінація 3 | import axios from 'axios'; 4 | export class UnsplashAPI { 5 | // Приватні властивості 6 | #BASE_URL = 'https://api.unsplash.com'; 7 | #API_KEY = 'LxvKVGJqiSe6NcEVZOaLXC-f2JIIWZaq_o0WrF8mwJc'; 8 | #query = ''; 9 | 10 | getPopularPhotos(page) { 11 | return axios.get(`${this.#BASE_URL}/search/photos`, { 12 | params: { 13 | query: 'random', 14 | page, 15 | per_page: 12, 16 | client_id: this.#API_KEY, 17 | }, 18 | }); 19 | } 20 | 21 | fetchPhotosByQuery(page) { 22 | return axios.get(`${this.#BASE_URL}/search/photos`, { 23 | params: { 24 | query: this.#query, 25 | page, 26 | per_page: 12, 27 | client_id: this.#API_KEY, 28 | }, 29 | }); 30 | } 31 | 32 | set query(newQuery){ 33 | this.#query = newQuery; 34 | } 35 | } 36 | 37 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tui-pagination", 3 | "version": "2.0.0", 4 | "description": "", 5 | "homepage": "https://IvanTymoshchuk.github.io/tui-pagination", 6 | "scripts": { 7 | "start": "parcel src/*.html", 8 | "build": "parcel build src/*.html --public-url /tui-pagination/" 9 | }, 10 | "repository": { 11 | "type": "git", 12 | "url": "git+https://github.com/IvanTymoshchuk/tui-pagination.git" 13 | }, 14 | "keywords": [], 15 | "author": "Alexander Repeta ", 16 | "license": "ISC", 17 | "bugs": { 18 | "url": "https://github.com/IvanTymoshchuk/tui-pagination/issues" 19 | }, 20 | "dependencies": { 21 | "axios": "^1.3.5", 22 | "modern-normalize": "^1.1.0", 23 | "simplelightbox": "^2.13.0", 24 | "tui-pagination": "^3.4.1" 25 | }, 26 | "devDependencies": { 27 | "@parcel/transformer-sass": "^2.6.0", 28 | "buffer": "^6.0.3", 29 | "parcel": "^2.6.0", 30 | "parcel-reporter-clean-dist": "^1.0.4", 31 | "parcel-transformer-hbs": "^1.0.4", 32 | "posthtml-include": "^1.7.4" 33 | }, 34 | "browserslist": "> 0.5%, last 2 versions, not dead" 35 | } 36 | -------------------------------------------------------------------------------- /src/sass/_gallery.scss: -------------------------------------------------------------------------------- 1 | .gallery-section { 2 | padding: 60px 0; 3 | } 4 | 5 | .search-form { 6 | display: flex; 7 | width: 600px; 8 | margin: 0 auto; 9 | margin-bottom: 40px; 10 | } 11 | 12 | .search-input { 13 | height: 40px; 14 | flex-grow: 1; 15 | font-size: 18px; 16 | padding-left: 15px; 17 | border: 1px solid #303030; 18 | } 19 | 20 | .search-btn, 21 | .load-more { 22 | font-size: 14px; 23 | padding: 10px 20px; 24 | background-color: #2ecc71; 25 | color: #ffffff; 26 | border: none; 27 | text-transform: uppercase; 28 | cursor: pointer; 29 | margin-left: 10px; 30 | transition: background-color 250ms linear; 31 | } 32 | 33 | .load-more { 34 | display: block; 35 | margin: 0 auto; 36 | } 37 | 38 | .load-more.is-hidden { 39 | display: none; 40 | } 41 | 42 | .search-btn:hover, 43 | .search-btn:focus, 44 | .load-more:hover, 45 | .load-more:focus { 46 | background-color: #27ae60; 47 | } 48 | 49 | .gallery { 50 | display: flex; 51 | flex-wrap: wrap; 52 | margin-left: -30px; 53 | margin-top: -30px; 54 | margin-bottom: 20px; 55 | } 56 | 57 | .gallery__item { 58 | flex-basis: calc((100% - 120px) / 4); 59 | margin-left: 30px; 60 | margin-top: 30px; 61 | } 62 | 63 | .gallery-img { 64 | width: 100%; 65 | height: 100%; 66 | max-width: unset; 67 | object-fit: cover; 68 | } 69 | 70 | #tui-pagination-container.is-hidden { 71 | display: none; 72 | } 73 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | #Junk 2 | .DS_Store 3 | .vscode/ 4 | .idea/ 5 | 6 | # Logs 7 | logs 8 | *.log 9 | npm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # Diagnostic reports (https://nodejs.org/api/report.html) 15 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 16 | 17 | # Runtime data 18 | pids 19 | *.pid 20 | *.seed 21 | *.pid.lock 22 | 23 | # Directory for instrumented libs generated by jscoverage/JSCover 24 | lib-cov 25 | 26 | # Coverage directory used by tools like istanbul 27 | coverage 28 | *.lcov 29 | 30 | # nyc test coverage 31 | .nyc_output 32 | 33 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 34 | .grunt 35 | 36 | # Bower dependency directory (https://bower.io/) 37 | bower_components 38 | 39 | # node-waf configuration 40 | .lock-wscript 41 | 42 | # Compiled binary addons (https://nodejs.org/api/addons.html) 43 | build/Release 44 | 45 | # Dependency directories 46 | node_modules/ 47 | jspm_packages/ 48 | 49 | # TypeScript v1 declaration files 50 | typings/ 51 | 52 | # TypeScript cache 53 | *.tsbuildinfo 54 | 55 | # Optional npm cache directory 56 | .npm 57 | 58 | # Optional eslint cache 59 | .eslintcache 60 | 61 | # Microbundle cache 62 | .rpt2_cache/ 63 | .rts2_cache_cjs/ 64 | .rts2_cache_es/ 65 | .rts2_cache_umd/ 66 | 67 | # Optional REPL history 68 | .node_repl_history 69 | 70 | # Output of 'npm pack' 71 | *.tgz 72 | 73 | # Yarn Integrity file 74 | .yarn-integrity 75 | 76 | # dotenv environment variables file 77 | .env 78 | .env.test 79 | 80 | # parcel-bundler cache (https://parceljs.org/) 81 | .parcel-cache 82 | 83 | # Next.js build output 84 | .next 85 | 86 | # Nuxt.js build / generate output 87 | .nuxt 88 | dist 89 | 90 | # Gatsby files 91 | .cache/ 92 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 93 | # https://nextjs.org/blog/next-9-1#public-directory-support 94 | # public 95 | 96 | # vuepress build output 97 | .vuepress/dist 98 | 99 | # Serverless directories 100 | .serverless/ 101 | 102 | # FuseBox cache 103 | .fusebox/ 104 | 105 | # DynamoDB Local files 106 | .dynamodb/ 107 | 108 | # TernJS port file 109 | .tern-port 110 | -------------------------------------------------------------------------------- /src/js/gallery.js: -------------------------------------------------------------------------------- 1 | import { UnsplashAPI } from './UnsplashAPI'; 2 | import createGalleryCards from '../templates/gallery-cards.hbs'; 3 | import Pagination from 'tui-pagination'; 4 | import 'tui-pagination/dist/tui-pagination.css'; 5 | import SimpleLightbox from 'simplelightbox'; 6 | import 'simplelightbox/dist/simple-lightbox.min.css'; 7 | 8 | const ulEl = document.querySelector('.js-gallery'); 9 | const container = document.getElementById('tui-pagination-container'); 10 | 11 | const options = { 12 | // below default value of options 13 | totalItems: 0, 14 | itemsPerPage: 12, 15 | visiblePages: 5, 16 | page: 1, 17 | }; 18 | 19 | const unsplashApi = new UnsplashAPI(); 20 | const pagination = new Pagination(container, options); 21 | const page = pagination.getCurrentPage(); 22 | const lightbox = new SimpleLightbox('.gallery a'); 23 | 24 | async function onRenderPage(page) { 25 | 26 | try { 27 | const respons = await unsplashApi.getPopularPhotos(page); 28 | lightbox.refresh(); 29 | ulEl.innerHTML = createGalleryCards(respons.data.results); 30 | 31 | pagination.reset(respons.data.total); 32 | 33 | 34 | // Якщо все добре, додаємо пагінацію 35 | container.classList.remove('is-hidden'); 36 | 37 | } catch (err) { 38 | console.log(err); 39 | } 40 | 41 | } 42 | // Метод для відображення на яку кнопку натиснули. Подальша підгрузка данних за допомгою пагінації 43 | const createPopularPagination = async event => { 44 | try { 45 | const currentPage = event.page; 46 | // Робимо подальші запити 47 | const respons = await unsplashApi.getPopularPhotos(currentPage); 48 | 49 | // Після відповіді відмальовуємо розмітку 50 | ulEl.innerHTML = createGalleryCards(respons.data.results); 51 | // lightbox.refresh(); 52 | } catch (err) { 53 | console.log(err); 54 | } 55 | }; 56 | 57 | // Додаємо слухача на пагінацію 58 | pagination.on('afterMove', createPopularPagination); 59 | 60 | onRenderPage(); 61 | 62 | //* 2 частина запиту картинок по ключовому слову 63 | const searchFormEl = document.querySelector('.js-search-form'); 64 | 65 | searchFormEl.addEventListener('submit', onSearchFormSubmit); 66 | 67 | const createPhotosByQueryPagination = async event => { 68 | try { 69 | const currentPage = event.page; 70 | 71 | // Робимо подальші запити 72 | const response = await unsplashApi.fetchPhotosByQuery(currentPage); 73 | 74 | // Після відповіді відмальовуємо розмітку 75 | ulEl.innerHTML = createGalleryCards(response.data.results); 76 | // lightbox.refresh(); 77 | } catch (err) { 78 | console.log(err); 79 | } 80 | }; 81 | 82 | async function onSearchFormSubmit(e) { 83 | e.preventDefault(); 84 | 85 | // Відписуємось від попередніх пагінацій 86 | pagination.off('afterMove', createPopularPagination); 87 | pagination.off('afterMove', createPhotosByQueryPagination); 88 | 89 | const searchQuery = 90 | e.currentTarget.elements['user-search-query'].value.trim(); 91 | 92 | unsplashApi.query = searchQuery; 93 | 94 | if (!searchQuery) { 95 | return alert('пустий запит'); 96 | } 97 | 98 | try { 99 | const respons = await unsplashApi.fetchPhotosByQuery(page); 100 | if (respons.data.results.length === 0) { 101 | container.classList.add('is-hidden'); 102 | searchFormEl.reset(); 103 | ulEl.innerHTML = ''; 104 | return alert('Вибачте, по вашому запису нічого не знайдено '); 105 | } 106 | 107 | if (respons.data.results.length < options.itemsPerPage) { 108 | container.classList.add('is-hidden'); 109 | ulEl.innerHTML = createGalleryCards(respons.data.results); 110 | return; 111 | } 112 | // lightbox.refresh(); 113 | ulEl.innerHTML = createGalleryCards(respons.data.results); 114 | pagination.reset(respons.data.total); 115 | // Робимо підписку на нову пагінацію, для подальших запросів 116 | pagination.on('afterMove', createPhotosByQueryPagination); 117 | } catch (err) { 118 | console.log(err); 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /README.en.md: -------------------------------------------------------------------------------- 1 | # Parcel template 2 | 3 | This project was created with Parcel. For familiarization and setting additional features [refer to documentation](https://parceljs.org/). 4 | 5 | ## Preparing a new project 6 | 7 | 1. Make sure you have an LTS version of Node.js installed on your computer. 8 | [Download and install](https://nodejs.org/en/) if needed. 9 | 2. Clone this repository. 10 | 3. Change the folder name from `parcel-project-template` to the name of your project. 11 | 4. Create a new empty GitHub repository. 12 | 5. Open the project in VSCode, launch the terminal and link the project to the GitHub repository 13 | [by instructions](https://docs.github.com/en/get-started/getting-started-with-git/managing-remote-repositories#changing-a-remote-repositorys-url). 14 | 6. Install the project's dependencies in the terminal with the `npm install` command. 15 | 7. Start development mode by running the `npm start` command. 16 | 8. Go to [http://localhost:1234](http://localhost:1234) in your browser. 17 | This page will automatically reload after saving changes to the project files. 18 | 19 | ## Files and folders 20 | 21 | - All stylesheet parshas should be in the `src/sass` folder and imported into the page stylesheets. For example, for `index.html` the style file is named `index.scss`. 22 | - Add images to the `src/images` folder. The assembler optimizes them, but only when deploying the production version of the project. All this happens in the cloud so as not to burden your computer, as it can take a long time on weak machines. 23 | 24 | ## Deploy 25 | 26 | To set up a project deployment, you need to perform a few additional steps to set up your repository. Go to the `Settings` tab and in the `Actions` subsection select the `General` item. 27 | 28 | ![GitHub actions settings](./assets/actions-config-step-1.png) 29 | 30 | Scroll the page to the last section, in which make sure the options are selected as in the following image and click `Save`. Without these settings, the build will not have enough rights to automate the deployment process. 31 | 32 | ![GitHub actions settings](./assets/actions-config-step-2.png) 33 | 34 | The production version of the project will be automatically built and deployed to GitHub Pages, in the `gh-pages` branch, every time the `main` branch is updated. For example, after a direct push or an accepted pull request. To do this, you need to edit the `homepage` field and the `build` script in the `package.json` file, replacing `your_username` and `your_repo_name` with your own, and submit the changes to GitHub. 35 | 36 | 37 | ```json 38 | "homepage": "https://your_username.github.io/your_repo_name/", 39 | "scripts": { 40 | "build": "parcel build src/*.html --public-url /your_repo_name/" 41 | }, 42 | ``` 43 | 44 | Next, you need to go to the settings of the GitHub repository (`Settings` > `Pages`) and set the distribution of the production version of files from the `/root` folder of the `gh-pages` branch, if this was not done automatically. 45 | 46 | ![GitHub Pages settings](./assets/repo-settings.png) 47 | 48 | ### Deployment status 49 | 50 | The deployment status of the latest commit is displayed with an icon next to its ID. 51 | 52 | - **Yellow color** - the project is being built and deployed. 53 | - **Green color** - deployment completed successfully. 54 | - **Red color** - an error occurred during linting, build or deployment. 55 | 56 | More detailed information about the status can be viewed by clicking on the icon, and in the drop-down window, follow the link `Details`. 57 | 58 | ![Deployment status](./assets/status.png) 59 | 60 | ### Live page 61 | 62 | After some time, usually a couple of minutes, the live page can be viewed at the address specified in the edited `homepage` property. For example, here is a link to a live version for this repository 63 | [https://goitacademy.github.io/parcel-project-template](https://goitacademy.github.io/parcel-project-template). 64 | 65 | If a blank page opens, make sure there are no errors in the `Console` tab related to incorrect paths to the CSS and JS files of the project (**404**). Most likely you have the wrong value for the `homepage` property or the `build` script in the `package.json` file. 66 | 67 | ## How it works 68 | 69 | ![How it works](./assets/how-it-works.png) 70 | 71 | 1. After each push to the `main` branch of the GitHub repository, a special script (GitHub Action) is launched from the `.github/workflows/deploy.yml` file. 72 | 2. All repository files are copied to the server, where the project is initialized and built before deployment. 73 | 3. If all steps are successful, the built production version of the project files is sent to the `gh-pages` branch. Otherwise, the script execution log will indicate what the problem is. 74 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Parcel template 2 | 3 | Этот проект был создан при помощи Parcel. Для знакомства и настройки 4 | дополнительных возможностей [обратись к документации](https://parceljs.org/). 5 | 6 | ## Подготовка нового проекта 7 | 8 | 1. Убедись что на компьютере установлена LTS-версия Node.js. 9 | [Скачай и установи](https://nodejs.org/en/) её если необходимо. 10 | 2. Склонируй этот репозиторий. 11 | 3. Измени имя папки с `parcel-project-template` на имя своего проекта. 12 | 4. Создай новый пустой репозиторий на GitHub. 13 | 5. Открой проект в VSCode, запусти терминал и свяжи проект с GitHub-репозиторием 14 | [по инструкции](https://docs.github.com/en/get-started/getting-started-with-git/managing-remote-repositories#changing-a-remote-repositorys-url). 15 | 6. Установи зависимости проекта в терминале командой `npm install` . 16 | 7. Запусти режим разработки, выполнив команду `npm start`. 17 | 8. Перейди в браузере по адресу [http://localhost:1234](http://localhost:1234). 18 | Эта страница будет автоматически перезагружаться после сохранения изменений в 19 | файлах проекта. 20 | 21 | ## Файлы и папки 22 | 23 | - Все паршалы файлов стилей должны лежать в папке `src/sass` и импортироваться в 24 | файлы стилей страниц. Например, для `index.html` файл стилей называется 25 | `index.scss`. 26 | - Изображения добавляй в папку `src/images`. Сборщик оптимизирует их, но только 27 | при деплое продакшн версии проекта. Все это происходит в облаке, чтобы не 28 | нагружать твой компьютер, так как на слабых машинах это может занять много 29 | времени. 30 | 31 | ## Деплой 32 | 33 | Для настройки деплоя проекта необходимо выполнить несколько дополнительных шагов 34 | по настройке твоего репозитория. Зайди во вкладку `Settings` и в подсекции 35 | `Actions` выбери выбери пункт `General`. 36 | 37 | ![GitHub actions settings](./assets/actions-config-step-1.png) 38 | 39 | Пролистай страницу до последней секции, в которой убедись что выбраны опции как 40 | на следующем изображении и нажми `Save`. Без этих настроек у сборки будет 41 | недостаточно прав для автоматизации процесса деплоя. 42 | 43 | ![GitHub actions settings](./assets/actions-config-step-2.png) 44 | 45 | Продакшн версия проекта будет автоматически собираться и деплоиться на GitHub 46 | Pages, в ветку `gh-pages`, каждый раз когда обновляется ветка `main`. Например, 47 | после прямого пуша или принятого пул-реквеста. Для этого необходимо в файле 48 | `package.json` отредактировать поле `homepage` и скрипт `build`, заменив 49 | `your_username` и `your_repo_name` на свои, и отправить изменения на GitHub. 50 | 51 | ```json 52 | "homepage": "https://your_username.github.io/your_repo_name/", 53 | "scripts": { 54 | "build": "parcel build src/*.html --public-url /your_repo_name/" 55 | }, 56 | ``` 57 | 58 | Далее необходимо зайти в настройки GitHub-репозитория (`Settings` > `Pages`) и 59 | выставить раздачу продакшн версии файлов из папки `/root` ветки `gh-pages`, если 60 | это небыло сделано автоматически. 61 | 62 | ![GitHub Pages settings](./assets/repo-settings.png) 63 | 64 | ### Статус деплоя 65 | 66 | Статус деплоя крайнего коммита отображается иконкой возле его идентификатора. 67 | 68 | - **Желтый цвет** - выполняется сборка и деплой проекта. 69 | - **Зеленый цвет** - деплой завершился успешно. 70 | - **Красный цвет** - во время линтинга, сборки или деплоя произошла ошибка. 71 | 72 | Более детальную информацию о статусе можно посмотреть кликнув по иконке, и в 73 | выпадающем окне перейти по ссылке `Details`. 74 | 75 | ![Deployment status](./assets/status.png) 76 | 77 | ### Живая страница 78 | 79 | Через какое-то время, обычно пару минут, живую страницу можно будет посмотреть 80 | по адресу указанному в отредактированном свойстве `homepage`. Например, вот 81 | ссылка на живую версию для этого репозитория 82 | [https://goitacademy.github.io/parcel-project-template](https://goitacademy.github.io/parcel-project-template). 83 | 84 | Если открывается пустая страница, убедись что во вкладке `Console` нет ошибок 85 | связанных с неправильными путями к CSS и JS файлам проекта (**404**). Скорее 86 | всего у тебя неправильное значение свойства `homepage` или скрипта `build` в 87 | файле `package.json`. 88 | 89 | ## Как это работает 90 | 91 | ![How it works](./assets/how-it-works.png) 92 | 93 | 1. После каждого пуша в ветку `main` GitHub-репозитория, запускается специальный 94 | скрипт (GitHub Action) из файла `.github/workflows/deploy.yml`. 95 | 2. Все файлы репозитория копируются на сервер, где проект инициализируется и 96 | проходит сборку перед деплоем. 97 | 3. Если все шаги прошли успешно, собранная продакшн версия файлов проекта 98 | отправляется в ветку `gh-pages`. В противном случае, в логе выполнения 99 | скрипта будет указано в чем проблема. 100 | -------------------------------------------------------------------------------- /README.uk.md: -------------------------------------------------------------------------------- 1 | # Parcel template 2 | 3 | Этот проект был создан при помощи Parcel. Для знакомства и настройки 4 | дополнительных возможностей [обратись к документации](https://parceljs.org/). 5 | 6 | ## Подготовка нового проекта 7 | 8 | 1. Убедись что на компьютере установлена LTS-версия Node.js. 9 | [Скачай и установи](https://nodejs.org/en/) её если необходимо. 10 | 2. Склонируй этот репозиторий. 11 | 3. Измени имя папки с `parcel-project-template` на имя своего проекта. 12 | 4. Создай новый пустой репозиторий на GitHub. 13 | 5. Открой проект в VSCode, запусти терминал и свяжи проект с GitHub-репозиторием 14 | [по инструкции](https://docs.github.com/en/get-started/getting-started-with-git/managing-remote-repositories#changing-a-remote-repositorys-url). 15 | 6. Установи зависимости проекта в терминале командой `npm install` . 16 | 7. Запусти режим разработки, выполнив команду `npm start`. 17 | 8. Перейди в браузере по адресу [http://localhost:1234](http://localhost:1234). 18 | Эта страница будет автоматически перезагружаться после сохранения изменений в 19 | файлах проекта. 20 | 21 | ## Файлы и папки 22 | 23 | - Все паршалы файлов стилей должны лежать в папке `src/sass` и импортироваться в 24 | файлы стилей страниц. Например, для `index.html` файл стилей называется 25 | `index.scss`. 26 | - Изображения добавляй в папку `src/images`. Сборщик оптимизирует их, но только 27 | при деплое продакшн версии проекта. Все это происходит в облаке, чтобы не 28 | нагружать твой компьютер, так как на слабых машинах это может занять много 29 | времени. 30 | 31 | ## Деплой 32 | 33 | Для настройки деплоя проекта необходимо выполнить несколько дополнительных шагов 34 | по настройке твоего репозитория. Зайди во вкладку `Settings` и в подсекции 35 | `Actions` выбери выбери пункт `General`. 36 | 37 | ![GitHub actions settings](./assets/actions-config-step-1.png) 38 | 39 | Пролистай страницу до последней секции, в которой убедись что выбраны опции как 40 | на следующем изображении и нажми `Save`. Без этих настроек у сборки будет 41 | недостаточно прав для автоматизации процесса деплоя. 42 | 43 | ![GitHub actions settings](./assets/actions-config-step-2.png) 44 | 45 | Продакшн версия проекта будет автоматически собираться и деплоиться на GitHub 46 | Pages, в ветку `gh-pages`, каждый раз когда обновляется ветка `main`. Например, 47 | после прямого пуша или принятого пул-реквеста. Для этого необходимо в файле 48 | `package.json` отредактировать поле `homepage` и скрипт `build`, заменив 49 | `your_username` и `your_repo_name` на свои, и отправить изменения на GitHub. 50 | 51 | ```json 52 | "homepage": "https://your_username.github.io/your_repo_name/", 53 | "scripts": { 54 | "build": "parcel build src/*.html --public-url /your_repo_name/" 55 | }, 56 | ``` 57 | 58 | Далее необходимо зайти в настройки GitHub-репозитория (`Settings` > `Pages`) и 59 | выставить раздачу продакшн версии файлов из папки `/root` ветки `gh-pages`, если 60 | это небыло сделано автоматически. 61 | 62 | ![GitHub Pages settings](./assets/repo-settings.png) 63 | 64 | ### Статус деплоя 65 | 66 | Статус деплоя крайнего коммита отображается иконкой возле его идентификатора. 67 | 68 | - **Желтый цвет** - выполняется сборка и деплой проекта. 69 | - **Зеленый цвет** - деплой завершился успешно. 70 | - **Красный цвет** - во время линтинга, сборки или деплоя произошла ошибка. 71 | 72 | Более детальную информацию о статусе можно посмотреть кликнув по иконке, и в 73 | выпадающем окне перейти по ссылке `Details`. 74 | 75 | ![Deployment status](./assets/status.png) 76 | 77 | ### Живая страница 78 | 79 | Через какое-то время, обычно пару минут, живую страницу можно будет посмотреть 80 | по адресу указанному в отредактированном свойстве `homepage`. Например, вот 81 | ссылка на живую версию для этого репозитория 82 | [https://goitacademy.github.io/parcel-project-template](https://goitacademy.github.io/parcel-project-template). 83 | 84 | Если открывается пустая страница, убедись что во вкладке `Console` нет ошибок 85 | связанных с неправильными путями к CSS и JS файлам проекта (**404**). Скорее 86 | всего у тебя неправильное значение свойства `homepage` или скрипта `build` в 87 | файле `package.json`. 88 | 89 | ## Как это работает 90 | 91 | ![How it works](./assets/how-it-works.png) 92 | 93 | 1. После каждого пуша в ветку `main` GitHub-репозитория, запускается специальный 94 | скрипт (GitHub Action) из файла `.github/workflows/deploy.yml`. 95 | 2. Все файлы репозитория копируются на сервер, где проект инициализируется и 96 | проходит сборку перед деплоем. 97 | 3. Если все шаги прошли успешно, собранная продакшн версия файлов проекта 98 | отправляется в ветку `gh-pages`. В противном случае, в логе выполнения 99 | скрипта будет указано в чем проблема. 100 | -------------------------------------------------------------------------------- /README.pl.md: -------------------------------------------------------------------------------- 1 | # Parcel template 2 | 3 | Ten projekt został stworzony przy pomocy Parcel. W celu zapoznania się i 4 | skonfigurowania dodatkowych opcji [zobacz dokumentację](https://parceljs.org/) 5 | 6 | ## Przygotowanie nowego projektu 7 | 8 | 1. Upewnij się, że na komputerze zainstalowana jest wersja LTS Node.js. 9 | [Ściągnij i zainstaluj](https://nodejs.org/en/), jeśli jest taka potrzeba. 10 | 2. Sklonuj to repozytorium. 11 | 3. Zmień nazwę folderu z `parcel-project-template` na nazwę swojego projektu. 12 | 4. Utwórz nowe, puste repozytorium na GitHub. 13 | 5. Otwórz projekt w VSCode, uruchom terminal i zwiąż projekt z repozytorium 14 | GitHub 15 | [zgodnie z instrukcją](https://docs.github.com/en/get-started/getting-started-with-git/managing-remote-repositories#changing-a-remote-repositorys-url). 16 | 6. Utwórz zależność projektu w terminalu przez polecenie `npm install` . 17 | 7. Włącz tryb edycji, wykonując polecenie `npm start`. 18 | 8. Przejdź w przeglądarce pod adres 19 | [http://localhost:1234](http://localhost:1234). Ta strona będzie się 20 | automatycznie odświeżać po dokonaniu zmian w plikach projektu. 21 | 22 | ## Pliki i foldery 23 | 24 | - Wszystkie partiale plików stylów powinny znajdować się w folderze `src/sass` i 25 | importować się w pliki stylów stron. Na przykład dla `index.html` plik stylów 26 | nazywa się `index.scss`. 27 | - Obrazy dodawaj do pliku `src/images`. Moduł zbierający optymalizuje je, ale 28 | tylko przy deploymencie wersji produkcyjnej projektu. Wszystko to zachodzi w 29 | chmurze, aby nie obciążać twojego komputera, ponieważ na słabszym sprzęcie 30 | może to zająć sporo czasu. 31 | 32 | ## Deployment 33 | 34 | Aby skonfigurować deployment projektu należy wykonać kilka dodatkowych kroków 35 | konfigurowania twojego repozytorium. Wejdź w zakładkę `Settings` i w podsekcji 36 | `Actions` wybierz punkt `General`. 37 | 38 | ![GitHub actions settings](./assets/actions-config-step-1.png) 39 | 40 | Przejdź do ostatniej sekcji, w której upewnij się, że wybrane opcje są takie 41 | same jak na następnym obrazku i kliknij `Save`. Bez tych ustawień w module 42 | zbierającym będzie zbyt mało pozwoleń dla automatyzacji procesu deploymentu. 43 | 44 | ![GitHub actions settings](./assets/actions-config-step-2.png) 45 | 46 | Wersja produkcyjna projektu będzie automatycznie gromadzić się i deployować na 47 | GitHub Pages w gałęzi `gh-pages` za każdym razem, gdy aktualizuje się gałąź 48 | `main`. Na przykład po bezpośrednim pushu lub przyjętym pull requeście. W tym 49 | celu niezbędne jest, aby w pliku `package.json` wyedytować pole `homepage` i 50 | skrypt `build`, zamieniając `your_username` i `your_repo_name` na swoje nazwy i 51 | wysłać zmiany na GitHub. 52 | 53 | ```json 54 | "homepage": "https://your_username.github.io/your_repo_name/", 55 | "scripts": { 56 | "build": "parcel build src/*.html --public-url /your_repo_name/" 57 | }, 58 | ``` 59 | 60 | Dalej należy wejść w ustawienia repozytorium GitHub (`Settings` > `Pages`) i 61 | wystawić dystrybucję wersji produkcyjnej z folderu `/root` gałęzi `gh-pages`, 62 | jeśli nie zrobiło się to automatycznie. 63 | 64 | ![GitHub Pages settings](./assets/repo-settings.png) 65 | 66 | ### Status deploymentu 67 | 68 | Status deploymentu ostatniego commitu wyświetla się na ikonie obok jego 69 | identyfikatora. 70 | 71 | - ** Żółty kolor** - wykonuje się zbudowanie i deployment projektu. 72 | - ** Zielony kolor** - deployment zakończył się sukcesem. 73 | - ** Czerwony kolor** - w czasie lintingu, budowania lub deplymentu pojawił się 74 | błąd. 75 | 76 | Więcej informacji o statusie można zobaczyć klikając na ikonkę i w wyskakującym 77 | oknie przejść do odnośnika `Details`. 78 | 79 | ![Deployment status](./assets/status.png) 80 | 81 | ### Działająca strona 82 | 83 | Po jakimś czasie, zazwyczaj kilku minut, działającą stronę będzie można zobaczyć 84 | pod adresem wskazanym w wyedytowanej właściwości `homepage`. Na przykład tu 85 | znajduje się odnośnik do działającej strony dla tego repozytorium 86 | [https://goitacademy.github.io/parcel-project-template](https://goitacademy.github.io/parcel-project-template). 87 | 88 | Jeżeli otwiera się pusta strona, upewnij się, że w zakładce `Console` nie ma 89 | błędów związanych z nieprawidłowymi ścieżkami do plików projektu CSS i JS 90 | (**404**). Najprawdopodobniej wprowadzona została nieprawidłowa wartość 91 | właściwości `homepage` lub skryptu `build` w pliku `package.json`. 92 | 93 | ## Jak to działa 94 | 95 | ![How it works](./assets/how-it-works.png) 96 | 97 | 1. Po każdym pushu w gałęzi `main` repozytorium GitHub, włącza się specjalny 98 | skrypt (GitHub Action) z pliku `.github/workflows/deploy.yml`. 99 | 2. Wszystkie pliki repozytorium kopiują się na serwer, gdzie projekt 100 | inicjalizuje się i buduje przed deploymentem. 101 | 3. Jeżeli wszystkie kroki zakończyły się sukcesem, zbudowana wersja produkcyjna 102 | plików projektu wysyła się w gałąź `gh-pages`. W przeciwnym razie, w logu 103 | wykonania skryptu wskazane zostanie, w czym jest problem. 104 | -------------------------------------------------------------------------------- /README.es.md: -------------------------------------------------------------------------------- 1 | # Parcel template 2 | 3 | Este proyecto fue creado con Parcel. [Consulte la documentación](https://parceljs.org/). 4 | para conocer y personalizar las funciones adicionales. 5 | 6 | ## Preparación de un nuevo proyecto 7 | 8 | 1. Asegúrate de que la versión LTS de Node.js está instalada en tu equipo. 9 | [Descárgala e instálala](https://nodejs.org/en/) si es necesario. 10 | 2. Clona este repositorio. 11 | 3. Cambie el nombre de la carpeta con `parcel-project-template` por el nombre de tu proyecto. 12 | 4. Crea un nuevo repositorio vacío en GitHub. 13 | 5. Abre el proyecto en VSCode, ejecuta el terminal y enlaza el proyecto con el repositorio de GitHub 14 | [según las instrucciones](https://docs.github.com/en/get-started/getting-started-with-git/managing-remote-repositories#changing-a-remote-repositorys-url). 15 | 6. Instala las dependencias del proyecto en el terminal con el comando `npm install`. 16 | 7. Inicia el modo de desarrollo, ejecutando el comando `npm start`. 17 | 8. Ve a la dirección [http://localhost:1234](http://localhost:1234) en tu navegador. 18 | Esta página se recargará automáticamente después de guardar los cambios en los 19 | archivos del proyecto. 20 | 21 | ## Archivos y carpetas 22 | 23 | - Todos los partials de los archivos de estilo deben estar en la carpeta `src/sass` 24 | y ser importados en los archivos de estilos de la página. Por ejemplo, para 25 | `index.html` el archivo de estilos se llama `index.scss`. 26 | - Añade las imágenes a la carpeta `src/images`. El ensamblador las optimizará, 27 | pero sólo cuando se cargue la versión de producción del proyecto. Todo esto 28 | se hace en la nube, para no sobrecargar tu ordenador, ya que puede tardar 29 | mucho en máquinas poco potentes. 30 | 31 | ## Deploy 32 | 33 | Para configurar un proyecto para ser implementado, hay algunos pasos adicionales 34 | para configurar tu repositorio. Ve a la pestaña `Settings` y en la subsección 35 | `Actions`, selecciona la opción `General`. 36 | 37 | ![GitHub actions settings](./assets/actions-config-step-1.png) 38 | 39 | Baja hasta la última sección, asegurándote de que las opciones esten seleccionadas 40 | como en la siguiente imagen, y haz clic en `Save`. Sin estas opciones, la compilación 41 | no tendrá suficientes permisos para automatizar el proceso de implementación. 42 | 43 | ![GitHub actions settings](./assets/actions-config-step-2.png) 44 | 45 | La versión de producción del proyecto se compilará e implementará automáticamente 46 | en GitHub Pages, en la rama `gh-pages`, cada vez que se actualice la rama `main`. 47 | Por ejemplo, después de un push directo o de un pool request aceptado. Para 48 | ello, edita el campo `homepage` y el script `build` en el archivo `package.json`, 49 | sustituyendo `your_username` y `your_repo_name` por los tuyos propios, y envía 50 | los cambios a GitHub. 51 | 52 | ```json 53 | "homepage": "https://your_username.github.io/your_repo_name/", 54 | "scripts": { 55 | "build": "parcel build src/*.html --public-url /your_repo_name/" 56 | }, 57 | ``` 58 | 59 | A continuación, hay que ir a la configuración del repositorio de GitHub 60 | (`Settings` > `Pages`) y seleccionar que la versión de producción de los archivos 61 | se distribuya desde la carpeta `/root` de la rama `gh-pages`, si no se hizo automáticamente. 62 | 63 | ![GitHub Pages settings](./assets/repo-settings.png) 64 | 65 | ### Estado del deploy 66 | 67 | El estado del deploy del último commit se indica con un icono junto a su identificador. 68 | 69 | - **Color amarillo** - el proyecto se está compilando y desplegando. 70 | - **Color verde** - el deploy se completó con éxito. 71 | - **Color rojo** - Se ha producido un error durante el linting, la compilación o el deploy. 72 | 73 | Se puede ver información de estado más detallada haciendo clic en el icono y 74 | en el enlace `Details` de la ventana desplegable. 75 | 76 | ![Deployment status](./assets/status.png) 77 | 78 | ### Página activa 79 | 80 | Después de un tiempo, normalmente un par de minutos, la página activa se puede 81 | ver en la dirección especificada en la propiedad `homepage`. Por ejemplo, aquí 82 | está el enlace a la versión activa de este repositorio. 83 | [https://goitacademy.github.io/parcel-project-template](https://goitacademy.github.io/parcel-project-template). 84 | 85 | Si se abre una página en blanco, asegúrese de que no haya errores en la pestaña 86 | `Console` relacionados con rutas incorrectas a los archivos CSS y JS del proyecto (**404**). 87 | Lo más probable es que tenga un valor incorrecto para la propiedad `homepage` o el 88 | script `build` en el archivo `package.json`. 89 | 90 | ## ¿Cómo funciona? 91 | 92 | ![How it works](./assets/how-it-works.png) 93 | 94 | 1. Después de cada push a la rama `main` del repositorio GitHub, se ejecuta un 95 | script especial (GitHub Action) del archivo `.github/workflows/deploy.yml`. 96 | 2. Todos los archivos del repositorio se copian en el servidor, donde el 97 | proyecto se inicializa y se compila antes de ser desplegado. 98 | 3. Si todos los pasos tienen éxito, la versión de producción compilada de los 99 | archivos del proyecto se envía a la rama `gh-pages`. De lo contrario, el 100 | registro de ejecución del script indicará cuál es el problema. 101 | --------------------------------------------------------------------------------