OSINT

플라스크 토글 및 쿠키값 저장

우제혁 2023. 6. 25. 23:58

html 과 javascript 코딩에 관한 글이다.

 

토글이란?

노션을 예로 들면 공부내용의 글을 open하면 새로운 페이지로 새로고침 되는게 아니라 옆에서 페이지가 보여지는데 이것을 토글이라고 생각하면 된다.

 

토글 예시

더보기

이게 보이고 안보이고 이것도 토글

 

페이지 설명

option을 누르면 토글 화면이 나온다.

옵션을 누르면 이렇게 세팅할 수 있는 창이 뜨는데 이것은 사실 div를 처음에 숨겨 놨다가 option을 누르면 보이게끔 해주는것이다.

코드로 설명

기본적으로 페이지가 시작되면 다음과 같이 display: none 과 aria-hidden="true"가 되어있어 보이지 않고 맨위의 body style class에도 별 특이점이 없다.

<div class="portfolio-modal modal fade" id="Option" tabindex="-1" style="display: none;" aria-hidden="true">

하지만 option을 클릭하게 되면! 다음과 같이 뾰로롱 하고 없던 것들이 추가가 된다. 하나씩 살펴보자

 

<body style="overflow: hidden; padding-right: 50px;" class="modal-open">

overflow: hidden; 속성은 요소의 내용이 너무 많이 커서 요소의 크기를 벗어날 때, 요소의 경계 상자 내부에 내용을 잘라내는 속성입니다. 즉, 요소의 크기를 벗어나는 내용을 보여주지 않고, 숨기는 역할을 합니다.

padding-right: 50px; 속성은 요소의 오른쪽 패딩 값을 50px로 설정하는 속성입니다. 패딩은 요소 내부의 내용과 경계 상자 사이의 여백을 말하며, 이를 이용하여 요소의 크기를 조절할 수 있습니다. 위의 코드에서는 오른쪽 패딩 값을 설정함으로써, 요소 내부의 내용과 오른쪽 경계 상자 사이에 50px의 여백을 추가하는 효과가 있습니다.

modal-open 은 따로 기능이 없으며 보기 좋으라고 class를 정한것이다.

원레는 fade에 show 가없으면

opacity: 0;
은 해당 요소를 완전히 투명하게 만들어, 해당 요소가 화면에서 보이지 않도록 하는 역할을 하는데

show가 생기면서 opacity: 0; 가 사라지고 보이게 되는것이다.

또한 display: block 이되면서 보이게 되는데

display: block;은 해당 요소가 블록 요소로 표시되도록 설정하는 역할을 하는것으로 그냥 일반적인 div로 되는것이고

 

aria-modal
속성은 모달 대화상자가 화면에 나타났을 때, 해당 요소가 모달 대화상자인지 여부를 나타내는 속성입니다.

 

aria-modal="true"role="dialog
로 설정된 요소는 모달 대화상자임을 의미하며, 스크린 리더 등의 보조기기에서 해당 요소를 모달 대화상자로 인식할 수 있도록 도와줍니다.

💡 여기서 모달은팝업창이라고 생각하면 된다.

 

class="modal-backdrop fade show”

 

.modal-backdrop 클래스는 모달 대화상자의 배경을 나타내며

 

, position: fixed;, top: 0;, left: 0;, z-index: var(--bs-backdrop-zindex);, width: 100vw;, height: 100vh;, background-color: var(--bs-backdrop-bg); 등의 속성으로 모달 대화상자의 배경을 설정합니다.

 

이때 --bs-backdrop-zindex--bs-backdrop-bg는 CSS 변수를 사용하여 설정하며, 이를 통해 유지보수성을 높이고 코드를 간결하게 유지할 수 있습니다.

 

.fade 클래스는 모달 대화상자가 나타나고 사라질 때의 애니메이션 효과를 설정합니다.

 

transition: opacity 0.15s linear; 속성은 opacity 속성이 변경될 때 0.15초 동안 선형적인 변화를 줌으로써 부드러운 애니메이션을 구현합니다.

 

.modal-backdrop.fade 클래스는 모달 대화상자가 사라질 때의 배경을 나타내며, opacity: 0; 속성을 이용하여 배경이 서서히 사라지는 애니메이션을 구현합니다.

 

javascript

이렇게 클릭만으로 바뀌는것은 javascript의 역할이다 코드를 보게 되면

<a class="btn btn-primary btn-lg" data-bs-toggle="modal"  href="#Option">Option</a>

data-bs-toggle="modal" 이렇게 모달임을 설정해주고

href="#Option" 즉 id="Option" 인곳을 가르키는데

부트스트랩을 사용했더니…. 아주 복잡한 코드에서 가져온다.

<!-- Bootstrap core JS-->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>

코드를 분석해본 결과 Ni 클래스가 모달에 관한 클래스였으며 다음과 같다

 

코드

