// (C) Copyright 2015 Martin Dougiamas // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { Injectable } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { CoreLangProvider } from '../lang'; /* * "Utils" service with helper functions for text. */ @Injectable() export class CoreTextUtilsProvider { element = document.createElement('div'); // Fake element to use in some functions, to prevent re-creating it each time. constructor(private translate: TranslateService, private langProvider: CoreLangProvider) {} /** * Given a list of sentences, build a message with all of them wrapped in
. * * @param {string[]} messages Messages to show. * @return {string} Message with all the messages. */ buildMessage(messages: string[]) : string { let result = ''; messages.forEach((message) => { if (message) { result += `
${message}
`; } }); return result; } /** * Convert size in bytes into human readable format * * @param {number} bytes Number of bytes to convert. * @param {number} [precision=2] Number of digits after the decimal separator. * @return {string} Size in human readable format. */ bytesToSize(bytes: number, precision = 2) : string { if (typeof bytes == 'undefined' || bytes < 0) { return this.translate.instant('mm.core.notapplicable'); } if (precision < 0) { precision = 2; } let keys = ['mm.core.sizeb', 'mm.core.sizekb', 'mm.core.sizemb', 'mm.core.sizegb', 'mm.core.sizetb'], units = this.translate.instant(keys), pos = 0; if (bytes >= 1024) { while (bytes >= 1024) { pos++; bytes = bytes / 1024; } // Round to "precision" decimals if needed. bytes = Number(Math.round(parseFloat(bytes + 'e+' + precision)) + 'e-' + precision); } return this.translate.instant('mm.core.humanreadablesize', {size: bytes, unit: units[keys[pos]]}); } /** * Clean HTML tags. * * @param {string} text The text to be cleaned. * @param {boolean} [singleLine] True if new lines should be removed (all the text in a single line). * @return {string} Clean text. */ cleanTags(text: string, singleLine?: boolean) : string { if (!text) { return ''; } // First, we use a regexpr. text = text.replace(/(<([^>]+)>)/ig,""); // Then, we rely on the browser. We need to wrap the text to be sure is HTML. this.element.innerHTML = text; text = this.element.textContent; // Recover or remove new lines. text = this.replaceNewLines(text, singleLine ? ' ' : '