레이블이 웹 프로그래밍인 게시물을 표시합니다. 모든 게시물 표시
레이블이 웹 프로그래밍인 게시물을 표시합니다. 모든 게시물 표시

10.04.2020

Studying Basic GIT(init, add, commit, branch, merge, stash)

This summary is based on a very useful tutorial. (not English, but Korean)


  • What is GIT?

    → Version Control System

Basic Commands of GIT

  • git init

  • git add

    • Why should I do git add before git commit ?

      It makes you possible to choose what to commit.

      It great when you have done massive changes on your code, but forgot to commit by each feature.

      We call stage area when you add but didn't commit.

      After commit, it goes to repository .

  • git status

    → It will show you what has been added(tracked) and what has not.

  • git config —global user.name <your name>

  • git config —global user.email <your email>

    → If you are using git for the first time, you need to configure git account to let git and others know who is making the commits.

  • git commit

    → activate vim for writing commit message

    shortcut git commit -m <your message>

  • git log

    → It will show you the history of commit that you made.

  • git log -p

    → you can see the differences between each commit

  • git diff <A commit id>..<B commit id>

    → It will show you the differences between A commit and B commit in a source level.

  • UNDO the commit

    1. reset
      • git reset <commit id that you want to go back to> — hard
      • the version after above commit will be disappear.
      • You will ONLY can reset the commit on your local.(can't reset already pushed one)
    2. revert
      • remove the target commit and create a new commit.

How GIT Works

  • index(also called cache, staging area)

    • Index contains the file names that have been added, and the location address of that file in the objects folder.

    • It uses SHA1 hash function to generate file directory name(first two letter of the hash string), and file name(left over hash string).

      → SO, If the contents of two different file is exactly same, then git reuses the previous one. (means that git does not create another objects file)

  • objects

    • The objects directory is the one contains the source code that has been git add .
    • The name of the file and the directory name which contains the target file are come from the hash string. So it doesn't contain the file name.(index does)
    • It also contains the commit log.
      • The commit object has two important infomations.
        1. tree(also called snapshot )

          → pointing the object that contains addresses of this version files.

          →The type of each file is blob .

        2. parent

          → pointing the object that contains addresses of previous version files.

  • GIT compares most recent index and commit objects, and make decisions.(git status messages)

GIT Branch

  • git branch

    → show all branches and let us know which one we're in

  • git branch <new branch name>

  • git checkout <branch name that you want to be in>

    shortcut git checkout -b <new branch name that you want to create and want to be in at the same time>

  • git log —branches —decorate —graph <optional : —oneline>

    → show git log with branches states and show us branch graph

  • git diff master..<other branch> || git log master..<other branch>

    → show us differences between two branchs

  • (if you want to merge A to B, you must checkout to B) git merge A

  • git branch -d <branch name that you want to delete>

  • git stash [save]

    stash command let you save current changes like a temporary commit, you don't actually write the commit command though.

    → you can skip the save command.

  • git stash list

    → It shows all the stashed log.

  • git stash apply

    →It brings back most recent stashed state, so that you can continue with your work.

    → It is helpful to type git status to understand how stash works.

  • git stash drop

    → It deletes most recent stash log.

    shortcut git stash pop(apply and drop)

  • git reset — hard HEAD

    → It roll back the current state to the most recent commit(not stash one, but actuall commit).

  • alert git stash ONLY handle the file that is being tracked to git. So, for example, if you have a new file that you never added before, then stash cannot handle that file.

Share:

9.22.2020

HTML Canvas Practice

 

HTML Canvas Practice


Recently I learned how to use html canvas tag. After reading a bit of MDN, I built a simple position detect page. User can draw a line by clicking and when user click the start point, the line turns into red line and user no longer can draw line until user click the reset button.
Below is the JavaScript code for this small project and preview of the project.





const canvas = document.querySelector("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext("2d");

const resetButton = document.querySelector("button");

ctx.fillRect(0, 0, window.innerWidth, window.innerHeight);

let coordinates = [];
let line = new Path2D();
ctx.lineWidth = 5;
ctx.strokeStyle = "white";


const appendNewLine = (x, y) => {
  if (coordinates.length <= 0) {
    return line.moveTo(x, y);
  }
  const {x:prevX, y:prevY} = coordinates[coordinates.length - 1];
  const newLine = new Path2D();
  newLine.moveTo(prevX, prevY);
  newLine.lineTo(x, y);
  line.addPath(newLine);
  ctx.stroke(line);
};

const addDot = (x, y) => {
  const newDot = new Path2D();
  newDot.arc(x, y, 5, 0, Math.PI * 2, true);
  ctx.fillStyle = "white";
  ctx.fill(newDot);
  appendNewLine(x, y);
  coordinates.push({
    x,
    y,
  });
}

const isReturnToStart = (x, y) => {
  if (coordinates.length > 0) {
    const {x:startX, y:startY} = coordinates[0];
    if (x <= startX + 5 && x >= startX - 5) {
      if (y <= startY + 5 && y >= startY - 5) return true;
    }
  }
  return false;
}

const drawLine = (e) => {
  if (isReturnToStart(e.offsetX, e.offsetY)) {
    appendNewLine(coordinates[0].x, coordinates[0].y);
    ctx.strokeStyle = "red";
    ctx.stroke(line);
    console.log(coordinates);
    return e.target.removeEventListener("click", drawLine);
  }
  addDot(e.offsetX, e.offsetY);
}

const resetCanvas = () => {
  ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, window.innerWidth, window.innerHeight);
  line = new Path2D();
  ctx.lineWidth = 5;
  ctx.strokeStyle = "white";
  coordinates = [];
  canvas.addEventListener("click", drawLine);  
}

resetButton.addEventListener("click", resetCanvas);

canvas.addEventListener("click", drawLine);


You can see a Demo in here :D

Share:

9.17.2020

Toy project with React + TypeScript + Firebase - LinkBook

 


LinkBook



User Experience


  • User can login or sign up with email and password.
  • User can login via Google or Github account.
  • User can create, read, update, delete links.
  • User can assign title and related tags(keywords) when creating or updating link items.
  • User can sort links by created(or updated)time by clicking arrow button.
  • User can filter their links by a tag keyword.

Preview





P.S.


  • Skills that I used
    • React (create-react-app)
    • TypeScript
    • Firebase
    • gh-pages
  • If you find any bug on this website, please let me know.
  • Contact Info
    • swimmingkiim@gmail.com
Share:

9.10.2020

TypeScript 기본 개념 정리




아래 정리는 노마드코더의 TypeScript 강의를 듣고 복습으로 작성한 것입니다.

TypeScript란


  • TypeScript는 JavaScript를 기초로 해서 만들어졌다.
  • 말랑한 언어인 JavaScript에 엄격하게 타입을 구분해서 사용하는 것이 TypeScript이다.
  • TypeScript는 컴파일 되어서 JavaScript로 사용된다.
  • 사소한 실수를 하더라도 TypeScript는 컴파일 과정에서 걸러지기 때문에 버그를 줄일 수 있다.

설치


  • npm install typescript --save-dev (개별 프로젝트에 설치시)
  • npm install g typescript (컴퓨터 전체에서 사용시)

tsconfig.json


  • TypeScript가 어떻게 JavaScript로 변환될지 옵션을 설정해주는 파일이다.
  • 기본 예시


{
  "compilerOptions": {
    "module": "commonjs",
    "target": "ES2015",
    "sourceMap": true,
    "outDir": "dist"
  },
  "include": ["index.ts"],
  "exclude": ["node_modules"]
}


tsc



  • tsc 를 터미널에 입력 후 실행하면 tsconfig.json의 설정에 따라 TypeScript 파일이 JavaScript 파일로 바뀐다.
  • package.json에서 start 명령어를 node (실행할 파일경로) , prestart 명령어를 tsc 로 해놓으면 다음과 같은 순서로 실행된다.
    1. tsc 를 실행하여 JavaScript 파일 생성
    2. node 명령어로 생성된 파일 실행

Types



P.S. VS Code를 사용한다면 TS Lint 익스텐션을 설치할 것. TypeScript Error를 나타내준다.
P.S. tsc-watch 모듈을 dev모드로 설치 후, package.json의 script에서 "start": "tsc-watch --onSuccess (백슬래쉬)" node (파일경로) (백슬래쉬)" 로 지정해주면 TypeScript 파일이 업데이트 될 때마다 자동으로 tsc 후 node 명령어를 실행시켜준다.

아래는 타입을 어떻게 지정하는지 보여주는 예시 코드이다.
const sayHi = (name:string, age:number):string => "someValue";

Interface


  • interface 로 선언한 타입은 TypeScript의 타입 지정할 때 사용될 수 있다.

interface Human {
  name: string;
  age:number;
  gender: string;
}

const person = {
  name: "me",
  age: 100,
  gender: "female"
}

const sampleFunction = (person:Human) : string => "someValue";

Class


  • interface 는 JavaScript 코드로 컴파일 되지 않는다.
  • 그런데 경우에 따라서는 이와 같은 구조가 JavaScript 코드로 컴파일 되어야 할 수 있다.
  • 그럴 때는 class 를 사용한다.

class Human {
  public name: string;
  public age: number;
  public gender: string;
  constructor(name: string, age: number, gender?: string) {
    this.name = name;
    this.age = age;
    this.gender = gender;
  }
}

const me: Human = new Human("me", 100, "female");

P.S. 파일 끝에 export {}; 코드를 넣어주어야 TypeScript Error가 나지 않는다.

P.S.
변수명 뒤에 ? 를 붙여주면 함수를 호출할 때 선택적으로 기입할 수 있게 된다.
P.S. const me:Human[] 라고 적어주면 me라는 변수는 Human이란 타입 요소들의 array가 된다.
Share:

I made a new portfolio website with React

thumbnail


I made new portfolio website


About a while ago, I built a personal portfolio website. I already had one, but it was just not look nice to me. SO, I decided to build another one. Again, I kept carried on with the concept of "Swimming Pool". But this time I worked differently.

  • First, I built chunks of vanilla JavaScript code on repl.it, which later became the React components of this project.
    • This process helped me a lot. I learned so much from making thing with vanilla JS.
  • Then, when I was working on React project, I divided the previous code into components , templates (layout of the each section), and pages (combines components and templates).
    • First, I thought this structuring is annoying, but it really did its job when I was refactoring this project. This big structure made me easy to find where I need to fix.


I Just LOVE web page that has its own concept


Yes I do. So I spent a lot of time building sea wave, bubbles and swimming rainbow fish. It can be look like little bit old fashion to someone, but whatever, I love it and that's it : D

here is the preview of my portfolio website.





What I've learned from this project



  1. how to convert vanilla JavaScript code(mostly DOM) to React states and hooks etc.
    • and realize how difficult that can be
  2. how to make CSS animation and JavaScript animation
  3. learned how to use svg tag(I used this skill to make a sea wave)
  4. learned how to use color palette from pinterest properly(since I'm suck with colors)
  5. A importance of mobile view
    • learned that I need to test a lot with different device width, and adjust font-size and ratio etc.


Share:

9.08.2020

자바스크립트에서 입력되는 한글값 구하기(How to get current user input charactor when you can't use onKey event)



자바스크립트에서 입력되는 한글값 구하기

심플한 마크다운 에디터, 공글 을 만들면서 자바스크립트와 DOM에 대해서 많이 배웠다. 그 과정에서 애를 먹은 기능 중 하나가 바로 한글의 keyCode 인식 불가능 문제이었다. 텍스트 에디터를 만들기 위해서는, 그리고 한국 사람들도 사용하기 위해서는 한글 입력은 필수이었다.

여러가지 경우의 수를 console.log로 찍어 보면서 몇 가지를 알게 되었다.

  • 키보드가 한글 입력일 때는 특수키(Shift, Control 등)를 제외하고는 onKeyUp 이벤트가 발생하지 않는다.

  • 따라서 당연히 keyCode를 사용할 수도 없다.

  • 여러가지 이벤트를 실험해본 결과 onInput 이벤트는 잘 작동했다. 이를 적절히 활용하면 가능할 것 같았다.

실시간으로 입력되는 텍스트가 필요한 상황이었다. 그래서 range와 onInput 이벤트를 사용해서 만들어 보았다. 아래는 input 이벤트가 일어나면 현재 커서(caret)를 기준으로 바로 앞칸의 텍스트를 리턴하는 코드이다.

const printCurrentInput = (event) => {
  const currentElement = window.getSelection().focusNode;
  const typedChar = currentElement.textContent.slice(
    window.getSelection().anchorOffset - 1,
    window.getSelection().anchorOffset
  );
  return typedChar;
}

이 코드의 한계로는 각각의 자음과 모음만을 필요로 하는, 즉 정말 어떤 글자키를 눌렀는지 알고 싶을 때는 사용하기 힘들다는 점이다. 다만 지금의 나와 같이 띄어쓰기(space)를 감지하고 싶을 경우 유용할 수 있다. 또한 특정 글자(예를 들면 "럼"과 같은)가 입력되었을 때 이벤트가 일어나야 한다면 유용할 것이다.

어쩐지 React 보다 바닐라 자바스크립트가 훨씬 더 강력하다는 생각이 드는 요즘이다.

Share:

9.07.2020

I made a simple markdown editor with vanilla javascript


Making a Markdown Editor with JavaScript

Two days ago, I started to make a custom markdown editor with JavaScript. Today in this blog post, I want to share the making process so that the other people who want to make their own custom markdown editor will get som help in this article.

Experiment : try to make it work with repl

I spent most of my time in repl project file when I was trying to find basic blueprint and logic of this editor that I want to make. I strongly recommend for the other people to do it as well. It doesn't matter if you're using repl or codepen or something else. This kind of services make our project easy to test, especially when your project is a combination of HTML, CSS and JS. Below is the repl code for this project. You can just directly learn from a code, or you can read the summary of the techniques that I needed for this project which I will explain at the bottom.


repl page : https://repl.it/@SooYoungKim/markdown-editor#index.html

keep in mind that repl code is not a final code, final code is in my github code


Vanilla JavaScript techniques that helped me a LOT

These are the techniques and JavaScript methods that I learned this time. I guess if there's someone who want to make a markdown editor, I think he or she will also need these kind of techniques.


  • div tag and contenteditable attribute

  • window.getSelection()

    • anchorNode

    • focusNode

    • removeAllRanges()

    • addRange()

  • document.createRange()

    • setStart()

    • setEnd()

    • collapse()

    • surroundContents

    • insertNode

    • deleteContents

  • event.keyCode

  • String

    • String.match()

    • String.replace(),

    • RegExp

    • String.indexOf()

    • String.lastIndexOf()

  • a tag download attribute, encodeURIComponent()

  • parentNode.insertBefore()

  • childNode.after()

Above techniques are the core techniques that helped me to build this markdown editor. You can google it each concept, or you can come back later when you want to add certain functionality but don't know how to.

Finally, I put it on to React project

Someone told me before that I should not directly use DOM inside of an React project. I understand what they're trying to say. But at the current moment, I have absolutely no idea how to implement this vanilla JS project to React style(using state, hooks etc but not pure DOM). However, I'm planning to use this editor on more big scale personal project and there're good chances that I will use React. So, I turned into React project, but still using DOM directly. I guess I can figure it out how to code them more "Reactfully" later on.

If anyone who want to see the code, or want to help me with the react code, I'll leave a github address, and deployed URL.


github code

you can use this markdown editor in here!

Share:

9.03.2020