Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor text formatting functions #1418

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 1 addition & 8 deletions src/scripts/mass_deleter.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { dom } from '../util/dom.js';
import { megaEdit } from '../util/mega_editor.js';
import { modalCancelButton, modalCompleteButton, showErrorModal, showModal } from '../util/modals.js';
import { addSidebarItem, removeSidebarItem } from '../util/sidebar.js';
import { dateTimeFormat } from '../util/text_format.js';
import { apiFetch } from '../util/tumblr_helpers.js';

const timezoneOffsetMs = new Date().getTimezoneOffset() * 60000;
Expand All @@ -18,14 +19,6 @@ const createNowString = () => {

return `${YYYY}-${MM}-${DD}T${hh}:${mm}`;
};
const dateTimeFormat = new Intl.DateTimeFormat(document.documentElement.lang, {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
timeZoneName: 'short'
});

const showDeleteDraftsPrompt = () => {
const form = dom('form', { id: 'xkit-mass-deleter-delete-drafts' }, { submit: confirmDeleteDrafts }, [
Expand Down
24 changes: 1 addition & 23 deletions src/scripts/mass_privater.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { dom } from '../util/dom.js';
import { megaEdit } from '../util/mega_editor.js';
import { showModal, modalCancelButton, modalCompleteButton, hideModal, showErrorModal } from '../util/modals.js';
import { addSidebarItem, removeSidebarItem } from '../util/sidebar.js';
import { dateTimeFormat, elementsAsList } from '../util/text_format.js';
import { apiFetch } from '../util/tumblr_helpers.js';
import { userBlogs } from '../util/user.js';

Expand All @@ -12,29 +13,6 @@ const createTagSpan = tag => dom('span', { class: 'mass-privater-tag' }, null, [
const createBlogSpan = name => dom('span', { class: 'mass-privater-blog' }, null, [name]);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const dateTimeFormat = new Intl.DateTimeFormat(document.documentElement.lang, {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
timeZoneName: 'short'
});

/**
* Adds string elements between an array's items to format it as an English prose list.
* The Oxford comma is included.
* @param {any[]} array - Input array of any number of items
* @param {string} andOr - String 'and' or 'or', used before the last item
* @returns {any[]} An array alternating between the input items and strings
*/
const elementsAsList = (array, andOr) =>
array.flatMap((item, i) => {
if (i === array.length - 1) return [item];
if (i === array.length - 2) return array.length === 2 ? [item, ` ${andOr} `] : [item, `, ${andOr} `];
return [item, ', '];
});

const timezoneOffsetMs = new Date().getTimezoneOffset() * 60000;

const createNowString = () => {
Expand Down
27 changes: 1 addition & 26 deletions src/scripts/timeformat.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,11 @@ import moment from '../lib/moment.js';
import { keyToCss } from '../util/css_map.js';
import { pageModifications } from '../util/mutations.js';
import { getPreferences } from '../util/preferences.js';
import { constructRelativeTimeString } from '../util/text_format.js';

let format;
let displayRelative;

const relativeTimeFormat = new Intl.RelativeTimeFormat(document.documentElement.lang, { style: 'long' });
const thresholds = [
{ unit: 'year', denominator: 31557600 },
{ unit: 'month', denominator: 2629800 },
{ unit: 'week', denominator: 604800 },
{ unit: 'day', denominator: 86400 },
{ unit: 'hour', denominator: 3600 },
{ unit: 'minute', denominator: 60 },
{ unit: 'second', denominator: 1 }
];

const constructRelativeTimeString = function (unixTime) {
const now = Math.trunc(new Date().getTime() / 1000);
const unixDiff = unixTime - now;
const unixDiffAbsolute = Math.abs(unixDiff);

for (const { unit, denominator } of thresholds) {
if (unixDiffAbsolute >= denominator) {
const value = Math.trunc(unixDiff / denominator);
return relativeTimeFormat.format(value, unit);
}
}

return relativeTimeFormat.format(-0, 'second');
};

const formatTimeElements = function (timeElements) {
timeElements.forEach(timeElement => {
const momentDate = moment(timeElement.dateTime, moment.ISO_8601);
Expand Down
26 changes: 1 addition & 25 deletions src/scripts/timestamps.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { apiFetch } from '../util/tumblr_helpers.js';
import { onNewPosts } from '../util/mutations.js';
import { getPreferences } from '../util/preferences.js';
import { keyToCss } from '../util/css_map.js';
import { constructRelativeTimeString } from '../util/text_format.js';

const noteCountSelector = keyToCss('noteCount');
const reblogHeaderSelector = keyToCss('reblogHeader');
Expand Down Expand Up @@ -39,16 +40,6 @@ const longTimeFormat = new Intl.DateTimeFormat(locale, {
second: '2-digit',
timeZoneName: 'short'
});
const relativeTimeFormat = new Intl.RelativeTimeFormat(locale, { style: 'long' });
const thresholds = [
{ unit: 'year', denominator: 31557600 },
{ unit: 'month', denominator: 2629800 },
{ unit: 'week', denominator: 604800 },
{ unit: 'day', denominator: 86400 },
{ unit: 'hour', denominator: 3600 },
{ unit: 'minute', denominator: 60 },
{ unit: 'second', denominator: 1 }
];

const constructTimeString = function (unixTime) {
const date = new Date(unixTime * 1000);
Expand Down Expand Up @@ -91,21 +82,6 @@ const constructISOString = function (unixTime) {
return `${fourDigitYear}-${twoDigitMonth}-${twoDigitDate}T${twoDigitHours}:${twoDigitMinutes}:${twoDigitSeconds}${timezoneOffsetIsNegative ? '+' : '-'}${twoDigitTimezoneOffsetHours}:${twoDigitTimezoneOffsetMinutes}`;
};

const constructRelativeTimeString = function (unixTime) {
const now = Math.trunc(new Date().getTime() / 1000);
const unixDiff = unixTime - now;
const unixDiffAbsolute = Math.abs(unixDiff);

for (const { unit, denominator } of thresholds) {
if (unixDiffAbsolute >= denominator) {
const value = Math.trunc(unixDiff / denominator);
return relativeTimeFormat.format(value, unit);
}
}

return relativeTimeFormat.format(-0, 'second');
};

const addPostTimestamps = async function () {
getPostElements({ excludeClass: 'xkit-timestamps-done' }).forEach(async postElement => {
const { id } = postElement.dataset;
Expand Down
48 changes: 48 additions & 0 deletions src/util/text_format.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
const thresholds = [
{ unit: 'year', denominator: 31557600 },
{ unit: 'month', denominator: 2629800 },
{ unit: 'week', denominator: 604800 },
{ unit: 'day', denominator: 86400 },
{ unit: 'hour', denominator: 3600 },
{ unit: 'minute', denominator: 60 },
{ unit: 'second', denominator: 1 }
];

const relativeTimeFormat = new Intl.RelativeTimeFormat(document.documentElement.lang, { style: 'long' });
export const constructRelativeTimeString = function (unixTime) {
const now = Math.trunc(new Date().getTime() / 1000);
const unixDiff = unixTime - now;
const unixDiffAbsolute = Math.abs(unixDiff);

for (const { unit, denominator } of thresholds) {
if (unixDiffAbsolute >= denominator) {
const value = Math.trunc(unixDiff / denominator);
return relativeTimeFormat.format(value, unit);
}
}

return relativeTimeFormat.format(-0, 'second');
};

export const dateTimeFormat = new Intl.DateTimeFormat(document.documentElement.lang, {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
timeZoneName: 'short'
});

/**
* Adds string elements between an array's items to format it as an English prose list.
* The Oxford comma is included.
* @param {any[]} array - Input array of any number of items
* @param {string} andOr - String 'and' or 'or', used before the last item
* @returns {any[]} An array alternating between the input items and strings
*/
export const elementsAsList = (array, andOr) =>
array.flatMap((item, i) => {
if (i === array.length - 1) return [item];
if (i === array.length - 2) return array.length === 2 ? [item, ` ${andOr} `] : [item, `, ${andOr} `];
return [item, ', '];
});