Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="app"></div>
              
            
!

CSS

              
                @import url('https://fonts.googleapis.com/css?family=Press+Start+2P&display=swap');
body {
  font-family: 'Press Start 2P', cursive;
  margin: 2rem;
}

#app {
  max-width: 980px;
  margin: auto;
}
              
            
!

JS

              
                /************************
 * view.ts
 ************************/

/** Nodeが取りうる3種の型 */
type NodeType = VNode | string | number
/** 属性の型 */
type AttributeType = string | EventListener
type Attributes = {
  [attr: string]: AttributeType
}

/**
 * 仮想DOMのひとつのオブジェクトを表す型
 */
type VNode = {
  nodeName: keyof ElementTagNameMap
  attributes: Attributes
  children: NodeType[]
}

/**
 * Nodeを受け取り、VNodeなのかTextなのかを判定する
 */
const isVNode = (node: NodeType): node is VNode => {
  return typeof node !== 'string' && typeof node !== 'number'
}

/**
 * 受け取った属性がイベントかどうか判定する
 * @param attribute 属性
 */
const isEventAttr = (attribute: string): boolean => {
  // onからはじまる属性名はイベントとして扱う
  return /^on/.test(attribute)
}

/**
 * View層の型定義
 */
interface View<State, Actions> {
  (state: State, actions: Actions): VNode
}

/**
 * 仮想DOMを作成する
 * @param nodeName Nodeの名前(HTMLのタグ名)
 * @param attributes Nodeの属性(width/heightやstyleなど)
 * @param children Nodeの子要素のリスト
 */
function h(nodeName: VNode['nodeName'], attributes: VNode['attributes'], ...children: VNode['children']): VNode {
  return {
    nodeName,
    attributes,
    children
  }
}

/**
 * 属性を設定する
 * @param target 操作対象のElement
 * @param attributes Elementに追加したい属性のリスト
 */
const setAttributes = (target: HTMLElement, attributes: Attributes): void => {
  for (const attr in attributes) {
    if (isEventAttr(attr)) {
      // onclickなどはイベントリスナーに登録する
      // onclickやoninput、onchangeなどのonを除いたイベント名を取得する
      const eventName = attr.slice(2)
      target.addEventListener(eventName, attributes[attr] as EventListener)
    } else {
      // イベントリスナ−以外はそのまま属性に設定する
      target.setAttribute(attr, attributes[attr] as string)
    }
  }
}

/**
 * 属性を更新する
 * @param target 操作対象のElement
 * @param oldAttrs 古い属性
 * @param newAttrs 新しい属性
 */
const updateAttributes = (target: HTMLElement, oldAttrs: Attributes, newAttrs: Attributes): void => {
  // 処理をシンプルにするためoldAttrsを削除後、newAttrsで再設定する
  for (const attr in oldAttrs) {
    if (!isEventAttr(attr)) {
      target.removeAttribute(attr)
    }
  }

  for (const attr in newAttrs) {
    if (!isEventAttr(attr)) {
      target.setAttribute(attr, newAttrs[attr] as string)
    }
  }
}

/**
 * input要素のvalueを更新する
 * @param target 操作対象のinput要素
 * @param newValue inputのvalueに設定する値
 */
const updateValue = (target: HTMLInputElement, newValue: string): void => {
  target.value = newValue
}

/** 差分のタイプ */
enum ChangedType {
  /** 差分なし */
  None,
  /** NodeTypeが異なる */
  Type,
  /** テキストNodeが異なる */
  Text,
  /** 要素名が異なる */
  Node,
  /** value属性が異なる(input要素用) */
  Value,
  /** 属性が異なる */
  Attr
}
/**
 * 差分検知を行う
 * @param a
 * @param b
 */
const hasChanged = (a: NodeType, b: NodeType): ChangedType => {
  if (typeof a !== typeof b) {
    return ChangedType.Type
  }

  if (!isVNode(a) && a !== b) {
    return ChangedType.Text
  }

  if (isVNode(a) && isVNode(b)) {
    if (a.nodeName !== b.nodeName) {
      return ChangedType.Node
    }

    if (a.attributes.value !== b.attributes.value) {
      return ChangedType.Value
    }

    if (JSON.stringify(a.attributes) !== JSON.stringify(b.attributes)) {
      // 本来ならオブジェクトひとつひとつを比較すべきなのですが、シンプルな実装にするためにJSON.stringifyを使っています
      // JSON.stringifyを使ったオブジェクトの比較は罠が多いので、できるだけ使わないほうが良いです
      return ChangedType.Attr
    }
  }

  return ChangedType.None
}

