aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/dumbyUtils.mjs
blob: 975833b8a1152224a838eecfd114cee349ec3914 (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
import LeaderLine from 'leader-line'
import { replaceTextNodes, full2Half } from './utils'
import proj4 from 'proj4'
import { coordPattern, GeoLink } from './Link.mjs'

/**
 * focusNextMap.
 * @param {Boolean} reverse - focus previous map
 */
export function focusNextMap (reverse = false) {
  const renderedList = this.utils.renderedMaps()
  const index = renderedList.findIndex(e => e.classList.contains('focus'))
  const nextIndex = (index + (reverse ? -1 : 1)) % renderedList.length

  const nextMap = renderedList.at(nextIndex)
  nextMap.classList.add('focus', 'focus-manual')
  nextMap.scrollIntoView({ behavior: 'smooth' })
}

/**
 * focusNextBlock.
 *
 * @param {Boolean} reverse - focus previous block
 */
export function focusNextBlock (reverse = false) {
  const blocks = this.blocks.filter(b =>
    b.checkVisibility({
      contentVisibilityAuto: true,
      opacityProperty: true,
      visibilityProperty: true,
    }),
  )
  const index = blocks.findIndex(e => e.classList.contains('focus'))
  const nextIndex = (index + (reverse ? -1 : 1)) % blocks.length

  blocks.forEach(b => b.classList.remove('focus'))
  const nextBlock = blocks.at(nextIndex)
  nextBlock?.classList?.add('focus')
  scrollToBlock(nextBlock)
}

/**
 * scrollToBlock. Smoothly scroll to target block.
 * If block is bigger than viewport, then pick strategy wisely.
 *
 * @param {HTMLElement} block - Scroll to this element
 */
export const scrollToBlock = block => {
  const parentRect = block.parentElement.getBoundingClientRect()
  const scrollBlock =
    block.getBoundingClientRect().height > parentRect.height * 0.8
      ? 'nearest'
      : 'center'
  block.scrollIntoView({ behavior: 'smooth', block: scrollBlock })
}

/**
 * focusDelay. Delay of throttle, value changes by cases
 */
export function focusDelay () {
  return window.window.getComputedStyle(this.showcase).display === 'none' ? 50 : 300
}

/**
 * switchToNextLayout.
 *
 * @param {Boolean} reverse - Switch to previous one
 */
export function switchToNextLayout (reverse = false) {
  const layouts = this.layouts
  const currentLayoutName = this.container.dataset.layout
  const currentIndex = layouts.map(l => l.name).indexOf(currentLayoutName)
  const padding = reverse ? -1 : 1
  const nextIndex =
    currentIndex === -1
      ? 0
      : (currentIndex + padding + layouts.length) % layouts.length
  const nextLayout = layouts[nextIndex]
  this.container.dataset.layout = nextLayout.name
}

/**
 * removeBlockFocus.
 */
export function removeBlockFocus () {
  this.blocks.forEach(b => b.classList.remove('focus'))
}

/**
 * addMarkerByPoint.
 *
 * @param {Number[]} options.point - page XY
 * @param {HTMLElement} options.map
 */
export const addMarkerByPoint = ({ point, map, title }) => {
  const rect = map.getBoundingClientRect()
  const [lon, lat] = map.renderer
    .unproject([point[0] - rect.left, point[1] - rect.top])
    .map(value => parseFloat(value.toFixed(6)))

  const marker = map.renderer.addMarker({
    xy: [lon, lat],
  })
  marker.dataset.xy = `${lon},${lat}`
  if (title) marker.title = title

  return marker
}

/**
 * addGeoSchemeByText.
 *
 * @param {Node} node
 */
export const addGeoSchemeByText = async (node) => {
  const digit = '[\\d\\uFF10-\\uFF19]'
  const decimal = '[.\\uFF0E]'
  const coordPattern = `(-?${digit}+${decimal}?${digit}*)`
  const DMSPattern = `([NEWS]${digit}+[dD°度]? ${digit}+[mM'分]? ${digit}+${decimal}?${digit}*[sS"秒]?)`
  const re = new RegExp(`${coordPattern}[,\x2F\uFF0C]${coordPattern}|${DMSPattern}\\s${DMSPattern}`, 'g')

  return replaceTextNodes(node, re, match => {
    const patterns = match.filter(p => p)
    const [match1, match2] = [full2Half(patterns.at(1)), full2Half(patterns.at(2))]
    let [x, y] = [undefined, undefined]

    // Get x,y by DMS or coordinates pattern
    if (match1.match('^[NEWS]')) {
      const dms2degreeString = (pchar, nchar) => (dms) => {
        const matches = dms.match(new RegExp(`([${pchar}${nchar}])(\\d+) (\\d+) (.*)$`))
        if (!matches) return null

        return (matches[1] === pchar ? '' : '-') + (Number(matches[2]) + Number(matches[3]) / 60 + Number(matches[4]) / 3600)
      }
      x = [match1, match2].map(dms2degreeString('E', 'W')).find(x => x)
      y = [match1, match2].map(dms2degreeString('N', 'S')).find(y => y)
    } else {
      [x, y] = [match1, match2]
    }

    // Don't process string which can be used as date
    if (Date.parse(match.at(0) + ' 1990')) return null
    if (!x || !y) return null

    // Return anchor element with Geo Scheme
    const a = document.createElement('a')
    a.className = 'not-geolink from-text'
    a.href = `geo:0,0?xy=${x},${y}`
    a.textContent = match.at(0)
    return a
  })
}

/**
 * @description Add more information into Anchor Element within Geo Scheme by CRS
 * @param {String} crs - EPSG/ESRI Code for CRS
 * @return {Function} - Function for link
 */
export const updateGeoSchemeByCRS = (crs) => (link) => {
  const transform = proj4(crs, 'EPSG:4326')
  const params = new URLSearchParams(link.search)
  let xy = params.get('xy')?.split(',')?.map(Number)

  // Set coords for Geo Scheme
  if (link.href.startsWith('geo:0,0')) {
    if (!xy) return null

    const [lon, lat] = transform.forward(xy)
      .map(value => parseFloat(value.toFixed(6)))
    link.href = `geo:${lat},${lon}`
  }

  const [lat, lon] = link.href
    .match(coordPattern)
    .slice(1)
    .map(Number)

  if (!xy) {
    xy = transform.inverse([lon, lat])
    params.set('xy', xy)
  }

  // set query strings
  params.set('crs', crs)
  params.set('q', `${lat},${lon}`)
  link.search = params

  const unit = proj4(crs).oProj.units
  const invalidDegree = unit === 'degrees' &&
    (lon > 180 || lon < -180 || lat > 90 || lat < -90)
  const invalidMeter = unit === 'm' && xy.find(v => v < 100)
  if (invalidDegree || invalidMeter) {
    link.replaceWith(document.createTextNode(link.textContent))
    return null
  }

  return link
}

/**
 * addGeoLinkByDrag.
 *
 * @param {HTMLElement} container
 * @param {Range} range
 */
export const addGeoLinkByDrag = (container, range, endOfLeaderLine) => {
  // link placeholder when dragging
  container.classList.add('dragging-geolink')
  const link = document.createElement('a')
  link.textContent = range.toString()
  link.classList.add('with-leader-line', 'geolink', 'drag', 'from-text')

  // Replace current content with link
  const originContent = range.cloneContents()
  const resumeContent = () => {
    range.deleteContents()
    range.insertNode(originContent)
  }
  range.deleteContents()
  range.insertNode(link)

  // Add leader-line
  const line = new LeaderLine({
    start: link,
    end: endOfLeaderLine,
    path: 'magnet',
  })

  const positionObserver = new window.MutationObserver(() => {
    line.position()
  })
  positionObserver.observe(endOfLeaderLine, {
    attributes: true,
    attributeFilter: ['style'],
  })

  // Handler for dragend
  container.onmouseup = (e) => {
    container.classList.remove('dragging-geolink')
    container.onmousemove = null
    container.onmouseup = null
    link.classList.remove('drag')
    positionObserver.disconnect()
    line.remove()
    endOfLeaderLine.remove()

    const map = document.elementFromPoint(e.clientX, e.clientY)
      .closest('.mapclay[data-render="fulfilled"]')
    if (!map) {
      resumeContent()
      return
    }

    const marker = addMarkerByPoint({ point: [e.clientX, e.clientY], map })
    if (!marker) {
      resumeContent()
      return
    }

    link.href = `geo:${marker.dataset.xy.split(',').reverse()}`
    GeoLink(link)
  }
}