aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/Layout.mjs
blob: c24a2bc3b278da4cfa69ce2c577d454ff72ab0f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import PlainDraggable from 'plain-draggable'
import { onRemove, animateRectTransition } from './utils'

/**
 * Basic class for layout
 */
export class Layout {
  /**
   * Creates a new Layout instance
   *
   * @param {Object} options - The options for the layout
   * @param {string} options.name - The name of the layout
   * @param {Function} [options.enterHandler] - Handler called when entering the layout
   * @param {Function} [options.leaveHandler] - Handler called when leaving the layout
   * @throws {Error} If the layout name is not provided
   */
  constructor (options = {}) {
    if (!options.name) throw Error('Layout name is not given')
    this.name = options.name
    this.enterHandler = options.enterHandler
    this.leaveHandler = options.leaveHandler
  }

  /**
   * Returns the name of the layout
   *
   * @returns {string} The name of the layout
   */
  valueOf = () => this.name
}

/**
 * Side-By-Side Layout, HTML content and Showcase show on left/right side
 *
 * @extends {Layout}
 */
export class SideBySide extends Layout {
  /**
   * Handler called when entering the Side-By-Side layout
   *
   * @param {Object} options - The options object
   * @param {HTMLElement} options.container - The main container element
   * @param {HTMLElement} options.htmlHolder - The HTML content holder
   * @param {HTMLElement} options.showcase - The showcase element
   */
  enterHandler = ({ container, htmlHolder, showcase }) => {
    const bar = document.createElement('div')
    bar.className = 'bar'
    bar.innerHTML = '<div class="bar-handle"></div>'
    const handle = bar.querySelector('.bar-handle')
    container.appendChild(bar)

    // Resize views by value
    const resizeByLeft = left => {
      htmlHolder.style.width = left + 'px'
      showcase.style.width =
        parseFloat(window.getComputedStyle(container).width) - left + 'px'
    }

    const draggable = new PlainDraggable(bar, {
      handle,
      containment: { left: '25%', top: 0, right: '75%', height: 0 },
    })
    draggable.draggableCursor = 'grab'

    draggable.onDrag = pos => {
      handle.style.transform = 'unset'
      resizeByLeft(pos.left)
    }
    draggable.onDragEnd = _ => {
      handle.style.cssText = ''
    }

    onRemove(bar, () => draggable.remove())
  }

  /**
   * Handler called when leaving the Side-By-Side layout
   *
   * @param {Object} options - The options object
   * @param {HTMLElement} options.container - The main container element
   */
  leaveHandler = ({ container }) => {
    container.querySelector('.bar')?.remove()
  }
}

/**
 * addDraggable.
 *
 * @param {HTMLElement} element
 */
const addDraggable = (element, { snap, left, top } = {}) => {
  element.classList.add('draggable-block')

  // Make sure current element always on top
  const siblings = Array.from(
    element.parentElement?.querySelectorAll(':scope > *') ?? [],
  )
  let popTimer = null
  const onmouseover = () => {
    popTimer = setTimeout(() => {
      siblings.forEach(e => e.style.removeProperty('z-index'))
      element.style.zIndex = '9001'
    }, 200)
  }
  const onmouseout = () => {
    clearTimeout(popTimer)
  }
  element.addEventListener('mouseover', onmouseover)
  element.addEventListener('mouseout', onmouseout)

  // Add draggable part
  const draggablePart = document.createElement('div')
  element.appendChild(draggablePart)
  draggablePart.className = 'draggable-part'
  draggablePart.innerHTML = '<div class="handle">\u2630</div>'

  // Add draggable instance
  const draggable = new PlainDraggable(element, {
    left,
    top,
    handle: draggablePart,
    snap,
  })

  // FIXME use pure CSS to hide utils
  draggable.onDragStart = () => {
    element.classList.add('dragging')
  }

  draggable.onDragEnd = () => {
    element.classList.remove('dragging')
    element.style.zIndex = '9000'
  }

  // Reposition draggable instance when resized
  const resizeObserver = new window.ResizeObserver(() => {
    draggable?.position()
  })
  resizeObserver.observe(element)

  // Callback for remove
  onRemove(element, () => {
    resizeObserver.disconnect()
  })

  new window.MutationObserver(() => {
    if (!element.classList.contains('draggable-block') && draggable) {
      element.removeEventListener('mouseover', onmouseover)
      element.removeEventListener('mouseout', onmouseout)
      resizeObserver.disconnect()
    }
  }).observe(element, {
    attributes: true,
    attributeFilter: ['class'],
  })

  return draggable
}

