1
0
mirror of https://github.com/flarum/core.git synced 2025-07-09 11:03:06 +02:00

Merge pull request #2207 from flarum/ds/typescript-conversion

Convert several files in `common/utils` to TypeScript
This commit is contained in:
Franz Liedke
2020-07-10 15:41:14 +02:00
committed by GitHub
10 changed files with 62 additions and 107 deletions

View File

@ -1,5 +1,9 @@
class Item { class Item {
constructor(content, priority) { content: any;
priority: number;
key?: number;
constructor(content: any, priority?: number) {
this.content = content; this.content = content;
this.priority = priority; this.priority = priority;
} }
@ -10,23 +14,15 @@ class Item {
* by priority. * by priority.
*/ */
export default class ItemList { export default class ItemList {
constructor() {
/** /**
* The items in the list. * The items in the list
*
* @type {Object}
* @public
*/ */
this.items = {}; items: { [key: string]: Item } = {};
}
/** /**
* Check whether the list is empty. * Check whether the list is empty.
*
* @returns {boolean}
* @public
*/ */
isEmpty() { isEmpty(): boolean {
for (const i in this.items) { for (const i in this.items) {
if (this.items.hasOwnProperty(i)) { if (this.items.hasOwnProperty(i)) {
return false; return false;
@ -38,36 +34,27 @@ export default class ItemList {
/** /**
* Check whether an item is present in the list. * Check whether an item is present in the list.
*
* @param key
* @returns {boolean}
*/ */
has(key) { has(key: string): boolean {
return !!this.items[key]; return !!this.items[key];
} }
/** /**
* Get the content of an item. * Get the content of an item.
*
* @param {String} key
* @return {*}
* @public
*/ */
get(key) { get(key: string): any {
return this.items[key].content; return this.items[key].content;
} }
/** /**
* Add an item to the list. * Add an item to the list.
* *
* @param {String} key A unique key for the item. * @param key A unique key for the item.
* @param {*} content The item's content. * @param content The item's content.
* @param {Integer} [priority] The priority of the item. Items with a higher * @param [priority] The priority of the item. Items with a higher
* priority will be positioned before items with a lower priority. * priority will be positioned before items with a lower priority.
* @return {ItemList}
* @public
*/ */
add(key, content, priority = 0) { add(key: string, content: any, priority: number = 0): this {
this.items[key] = new Item(content, priority); this.items[key] = new Item(content, priority);
return this; return this;
@ -75,14 +62,8 @@ export default class ItemList {
/** /**
* Replace an item in the list, only if it is already present. * Replace an item in the list, only if it is already present.
*
* @param {String} key
* @param {*} [content]
* @param {Integer} [priority]
* @return {ItemList}
* @public
*/ */
replace(key, content = null, priority = null) { replace(key: string, content: any = null, priority: number = null): this {
if (this.items[key]) { if (this.items[key]) {
if (content !== null) { if (content !== null) {
this.items[key].content = content; this.items[key].content = content;
@ -98,12 +79,8 @@ export default class ItemList {
/** /**
* Remove an item from the list. * Remove an item from the list.
*
* @param {String} key
* @return {ItemList}
* @public
*/ */
remove(key) { remove(key: string): this {
delete this.items[key]; delete this.items[key];
return this; return this;
@ -111,12 +88,8 @@ export default class ItemList {
/** /**
* Merge another list's items into this one. * Merge another list's items into this one.
*
* @param {ItemList} items
* @return {ItemList}
* @public
*/ */
merge(items) { merge(items: this): this {
for (const i in items.items) { for (const i in items.items) {
if (items.items.hasOwnProperty(i) && items.items[i] instanceof Item) { if (items.items.hasOwnProperty(i) && items.items[i] instanceof Item) {
this.items[i] = items.items[i]; this.items[i] = items.items[i];
@ -130,12 +103,9 @@ export default class ItemList {
* Convert the list into an array of item content arranged by priority. Each * Convert the list into an array of item content arranged by priority. Each
* item's content will be assigned an `itemName` property equal to the item's * item's content will be assigned an `itemName` property equal to the item's
* unique key. * unique key.
*
* @return {Array}
* @public
*/ */
toArray() { toArray(): any[] {
const items = []; const items: Item[] = [];
for (const i in this.items) { for (const i in this.items) {
if (this.items.hasOwnProperty(i) && this.items[i] instanceof Item) { if (this.items.hasOwnProperty(i) && this.items[i] instanceof Item) {

View File

@ -1,5 +1,14 @@
export default class RequestError { export default class RequestError {
constructor(status, responseText, options, xhr) { status: string;
options: object;
xhr: XMLHttpRequest;
responseText: string | null;
response: object | null;
alert: any;
constructor(status: string, responseText: string | null, options: object, xhr: XMLHttpRequest) {
this.status = status; this.status = status;
this.responseText = responseText; this.responseText = responseText;
this.options = options; this.options = options;

View File

@ -4,11 +4,8 @@
* @example * @example
* abbreviateNumber(1234); * abbreviateNumber(1234);
* // "1.2K" * // "1.2K"
*
* @param {Integer} number
* @return {String}
*/ */
export default function abbreviateNumber(number) { export default function abbreviateNumber(number: number): string {
// TODO: translation // TODO: translation
if (number >= 1000000) { if (number >= 1000000) {
return Math.floor(number / 1000000) + app.translator.trans('core.lib.number_suffix.mega_text'); return Math.floor(number / 1000000) + app.translator.trans('core.lib.number_suffix.mega_text');

View File

@ -1,15 +0,0 @@
/**
* The `extract` utility deletes a property from an object and returns its
* value.
*
* @param {Object} object The object that owns the property
* @param {String} property The name of the property to extract
* @return {*} The value of the property
*/
export default function extract(object, property) {
const value = object[property];
delete object[property];
return value;
}

View File

@ -0,0 +1,15 @@
/**
* The `extract` utility deletes a property from an object and returns its
* value.
*
* @param object The object that owns the property
* @param property The name of the property to extract
* @return The value of the property
*/
export default function extract<T, K extends keyof T>(object: T, property: K): T[K] {
const value = object[property];
delete object[property];
return value;
}

View File

@ -5,10 +5,7 @@
* @example * @example
* formatNumber(1234); * formatNumber(1234);
* // 1,234 * // 1,234
*
* @param {Number} number
* @return {String}
*/ */
export default function formatNumber(number) { export default function formatNumber(number: number): string {
return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
} }

View File

@ -1,11 +1,8 @@
/** /**
* The `humanTime` utility converts a date to a localized, human-readable time- * The `humanTime` utility converts a date to a localized, human-readable time-
* ago string. * ago string.
*
* @param {Date} time
* @return {String}
*/ */
export default function humanTime(time) { export default function humanTime(time: Date): string {
let d = dayjs(time); let d = dayjs(time);
const now = dayjs(); const now = dayjs();
@ -18,7 +15,7 @@ export default function humanTime(time) {
const day = 864e5; const day = 864e5;
const diff = d.diff(dayjs()); const diff = d.diff(dayjs());
let ago = null; let ago: string;
// If this date was more than a month ago, we'll show the name of the month // If this date was more than a month ago, we'll show the name of the month
// in the string. If it wasn't this year, we'll show the year as well. // in the string. If it wasn't this year, we'll show the year as well.

View File

@ -1,18 +1,18 @@
import humanTimeUtil from './humanTime'; import humanTime from './humanTime';
function updateHumanTimes() { function updateHumanTimes() {
$('[data-humantime]').each(function () { $('[data-humantime]').each(function () {
const $this = $(this); const $this = $(this);
const ago = humanTimeUtil($this.attr('datetime')); const ago = humanTime($this.attr('datetime'));
$this.html(ago); $this.html(ago);
}); });
} }
/** /**
* The `humanTime` initializer sets up a loop every 1 second to update * The `liveHumanTimes` initializer sets up a loop every 1 second to update
* timestamps rendered with the `humanTime` helper. * timestamps rendered with the `humanTime` helper.
*/ */
export default function humanTime() { export default function liveHumanTimes() {
setInterval(updateHumanTimes, 10000); setInterval(updateHumanTimes, 10000);
} }

View File

@ -1,12 +1,7 @@
/** /**
* Truncate a string to the given length, appending ellipses if necessary. * Truncate a string to the given length, appending ellipses if necessary.
*
* @param {String} string
* @param {Number} length
* @param {Number} [start=0]
* @return {String}
*/ */
export function truncate(string, length, start = 0) { export function truncate(string: string, length: number, start: number = 0): string {
return (start > 0 ? '...' : '') + string.substring(start, start + length) + (string.length > start + length ? '...' : ''); return (start > 0 ? '...' : '') + string.substring(start, start + length) + (string.length > start + length ? '...' : '');
} }
@ -17,11 +12,8 @@ export function truncate(string, length, start = 0) {
* NOTE: This method does not use the comparably sophisticated transliteration * NOTE: This method does not use the comparably sophisticated transliteration
* mechanism that is employed in the backend. Therefore, it should only be used * mechanism that is employed in the backend. Therefore, it should only be used
* to *suggest* slugs that can be overridden by the user. * to *suggest* slugs that can be overridden by the user.
*
* @param {String} string
* @return {String}
*/ */
export function slug(string) { export function slug(string: string): string {
return string return string
.toLowerCase() .toLowerCase()
.replace(/[^a-z0-9]/gi, '-') .replace(/[^a-z0-9]/gi, '-')
@ -32,11 +24,8 @@ export function slug(string) {
/** /**
* Strip HTML tags and quotes out of the given string, replacing them with * Strip HTML tags and quotes out of the given string, replacing them with
* meaningful punctuation. * meaningful punctuation.
*
* @param {String} string
* @return {String}
*/ */
export function getPlainContent(string) { export function getPlainContent(string: string): string {
const html = string.replace(/(<\/p>|<br>)/g, '$1 &nbsp;').replace(/<img\b[^>]*>/gi, ' '); const html = string.replace(/(<\/p>|<br>)/g, '$1 &nbsp;').replace(/<img\b[^>]*>/gi, ' ');
const dom = $('<div/>').html(html); const dom = $('<div/>').html(html);
@ -55,10 +44,7 @@ getPlainContent.removeSelectors = ['blockquote', 'script'];
/** /**
* Make a string's first character uppercase. * Make a string's first character uppercase.
*
* @param {String} string
* @return {String}
*/ */
export function ucfirst(string) { export function ucfirst(string: string): string {
return string.substr(0, 1).toUpperCase() + string.substr(1); return string.substr(0, 1).toUpperCase() + string.substr(1);
} }

View File

@ -1,4 +1,6 @@
function hsvToRgb(h, s, v) { type RGB = { r: number; g: number; b: number };
function hsvToRgb(h: number, s: number, v: number): RGB {
let r; let r;
let g; let g;
let b; let b;
@ -51,11 +53,8 @@ function hsvToRgb(h, s, v) {
/** /**
* Convert the given string to a unique color. * Convert the given string to a unique color.
*
* @param {String} string
* @return {String}
*/ */
export default function stringToColor(string) { export default function stringToColor(string: string): string {
let num = 0; let num = 0;
// Convert the username into a number based on the ASCII value of each // Convert the username into a number based on the ASCII value of each