summaryrefslogtreecommitdiff
path: root/webroot/js/utils/helpers.js
blob: b4c8779bd30922ee74b14bdf48a277a4ae8fa452 (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
import { ORIENTATION_LANDSCAPE, ORIENTATION_PORTRAIT } from './constants.js';

export function getLocalStorage(key) {
  try {
    return localStorage.getItem(key);
  } catch (e) {}
  return null;
}

export function setLocalStorage(key, value) {
  try {
    if (value !== '' && value !== null) {
      localStorage.setItem(key, value);
    } else {
      localStorage.removeItem(key);
    }
    return true;
  } catch (e) {}
  return false;
}

export function clearLocalStorage(key) {
  localStorage.removeItem(key);
}

// jump down to the max height of a div, with a slight delay
export function jumpToBottom(element) {
  if (!element) return;

  setTimeout(
    () => {
      element.scrollTo({
        top: element.scrollHeight,
        left: 0,
        behavior: 'smooth',
      });
    },
    50,
    element
  );
}

// convert newlines to <br>s
export function addNewlines(str) {
  return str.replace(/(?:\r\n|\r|\n)/g, '<br />');
}

export function pluralize(string, count) {
  if (count === 1) {
    return string;
  } else {
    return string + 's';
  }
}

// Trying to determine if browser is mobile/tablet.
// Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent
export function hasTouchScreen() {
  let hasTouch = false;
  if ('maxTouchPoints' in navigator) {
    hasTouch = navigator.maxTouchPoints > 0;
  } else if ('msMaxTouchPoints' in navigator) {
    hasTouch = navigator.msMaxTouchPoints > 0;
  } else {
    var mQ = window.matchMedia && matchMedia('(pointer:coarse)');
    if (mQ && mQ.media === '(pointer:coarse)') {
      hasTouch = !!mQ.matches;
    } else if ('orientation' in window) {
      hasTouch = true; // deprecated, but good fallback
    } else {
      // Only as a last resort, fall back to user agent sniffing
      var UA = navigator.userAgent;
      hasTouch =
        /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
        /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA);
    }
  }
  return hasTouch;
}

export function getOrientation(forTouch = false) {
  // chrome mobile gives misleading matchMedia result when keyboard is up
  if (forTouch && window.screen && window.screen.orientation) {
    return window.screen.orientation.type.match('portrait')
      ? ORIENTATION_PORTRAIT
      : ORIENTATION_LANDSCAPE;
  } else {
    // all other cases
    return window.matchMedia('(orientation: portrait)').matches
      ? ORIENTATION_PORTRAIT
      : ORIENTATION_LANDSCAPE;
  }
}

export function padLeft(text, pad, size) {
  return String(pad.repeat(size) + text).slice(-size);
}

export function parseSecondsToDurationString(seconds = 0) {
  const finiteSeconds = Number.isFinite(+seconds) ? Math.abs(seconds) : 0;

  const days = Math.floor(finiteSeconds / 86400);
  const daysString = days > 0 ? `${days} day${days > 1 ? 's' : ''} ` : '';

  const hours = Math.floor((finiteSeconds / 3600) % 24);
  const hoursString = hours || days ? padLeft(`${hours}:`, '0', 3) : '';

  const mins = Math.floor((finiteSeconds / 60) % 60);
  const minString = padLeft(`${mins}:`, '0', 3);

  const secs = Math.floor(finiteSeconds % 60);
  const secsString = padLeft(`${secs}`, '0', 2);

  return daysString + hoursString + minString + secsString;
}

export function setVHvar() {
  var vh = window.innerHeight * 0.01;
  // Then we set the value in the --vh custom property to the root of the document
  document.documentElement.style.setProperty('--vh', `${vh}px`);
}

export function doesObjectSupportFunction(object, functionName) {
  return typeof object[functionName] === 'function';
}

// return a string of css classes
export function classNames(json) {
  const classes = [];

  Object.entries(json).map(function (item) {
    const [key, value] = item;
    if (value) {
      classes.push(key);
    }
    return null;
  });
  return classes.join(' ');
}

// taken from
// https://medium.com/@TCAS3/debounce-deep-dive-javascript-es6-e6f8d983b7a1
export function debounce(fn, time) {
  let timeout;

  return function () {
    const functionCall = () => fn.apply(this, arguments);

    clearTimeout(timeout);
    timeout = setTimeout(functionCall, time);
  };
}

export function getDiffInDaysFromNow(timestamp) {
  const time = typeof timestamp === 'string' ? new Date(timestamp) : timestamp;
  return (new Date() - time) / (24 * 3600 * 1000);
}

// "Last live today at [time]" or "last live [date]"
export function makeLastOnlineString(timestamp) {
  if (!timestamp) {
    return '';
  }
  let string = '';
  const time = new Date(timestamp);
  const comparisonDate = new Date(time).setHours(0, 0, 0, 0);

  if (comparisonDate == new Date().setHours(0, 0, 0, 0)) {
    const atTime = time.toLocaleTimeString([], {
      hour: '2-digit',
      minute: '2-digit',
    });
    string = `Today ${atTime}`;
  } else {
    string = time.toLocaleDateString();
  }

  return `Last live: ${string}`;
}

// Routing & Tabs
export const ROUTE_RECORDINGS = 'recordings';
export const ROUTE_SCHEDULE = 'schedule';
// looks for `/recording|schedule/id` pattern to determine what to display from the tab view
export function checkUrlPathForDisplay() {
  const pathTest = [ROUTE_RECORDINGS, ROUTE_SCHEDULE];
  const pathParts = window.location.pathname.split('/');

  if (pathParts.length >= 2) {
    const part = pathParts[1].toLowerCase();
    if (pathTest.includes(part)) {
      return {
        section: part,
        sectionId: pathParts[2] || '',
      };
    }
  }
  return null;
}