/**
 * Overlay Layout, Showcase occupies viewport, and HTML content becomes draggable blocks
 *
 * @extends {Layout}
 */
export class Overlay extends Layout {
  /**
   * saveLeftTopAsData.
   *
   * @param {HTMLElement} element
   */
  saveLeftTopAsData = element => {
    const { left, top } = element.getBoundingClientRect()
    element.dataset.left = left
    element.dataset.top = top
  }

  /**
   * enterHandler.
   *
   * @param {HTMLElement} options.hemlHolder - Parent element for block
   * @param {HTMLElement[]} options.blocks
   */
  enterHandler = ({ htmlHolder, blocks }) => {
    // FIXME It is weird rect from this method and this scope are different...
    blocks.forEach(this.saveLeftTopAsData)

    // If no block are focused, focus first three blocks (make them visible)
    if (!blocks.find(b => b.classList.contains('focus'))) {
      blocks.slice(0, 3).forEach(b => b.classList.add('focus'))
    }

    // Create draggable blocks and set each position by previous one
    let [left, top] = [20, 20]
    blocks.forEach(block => {
      const originLeft = Number(block.dataset.left)
      const originTop = Number(block.dataset.top)

      // Create draggable block
      const wrapper = document.createElement('div')
      wrapper.classList.add('draggable-block')
      wrapper.innerHTML = `
        <div class="utils">
          <div id="close">\u274C</div>
          <div id="plus-font-size" ">\u2795</div>
          <div id="minus-font-size">\u2796</div>
        </div>
      `
      wrapper.title = 'Middle-click to hide block'
      wrapper.onmouseup = e => {
        // Hide block with middle click
        if (e.button === 1) {
          block.classList.remove('focus')
        }
      }

      // Set DOMRect for wrapper
      block.replaceWith(wrapper)
      wrapper.appendChild(block)
      wrapper.style.left = left + 'px'
      wrapper.style.top = top + 'px'
      const rect = wrapper.getBoundingClientRect()
      left += rect.width + 30
      if (left > window.innerWidth) {
        top += 200
        left = left % window.innerWidth
      }

      // Animation for DOMRect
      animateRectTransition(
        wrapper,
        { left: originLeft, top: originTop },
        { resume: true, duration: 300 },
      ).finished.finally(() => addDraggable(wrapper, {
        left: rect.left,
        top: rect.top,
        snap: {
          x: { step: 20 },
          y: { step: 20 },
        },
      }))

      // Close button
      wrapper.querySelector('#close').onclick = () => {
        block.classList.remove('focus')
      }
      // Plus/Minus font-size of content
      wrapper.querySelector('#plus-font-size').onclick = () => {
        const fontSize = parseFloat(window.getComputedStyle(block).fontSize) / 16
        block.style.fontSize = `${fontSize + 0.2}rem`
      }
      wrapper.querySelector('#minus-font-size').onclick = () => {
        const fontSize = parseFloat(window.getComputedStyle(block).fontSize) / 16
        block.style.fontSize = `${fontSize - 0.2}rem`
      }
    })
  }

  /**
   * leaveHandler.
   *
   * @param {HTMLElement} htmlHolder
   * @param {HTMLElement[]} blocks
   */
  leaveHandler = ({ blocks }) => {
    const resumeFromDraggable = block => {
      const draggableContainer = block.closest('.draggable-block')
      if (!draggableContainer) return
      draggableContainer.replaceWith(block)
      draggableContainer.remove()
    }
    blocks.forEach(resumeFromDraggable)
  }
}

/**
 * Sticky Layout, Showcase is draggable and stick to viewport
 *
 * @extends {Layout}
 */
export class Sticky extends Layout {
  draggable = document.createElement('div')

  enterHandler = ({ showcase }) => {
    showcase.replaceWith(this.draggable)
    this.draggable.appendChild(showcase)
    this.draggableInstance = addDraggable(this.draggable)
    const rect = this.draggable.getBoundingClientRect()
    this.draggable.style.cssText = `left: ${window.innerWidth - rect.width - 20}px; top: ${window.innerHeight - rect.height - 20}px;`
  }

  leaveHandler = ({ showcase }) => {
    this.draggableInstance?.remove()
    this.draggable.replaceWith(showcase)
    this.draggable.querySelectorAll(':scope > :not(.mapclay)').forEach(e => e.remove())
  }
}