/**
 * リアルDOMを作成する
 * @param node 作成するNode
 */
function createElement(node: NodeType): HTMLElement | Text {
  if (!isVNode(node)) {
    return document.createTextNode(node.toString())
  }

  const el = document.createElement(node.nodeName)
  setAttributes(el, node.attributes)
  node.children.forEach(child => el.appendChild(createElement(child)))

  return el
}

/**
 * 仮想DOMの差分を検知し、リアルDOMに反映する
 * @param parent 親要素
 * @param oldNode 古いNode情報
 * @param newNode 新しいNode情報
 * @param index 子要素の順番
 */
function updateElement(parent: HTMLElement, oldNode: NodeType, newNode: NodeType, index = 0): void {
  // oldNodeがない場合は新しいNodeを作成する
  if (!oldNode) {
    parent.appendChild(createElement(newNode))
    return
  }

  // newNodeがない場合は削除されたと判断し、そのNodeを削除する
  const target = parent.childNodes[index]
  if (!newNode) {
    parent.removeChild(target)
    return
  }

  // 差分検知し、パッチ処理(変更箇所だけ反映)を行う
  const changeType = hasChanged(oldNode, newNode)
  switch (changeType) {
    case ChangedType.Type:
    case ChangedType.Text:
    case ChangedType.Node:
      parent.replaceChild(createElement(newNode), target)
      return
    case ChangedType.Value:
      updateValue(target as HTMLInputElement, (newNode as VNode).attributes.value as string)
      return
    case ChangedType.Attr:
      updateAttributes(target as HTMLInputElement, (oldNode as VNode).attributes, (newNode as VNode).attributes)
      return
  }

  // 子要素の差分検知・リアルDOM反映を再帰的に実行する
  if (isVNode(oldNode) && isVNode(newNode)) {
    for (let i = 0; i < newNode.children.length || i < oldNode.children.length; i++) {
      updateElement(target as HTMLElement, oldNode.children[i], newNode.children[i], i)
    }
  }
}


/************************
 * action.ts
 ************************/

type ActionType<State> = (state: State, ...data: any) => void | any

/**
 * Action層の型定義
 */
interface ActionTree<State> {
  [action: string]: ActionType<State>
}


/************************
 * controller.ts
 ************************/

// import { View, VNode, updateElement, createElement } from './view'
// import { ActionTree } from './action'

interface AppConstructor<State, Actions extends ActionTree<State>> {
  /** メインNode */
  el: Element | string
  /** Viewの定義 */
  view: View<State, Actions>
  /** 状態管理 */
  state: State
  /** Actionの定義 */
  actions: Actions
}

class App<State, Actions extends ActionTree<State>> {
  private readonly el: Element
  private readonly view: AppConstructor<State, Actions>['view']
  private readonly state: AppConstructor<State, Actions>['state']
  private readonly actions: AppConstructor<State, Actions>['actions']

  /** 仮想DOM(変更前用) */
  private oldNode: VNode
  /** 仮想DOM(変更後用) */
  private newNode: VNode

  /** 連続でリアルDOM操作が走らないためのフラグ */
  private skipRender: boolean

  constructor(params: AppConstructor<State, Actions>) {
    this.el = typeof params.el === 'string' ? document.querySelector(params.el) : params.el
    this.view = params.view
    this.state = params.state
    this.actions = this.dispatchAction(params.actions)
    this.resolveNode()
  }

  /**
   * ユーザが定義したActionsに仮想DOM再構築用のフックを仕込む
   * @param actions
   */
  private dispatchAction(actions: Actions): Actions {
    const dispatched: ActionTree<State> = {}

    for (const key in actions) {
      const action = actions[key]
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      dispatched[key] = (state: State, ...data: any): any => {
        const ret = action(state, ...data)
        this.resolveNode()
        return ret
      }
    }

    return dispatched as Actions
  }

