at the end of the day, it was inevitable
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
import $ from 'jquery'
|
||||
import config from '../appConfig'
|
||||
|
||||
export const parseSearchDays = function (date) {
|
||||
const period = date.slice(-1)
|
||||
const dateNum = parseInt(date)
|
||||
|
||||
if (period === 'd') {
|
||||
return dateNum
|
||||
} else {
|
||||
let daysCount = 0
|
||||
|
||||
for (let i = 0; i <= dateNum; i++) {
|
||||
const date = new Date(new Date().setFullYear(new Date().getFullYear() - i))
|
||||
daysCount += date.getFullYear() % 4 === 0 ? 366 : 365
|
||||
console.log(daysCount)
|
||||
}
|
||||
return daysCount
|
||||
}
|
||||
}
|
||||
|
||||
export const makeStickySidebar = function ({component, sidebarSelector, footerSelector, sidebarTopMargin, sidebarBottomMargin}) {
|
||||
const sidebarEl = $(sidebarSelector)
|
||||
const footerEl = $(footerSelector)
|
||||
const sidebarTopPos = parseInt(sidebarEl.css('top'))
|
||||
const sidebarBottomPos = parseInt(sidebarEl.css('bottom'))
|
||||
|
||||
let windowHeight = $(window).height()
|
||||
let docScrollTop = $(document).scrollTop()
|
||||
|
||||
$(window).on('resize', function () {
|
||||
windowHeight = $(window).height() //recalc win height
|
||||
_updateSidebarPosition()
|
||||
})
|
||||
|
||||
$(window).on('scroll', function () {
|
||||
docScrollTop = $(document).scrollTop() //recalc scroll top
|
||||
_updateSidebarPosition()
|
||||
})
|
||||
|
||||
_updateSidebarPosition()
|
||||
|
||||
function _updateSidebarPosition () {
|
||||
const footerTop = footerEl.offset().top
|
||||
const windowBottomPos = docScrollTop + windowHeight
|
||||
// check if document scrollTop position cross sidebar top position with margin
|
||||
//if so we set sidebar top position to its margin value
|
||||
if (docScrollTop < sidebarTopPos - sidebarTopMargin) {
|
||||
sidebarEl.css('top', sidebarTopPos - docScrollTop)
|
||||
} else {
|
||||
sidebarEl.css('top', sidebarTopMargin)
|
||||
}
|
||||
//fixing overlapping on footer
|
||||
if (windowBottomPos >= footerTop + sidebarBottomMargin) {
|
||||
sidebarEl.css('bottom', sidebarBottomPos - footerTop + windowBottomPos)
|
||||
} else {
|
||||
sidebarEl.css('bottom', sidebarBottomPos)
|
||||
}
|
||||
}
|
||||
|
||||
component.componentWillUnmount = function () {
|
||||
$(window).off('resize')
|
||||
$(window).off('scroll')
|
||||
}
|
||||
|
||||
return _updateSidebarPosition
|
||||
}
|
||||
|
||||
//default handler - returns errors field from server response or throw error with given text
|
||||
const defaultApiErrorHandler = (jqXHR, transKey = 'unknown', message = 'Unknown error') => {
|
||||
if (jqXHR.status === 402) {
|
||||
return []
|
||||
}
|
||||
|
||||
if (jqXHR.responseJSON && jqXHR.responseJSON.errors && jqXHR.responseJSON.errors.length) {
|
||||
return jqXHR.responseJSON.errors
|
||||
} else {
|
||||
return [{type: 'error', transKey: transKey, message: message}]
|
||||
}
|
||||
}
|
||||
|
||||
export const createApi = (httpMethod, url,
|
||||
{
|
||||
urlData = false,
|
||||
inputData = (payload) => JSON.stringify(payload),
|
||||
resolveData = (response) => response,
|
||||
rejectData = (defHandler, jqXHR) => { return defHandler(jqXHR) }
|
||||
} = {}
|
||||
) => {
|
||||
return (token, payload, ...args) => {
|
||||
let requestUrl = url
|
||||
if (typeof urlData === 'function') {
|
||||
const urlParams = urlData(payload, ...args)
|
||||
console.log('%c urlParams=' + JSON.stringify(urlParams), 'color: green')
|
||||
requestUrl = url.replace(/\{(.*?)\}/g, function (match, field) {
|
||||
return urlParams[field]
|
||||
})
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let ajaxOptions = {
|
||||
type: httpMethod,
|
||||
url: config.apiUrl + requestUrl,
|
||||
dataType: 'json',
|
||||
contentType: 'application/json',
|
||||
data: inputData(payload),
|
||||
success: function (data) {
|
||||
resolve(resolveData(data))
|
||||
},
|
||||
error: function (jqXHR, textStatus, errorThrown) {
|
||||
console.log(`%c [API Error] HTTP ${jqXHR.status}, ${errorThrown}`, 'background: red; color: yellow')
|
||||
reject(rejectData(defaultApiErrorHandler, jqXHR, textStatus, errorThrown))
|
||||
}
|
||||
}
|
||||
|
||||
if (token) {
|
||||
ajaxOptions.headers = {
|
||||
Authorization: 'Bearer ' + token
|
||||
}
|
||||
}
|
||||
|
||||
// Used for backend debugging :)
|
||||
if (__DEV__) {
|
||||
ajaxOptions['xhrFields'] = {
|
||||
withCredentials: true
|
||||
}
|
||||
}
|
||||
|
||||
$.ajax(ajaxOptions)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const mockApi = (fakeData, timeout = 2000) => () => {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve(fakeData)
|
||||
}, timeout)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
export const normalize = function (arr, entityCallback) {
|
||||
let ids = []
|
||||
let entities = {}
|
||||
arr.forEach((item, i) => {
|
||||
if (item.id) {
|
||||
ids.push(item.id)
|
||||
|
||||
if (entityCallback) {
|
||||
entities[item.id] = entityCallback(item, item.id)
|
||||
}
|
||||
else {
|
||||
entities[item.id] = item
|
||||
}
|
||||
} else {
|
||||
ids.push(i.toString())
|
||||
|
||||
if (entityCallback) {
|
||||
entities[i] = entityCallback(item, i)
|
||||
}
|
||||
else {
|
||||
entities[i] = item
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return {ids, entities}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
export const padLeft = function (string, total) {
|
||||
if (typeof string !== 'string') {
|
||||
throw new Error('First parameter must be a string')
|
||||
}
|
||||
if (typeof total !== 'number') {
|
||||
throw new Error('Second parameter must be a integer')
|
||||
}
|
||||
return new Array(total - string.length + 1).join('0') + string
|
||||
}
|
||||
|
||||
export const addOrdinalSuffix = function (num) {
|
||||
if (typeof num !== 'number') {
|
||||
return num
|
||||
}
|
||||
|
||||
const j = num % 10
|
||||
const k = num % 100
|
||||
|
||||
if (j === 1 && k !== 11) {
|
||||
return num + 'st'
|
||||
}
|
||||
if (j === 2 && k !== 12) {
|
||||
return num + 'nd'
|
||||
}
|
||||
if (j === 3 && k !== 13) {
|
||||
return num + 'rd'
|
||||
}
|
||||
|
||||
return num + 'th'
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import moment from 'moment-timezone'
|
||||
|
||||
const getZonesNames = function () {
|
||||
return moment.tz.names()
|
||||
}
|
||||
|
||||
export const getCurrentTimezone = function () {
|
||||
return moment.tz.guess()
|
||||
}
|
||||
|
||||
const getTimezones = function () {
|
||||
const names = getZonesNames()
|
||||
return names.map(name => {
|
||||
const zone = moment.tz.zone(name)
|
||||
const utc = moment.parseZone(zone).format('Z')
|
||||
const label = `(UTC ${utc}) ${name}`
|
||||
return {value: name, label}
|
||||
})
|
||||
}
|
||||
|
||||
export const timezones = getTimezones()
|
||||
@@ -0,0 +1,20 @@
|
||||
import appConfig from '../appConfig.js';
|
||||
|
||||
const { appEnv, hubSpotportalID } = appConfig;
|
||||
|
||||
// when `npm start` server in local
|
||||
export const isDevelopment = process.env.NODE_ENV === 'development';
|
||||
|
||||
// when `npm run build`
|
||||
export const isProduction = process.env.NODE_ENV === 'production';
|
||||
|
||||
// when run locally or build is generated for corresponding sites
|
||||
export const isLive = appEnv === 'live';
|
||||
export const isStaging = appEnv === 'staging';
|
||||
export const isLocal = appEnv === 'local';
|
||||
|
||||
export const errorConstants = {
|
||||
'Bad credentials.': 'badCredentials'
|
||||
};
|
||||
|
||||
export const hubspotBaseURL = `https://api.hsforms.com/submissions/v3/integration/submit/${hubSpotportalID}`;
|
||||
@@ -0,0 +1,183 @@
|
||||
import moment from 'moment';
|
||||
import { cloneDeep } from 'lodash';
|
||||
import axios from 'axios';
|
||||
import Cookies from 'cookies-js';
|
||||
|
||||
// append scripts in body
|
||||
export const appendScriptLink = (sources) => {
|
||||
sources.map((src) => {
|
||||
const script = document.createElement('script');
|
||||
script.type = 'text/javascript';
|
||||
script.setAttribute('src', src);
|
||||
script.setAttribute('async', true);
|
||||
document.body.appendChild(script);
|
||||
});
|
||||
};
|
||||
|
||||
// load script into body part
|
||||
export const loadScript = (source) => {
|
||||
const s = document.createElement('script');
|
||||
s.type = 'text/javascript';
|
||||
s.async = true;
|
||||
s.innerHTML = source;
|
||||
document.body.appendChild(s);
|
||||
};
|
||||
|
||||
// set document element value
|
||||
export const setDocumentData = (tag, value) => {
|
||||
if (tag === 'title') {
|
||||
document.title = value
|
||||
? `${value} | SOCIALHOSE.IO App`
|
||||
: 'Social Listening Platform | Social Analytics | SOCIALHOSE.IO App';
|
||||
}
|
||||
};
|
||||
|
||||
// convert UTC date to Local date
|
||||
export const convertUTCtoLocal = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
|
||||
if (!date) return '';
|
||||
const utcDate = moment.utc(date).format(); //is used to consider input as UTC if timezone offset is not passed
|
||||
return moment(utcDate).format(format);
|
||||
};
|
||||
|
||||
// convert Local date to UTC date
|
||||
export const convertlocaltoUTC = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
|
||||
if (!date) return '';
|
||||
return moment.utc(date).format(format);
|
||||
};
|
||||
|
||||
// get date
|
||||
export const getDate = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
|
||||
return !date ? moment().format(format) : moment(date).format(format);
|
||||
};
|
||||
|
||||
export const getMomentObject = (date) => {
|
||||
return date ? (moment.isMoment(date) ? date : moment(date)) : null;
|
||||
};
|
||||
|
||||
export const getQueryParams = (obj) => {
|
||||
if (!obj) {
|
||||
return null;
|
||||
}
|
||||
const { page, pageSize = 10, sorted, searchQuery = undefined } = obj;
|
||||
const params = {
|
||||
page: page + 1,
|
||||
limit: pageSize,
|
||||
query: searchQuery
|
||||
};
|
||||
if (sorted && sorted.length) {
|
||||
const sortedField = sorted[0];
|
||||
const sort = {
|
||||
field: sortedField.id,
|
||||
direction: sortedField.desc ? 'desc' : 'asc'
|
||||
};
|
||||
params['sort'] = sort;
|
||||
}
|
||||
return params;
|
||||
};
|
||||
|
||||
export function removeHttpsUrl(url) {
|
||||
return !url ? '' : url.replace(/(^\w+:|^)\/\//, '');
|
||||
}
|
||||
|
||||
export function capOnlyFirstLetter(string) {
|
||||
// lodash: capitalize
|
||||
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
|
||||
}
|
||||
|
||||
export function capFirstLetter(string) {
|
||||
return string.charAt(0).toUpperCase() + string.slice(1);
|
||||
}
|
||||
|
||||
export function getValidHttpUrl(string) {
|
||||
let url;
|
||||
|
||||
try {
|
||||
url = new URL(string);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
url.protocol = 'https:';
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
export function getArray(obj, key = 'name', value = 'value') {
|
||||
return Object.entries(obj).map((v) => ({
|
||||
[key]: v[0],
|
||||
[value]: v[1]
|
||||
}));
|
||||
}
|
||||
|
||||
// get title for source index table
|
||||
export function getTitle(prevTitle) {
|
||||
if (prevTitle && prevTitle.replace(/!+/g, '').trim().length > 0) {
|
||||
return prevTitle;
|
||||
}
|
||||
|
||||
return '[No Name]';
|
||||
}
|
||||
|
||||
export function abbreviateNumber(num) {
|
||||
if (num >= 1000000000) {
|
||||
return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
|
||||
}
|
||||
if (num >= 1000000) {
|
||||
return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
|
||||
}
|
||||
if (num >= 1000) {
|
||||
return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
export function notNullAndUnd(value) {
|
||||
return value !== null && value !== undefined;
|
||||
}
|
||||
|
||||
export function validateForm(form, errors, handleValidation) {
|
||||
let failed;
|
||||
for (let val in errors) {
|
||||
const fieldError = errors[val];
|
||||
if (fieldError) {
|
||||
failed = true;
|
||||
} else if (fieldError === null && !form[val] && form[val] !== 0) {
|
||||
failed = true;
|
||||
handleValidation(val, true);
|
||||
}
|
||||
}
|
||||
if (failed) {
|
||||
return false;
|
||||
} else {
|
||||
return cloneDeep(form);
|
||||
}
|
||||
}
|
||||
|
||||
// get IP
|
||||
export function getIP() {
|
||||
return localStorage.getItem('ip');
|
||||
}
|
||||
|
||||
export const setIP = async () => {
|
||||
try {
|
||||
const res = await axios.get('https://api.ipify.org/?format=json');
|
||||
res.data && res.data.ip && localStorage.setItem('ip', res.data.ip);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
};
|
||||
|
||||
export function getHPContext() {
|
||||
return {
|
||||
hutk: Cookies.get('hubspotutk') || undefined,
|
||||
ipAddress: getIP() || undefined
|
||||
};
|
||||
}
|
||||
|
||||
export function arraymove(arr, fromIndex, toIndex) {
|
||||
if (fromIndex === -1 || toIndex === -1) {
|
||||
return;
|
||||
}
|
||||
var element = arr[fromIndex];
|
||||
arr.splice(fromIndex, 1);
|
||||
arr.splice(toIndex, 0, element);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import React from 'react';
|
||||
import appConfig from '../appConfig';
|
||||
|
||||
const { gtagID, gtagID2, fbPixelID, hubSpotID, insightTagID } = appConfig;
|
||||
|
||||
export const gtagScriptURL = (
|
||||
<script
|
||||
async
|
||||
src={`https://www.googletagmanager.com/gtag/js?id=${gtagID}`}
|
||||
></script>
|
||||
);
|
||||
|
||||
export const gtagScript = (
|
||||
<script>{`
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
function gtag(){dataLayer.push(arguments);}
|
||||
gtag('js', new Date());
|
||||
gtag('config', '${gtagID}', { send_page_view: false });
|
||||
gtag('config', '${gtagID2}', { send_page_view: false });
|
||||
`}</script>
|
||||
);
|
||||
|
||||
export const fbPixelScript = (
|
||||
<script>{`
|
||||
!function(f,b,e,v,n,t,s)
|
||||
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
|
||||
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
|
||||
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
|
||||
n.queue=[];t=b.createElement(e);t.async=!0;
|
||||
t.src=v;s=b.getElementsByTagName(e)[0];
|
||||
s.parentNode.insertBefore(t,s)}(window,document,'script',
|
||||
'https://connect.facebook.net/en_US/fbevents.js');
|
||||
fbq('init', '${fbPixelID}');
|
||||
fbq('track', 'PageView');
|
||||
`}</script>
|
||||
);
|
||||
|
||||
export const hubspotTracking = (
|
||||
<script
|
||||
type="text/javascript"
|
||||
id="hs-script-loader"
|
||||
async
|
||||
defer
|
||||
src={`//js.hs-scripts.com/${hubSpotID}.js`}
|
||||
></script>
|
||||
);
|
||||
|
||||
export const linkedInsightTag = [
|
||||
<script key="insight-tag" type="text/javascript">{`
|
||||
_linkedin_partner_id = "${insightTagID}"; window._linkedin_data_partner_ids = window._linkedin_data_partner_ids || []; window._linkedin_data_partner_ids.push(_linkedin_partner_id);
|
||||
`}</script>,
|
||||
|
||||
<script key="insight-tag-2" type="text/javascript">{`
|
||||
(function(){var s = document.getElementsByTagName("script")[0]; var b = document.createElement("script"); b.type = "text/javascript";b.async = true; b.src = "https://snap.licdn.com/li.lms-analytics/insight.min.js"; s.parentNode.insertBefore(b, s);})();
|
||||
`}</script>
|
||||
];
|
||||
Reference in New Issue
Block a user