더보기
class Ni extends z {
    constructor(t, e) {
      super(t, e),
        (this._dialog = Q.findOne('.modal-dialog', this._element)),
        (this._backdrop = this._initializeBackDrop()),
        (this._focustrap = this._initializeFocusTrap()),
        (this._isShown = !1),
        (this._isTransitioning = !1),
        (this._scrollBar = new gi()),
        this._addEventListeners();
    }
    static get Default() {
      return Si;
    }
    static get DefaultType() {
      return Ii;
    }
    static get NAME() {
      return 'modal';
    }
    toggle(t) {
      return this._isShown ? this.hide() : this.show(t);
    }
    show(t) {
      this._isShown ||
        this._isTransitioning ||
        P.trigger(this._element, xi, { relatedTarget: t }).defaultPrevented ||
        ((this._isShown = !0),
        (this._isTransitioning = !0),
        this._scrollBar.hide(),
        document.body.classList.add(ki),
        this._adjustDialog(),
        this._backdrop.show(() => this._showElement(t)));
    }
    hide() {
      this._isShown &&
        !this._isTransitioning &&
        (P.trigger(this._element, 'hide.bs.modal').defaultPrevented ||
          ((this._isShown = !1),
          (this._isTransitioning = !0),
          this._focustrap.deactivate(),
          this._element.classList.remove(Li),
          this._queueCallback(
            () => this._hideModal(),
            this._element,
            this._isAnimated()
          )));
    }
    dispose() {
      for (const t of [window, this._dialog]) P.off(t, '.bs.modal');
      this._backdrop.dispose(), this._focustrap.deactivate(), super.dispose();
    }
    handleUpdate() {
      this._adjustDialog();
    }
    _initializeBackDrop() {
      return new yi({
        isVisible: Boolean(this._config.backdrop),
        isAnimated: this._isAnimated(),
      });
    }
    _initializeFocusTrap() {
      return new Ci({ trapElement: this._element });
    }
    _showElement(t) {
      document.body.contains(this._element) ||
        document.body.append(this._element),
        (this._element.style.display = 'block'),
        this._element.removeAttribute('aria-hidden'),
        this._element.setAttribute('aria-modal', !0),
        this._element.setAttribute('role', 'dialog'),
        (this._element.scrollTop = 0);
      const e = Q.findOne('.modal-body', this._dialog);
      e && (e.scrollTop = 0),
        d(this._element),
        this._element.classList.add(Li),
        this._queueCallback(
          () => {
            this._config.focus && this._focustrap.activate(),
              (this._isTransitioning = !1),
              P.trigger(this._element, 'shown.bs.modal', { relatedTarget: t });
          },
          this._dialog,
          this._isAnimated()
        );
    }
    _addEventListeners() {
      P.on(this._element, 'keydown.dismiss.bs.modal', (t) => {
        if ('Escape' === t.key)
          return this._config.keyboard
            ? (t.preventDefault(), void this.hide())
            : void this._triggerBackdropTransition();
      }),
        P.on(window, 'resize.bs.modal', () => {
          this._isShown && !this._isTransitioning && this._adjustDialog();
        }),
        P.on(this._element, 'mousedown.dismiss.bs.modal', (t) => {
          P.one(this._element, 'click.dismiss.bs.modal', (e) => {
            this._element === t.target &&
              this._element === e.target &&
              ('static' !== this._config.backdrop
                ? this._config.backdrop && this.hide()
                : this._triggerBackdropTransition());
          });
        });
    }
    _hideModal() {
      (this._element.style.display = 'none'),
        this._element.setAttribute('aria-hidden', !0),
        this._element.removeAttribute('aria-modal'),
        this._element.removeAttribute('role'),
        (this._isTransitioning = !1),
        this._backdrop.hide(() => {
          document.body.classList.remove(ki),
            this._resetAdjustments(),
            this._scrollBar.reset(),
            P.trigger(this._element, Oi);
        });
    }
    _isAnimated() {
      return this._element.classList.contains('fade');
    }
    _triggerBackdropTransition() {
      if (P.trigger(this._element, 'hidePrevented.bs.modal').defaultPrevented)
        return;
      const t =
          this._element.scrollHeight > document.documentElement.clientHeight,
        e = this._element.style.overflowY;
      'hidden' === e ||
        this._element.classList.contains(Di) ||
        (t || (this._element.style.overflowY = 'hidden'),
        this._element.classList.add(Di),
        this._queueCallback(() => {
          this._element.classList.remove(Di),
            this._queueCallback(() => {
              this._element.style.overflowY = e;
            }, this._dialog);
        }, this._dialog),
        this._element.focus());
    }
    _adjustDialog() {
      const t =
          this._element.scrollHeight > document.documentElement.clientHeight,
        e = this._scrollBar.getWidth(),
        i = e > 0;
      if (i && !t) {
        const t = p() ? 'paddingLeft' : 'paddingRight';
        this._element.style[t] = `${e}px`;
      }
      if (!i && t) {
        const t = p() ? 'paddingRight' : 'paddingLeft';
        this._element.style[t] = `${e}px`;
      }
    }
    _resetAdjustments() {
      (this._element.style.paddingLeft = ''),
        (this._element.style.paddingRight = '');
    }
    static jQueryInterface(t, e) {
      return this.each(function () {
        const i = Ni.getOrCreateInstance(this, t);
        if ('string' == typeof t) {
          if (void 0 === i[t]) throw new TypeError(`No method named "${t}"`);
          i[t](e);
        }
      });
    }
  }

 

  • toggle(): 이 메서드는 Modal 구성 요소의 가시성을 전환합니다. 현재 모달이 표시되어 있으면 숨겨지고 숨겨져 있으면 표시됩니다. 메소드는 먼저 Modal이 현재 전환 중인지(즉, 애니메이션이 진행 중인지) 확인하고, 전환 중이면 조기 종료됩니다. 그렇지 않으면 '_isShow' 속성을 현재 값(true 또는 false)과 반대로 설정하고 '_showElement()' 또는 '_hideModal()''의 값에 따라 '_isShow’ 메서드를 호출합니다.
  • 'show()': 이 메서드는 Modal 구성 요소를 보여줍니다. 먼저 Modal이 현재 표시되어 있는지 또는 전환 중인지 확인하고, 표시되어 있으면 조기 종료됩니다. 그렇지 않으면 '_isShow' 속성을 true로 설정하고 '_showElement()' 메서드를 호출합니다.
  • 'hide()': 이 메서드는 Modal 구성 요소를 숨깁니다. 먼저 Modal이 현재 숨겨져 있는지 또는 전환 중인지 확인하고, 그렇다면 조기 종료됩니다. 그렇지 않으면 '_isShowed' 속성을 false로 설정하고 '_hideModal()' 메서드를 호출합니다.
  • 'disposure()': 이 메서드는 DOM에서 Modal 구성 요소를 제거하고 이벤트 수신기 또는 관련된 다른 리소스를 정리합니다. 먼저 '_hideModal()' 메서드를 호출하여 Modal이 숨겨져 있는지 확인한 다음 DOM에서 Modal 요소를 제거하고 연결된 모든 이벤트 수신기를 제거합니다. 마지막으로 Modal 구성 요소의 모든 속성을 기본값으로 재설정합니다.
  • 'handleUpdate()': 이 메서드는 Modal 구성 요소가 표시되고 내용이 변경된 경우(예: 크기 또는 위치가 변경된 경우)에 호출됩니다. 모달의 위치와 크기를 다시 계산하고 그에 따라 스타일을 업데이트합니다.
  • '_initializeBackdrop()': 이 메서드는 Modal 구성 요소 뒤에 표시되는 배경 요소를 초기화합니다. 이것은 새로운 'div' 요소를 만들고 여기에 적절한 CSS 클래스와 속성을 추가합니다.
  • '_초기화FocusTrap()': 이 방법은 사용자가 Modal 구성 요소에서 탭 아웃할 수 없도록 하는 FocusTrap을 초기화합니다. 새로운 'div' 요소를 생성하고 여기에 적절한 CSS 클래스와 속성을 추가하며 이벤트 수신기를 부착하여 포커스를 관리합니다.
  • '_showElement()': 이 메서드는 요소에 적절한 CSS 클래스와 속성을 추가하여 Modal 구성 요소를 표시합니다. 먼저 Modal이 이미 표시되었는지 또는 전환되었는지 확인하고, 표시된 경우 조기 종료됩니다. 그렇지 않으면 '_isTransitioning' 속성을 true로 설정하고 적절한 CSS 클래스와 속성을 Modal 요소와 해당 하위 요소에 추가하여 표시합니다. 또한 '_adjustDialog()' 메서드를 호출하여 모달의 위치와 크기를 조정합니다.
  • '_hideModal()': 이 메서드는 요소에서 적절한 CSS 클래스 및 속성을 제거하여 Modal 구성 요소를 숨깁니다. 먼저 Modal이 이미 숨겨져 있는지 또는 전환되어 있는지 확인하고, Modal이 이미 숨겨져 있으면 조기에 종료됩니다. 그렇지 않으면 '_isTransitioning' 속성을 true로 설정하고 Modal 요소와 하위 요소에서 적절한 CSS 클래스와 속성을 제거하여 숨깁니다. 또한 배경 및 포커스 트랩 요소가 있는 경우 해당 요소를 제거합니다.
  • '_isAnimated()': 이 메서드는 Modal 구성 요소에 CSS 전환 또는 애니메이션이 적용되어 있는지 확인합니다.
  • '_triggerBackdropTransition()': 이 메서드는 Modal 구성 요소를 표시하거나 숨길 때 배경 요소에서 전환을 트리거합니다.
  • '_adjustDialog()': 이 메서드는 Modal 구성 요소의 위치와 크기를 조정하여 화면 중심에 위치하고 뷰포트 내에 맞도록 합니다. 뷰포트 크기를 기준으로 모달의 최대 높이와 너비를 계산하고 그에 따라 모달의 높이와 너비를 설정합니다. 또한 모달의 중심을 화면에 수평 및 수직으로 맞춥니다.