  /**
   * 仮想DOMを構築する
   */
  private resolveNode(): void {
    // 仮想DOMを再構築する
    this.newNode = this.view(this.state, this.actions)
    this.scheduleRender()
  }

  /**
   * renderのスケジューリングを行う
   */
  private scheduleRender(): void {
    if (!this.skipRender) {
      this.skipRender = true
      // setTimeoutを使うことで非同期になり、かつ実行を数ミリ秒遅延できる
      setTimeout(this.render.bind(this))
    }
  }

  /**
   * リアルDOMに反映する
   */
  private render(): void {
    if (this.oldNode) {
      updateElement(this.el as HTMLElement, this.oldNode, this.newNode)
    } else {
      this.el.appendChild(createElement(this.newNode))
    }

    this.oldNode = this.newNode
    this.skipRender = false
  }
}


/************************
 * app.ts
 ************************/

// import { ActionTree } from './framework/action'
// import { View, h } from './framework/view'
// import { App } from './framework/controller'

/**
 * State: 状態管理
 */
type Task = string
type Form = {
  /** タスクのタイトル */
  title: string
  /** バリデーション結果 */
  hasError: boolean
}
type State = {
  /** タスク一覧 */
  tasks: Task[]
  /** フォームの状態 */
  form: Form
}
const state: State = {
  tasks: ['Learn about Virtual DOM', 'Write a document'],
  form: {
    title: '',
    hasError: true
  }
}

/**
 * Actions: 各種イベント処理
 */
interface Actions extends ActionTree<State> {
  /** タイトルの入力チェックを行う */
  validate: (state: State, title: string) => boolean
  /** 新しいタスクを作成する */
  createTask: (state: State, title: string) => void
  /** indexで指定したタスクを削除する */
  removeTask: (state: State, index: number) => void
}
const actions: Actions = {
  validate(state, title: string) {
    if (!title || title.length < 3 || title.length > 20) {
      state.form.hasError = true
    } else {
      state.form.hasError = false
    }

    return !state.form.hasError
  },

  createTask(state, title = '') {
    state.tasks.push(title)
    state.form.title = ''
  },

  removeTask(state, index: number) {
    state.tasks.splice(index, 1)
  }
}

/**
 * View: 描画関連
 */
const view: View<State, Actions> = (state, actions) => {
  // prettier-ignore
  return h(
    'div', 
    { 
      class: 'nes-container is-rounded',
      style: 'padding: 2rem;'
    },
    h(
      'h1',
      {
        class: 'title',
        style: 'margin-bottom: 2rem;'
      },
      h('i', { class: 'nes-icon heart is-medium' }),
      'Virtual DOM TODO App '
    ),
    h(
      'form',
      {
        class: 'nes-container',
        style: 'margin-bottom: 2rem;'
      },
      h(
        'div',
        {
          class: 'nes-field',
          style: 'margin-bottom: 1rem;',
        },
        h(
          'label',
          {
            class: 'label',
            for: 'task-title'
          },
          'Title'
        ),
        h('input', {
          type: 'text',
          id: 'task-title',
          class: 'nes-input',
          value: state.form.title,
          oninput: (ev: Event) => {
            const target = ev.target as HTMLInputElement
            state.form.title = target.value
            actions.validate(state, target.value)
          }
        }),
      ),
      h(
        'p',
        {
          class: 'nes-text is-error',
          style: `display: ${state.form.hasError ? 'display' : 'none'}`,
        },
        'Enter a value between 3 and 20 characters'
      ),
      h(
        'button',
        {
          type: 'button',
          class: 'nes-btn is-primary',
          onclick: () => {
            if (state.form.hasError) return
            actions.createTask(state, state.form.title)
          }
        },
        'Create'
      )
    ),
    h(
      'ul',
      { class: 'nes-list is-disc nes-container' },
      ...state.tasks.map((task, i) => {
        return h(
          'li',
          {
            class: 'item',
            style: 'margin-bottom: 1rem;'
          },
          task,
          h(
            'button',
            {
              type: 'button',
              class: 'nes-btn is-error',
              style: 'margin-left: 1rem;',
              onclick: () => actions.removeTask(state, i)
            },
            '×'
          )
        )
      })
    )
  )
}

new App<State, Actions>({
  el: '#app',
  state,
  view,
  actions
})
              
            
!
999px

Console