Skip to content

Commit

Permalink
JS → TS
Browse files Browse the repository at this point in the history
  • Loading branch information
hcodes committed Nov 1, 2020
1 parent b073d5a commit 15572ca
Show file tree
Hide file tree
Showing 234 changed files with 3,299 additions and 2,775 deletions.
6 changes: 4 additions & 2 deletions .babelrc
@@ -1,3 +1,5 @@
{
"presets": ["@babel/preset-env"]
}
"presets": [
"@babel/preset-env"
]
}
2 changes: 1 addition & 1 deletion .eslintignore
Expand Up @@ -4,4 +4,4 @@ coverage/**
build/**
dist/**
node_modules/**
test/**
benchmark/**
26 changes: 10 additions & 16 deletions .eslintrc
@@ -1,4 +1,8 @@
{
"plugins": [
"@typescript-eslint"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
Expand Down Expand Up @@ -57,25 +61,15 @@
{
"SwitchCase": 1
}
],
"valid-jsdoc": [
2,
{
"prefer": {
"return": "returns"
},
"requireParamDescription": false,
"requireReturnDescription": false,
"requireReturn": false
}
]
},
"env": {
"node": true,
"mocha": true
},
"globals": {
"define": true
"jest": true
},
"extends": "eslint:recommended"
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
]
}
5 changes: 5 additions & 0 deletions CHANGELOG.md
@@ -1,5 +1,10 @@
# Changelog

# v7.0.0
- Кодовая база переписана на TypeScript.
- Поддержка ES Modules, `dist/typograf.esm.js` и `dist/typograf.all.esm.js`.
- Удалена поддержка старых версий Node.js < 12.

# v6.11.2
Исправлена ошибка в правиле `ru/punctuation/ano` #373.

Expand Down
29 changes: 16 additions & 13 deletions benchmark/benchmark.js
@@ -1,32 +1,32 @@
'use strict';

const fs = require('fs');
const Typograf = require('../build/typograf.js');

const tp = new Typograf({locale: 'ru'});
const beforeTimes = {};
const afterTimes = {};
const text = fs.readFileSync('./benchmark/war_and_peace.html').toString();
const text = fs.readFileSync('./war_and_peace.html').toString();

tp._onBeforeRule = function(name) { beforeTimes[name] = now(); };
tp._onAfterRule = function(name) { afterTimes[name] = now(); };
tp.onBeforeRule = rule => { beforeTimes[rule.name] = now(); };
tp.onAfterRule = rule => { afterTimes[rule.name] = now(); };

function now() {
const hrtime = process.hrtime();

return ( hrtime[0] * 1000000 + hrtime[1] / 1000 ) / 1000;
}

function calcTimes() {
const times = [];
let total = 0;

Object.keys(afterTimes).forEach(function(name) {
Object.keys(afterTimes).forEach(name => {
times.push({
name: name,
time: afterTimes[name] - beforeTimes[name]
});
});

times.sort(function(a, b) {
times.sort((a, b) => {
if (a.time < b.time) {
return 1;
} else if (a.time > b.time) {
Expand All @@ -36,7 +36,7 @@ function calcTimes() {
return 0;
});

times.forEach(function(item) {
times.forEach(item => {
total += item.time;
});

Expand All @@ -51,15 +51,18 @@ console.log(`Text length: ${text.length} symbols`);
const startTime = now();
const output = tp.execute(text);
const totalTime = now() - startTime;
console.log(`Total time: ${totalTime} ms`);

console.log(`Total time: ${totalTime.toFixed(2)} ms`);

const result = calcTimes();
console.log(`Total time in rules: ${result.total} ms`);
result.times.forEach(function(item, i) {

console.log(`Total time in rules: ${result.total.toFixed(2)} ms`);
result.times.forEach((item, i) => {
const time = Math.floor(item.time * 1000) / 1000;

if (item.time) {
console.log(`${i + 1}. ${item.name}: ${time} ms`);
console.log(`${i + 1}. ${item.name}: ${time.toFixed(2)} ms`);
}
});

fs.writeFileSync('./benchmark/output.html', output);
fs.writeFileSync('./output.html', output);
196 changes: 98 additions & 98 deletions docs/RULES.en-US.md

Large diffs are not rendered by default.

196 changes: 98 additions & 98 deletions docs/RULES.ru.md

Large diffs are not rendered by default.

196 changes: 98 additions & 98 deletions docs/RULES_SORTED.en-US.md

Large diffs are not rendered by default.

196 changes: 98 additions & 98 deletions docs/RULES_SORTED.ru.md

Large diffs are not rendered by default.

8 changes: 6 additions & 2 deletions docs/api_attrs.md
Expand Up @@ -2,9 +2,13 @@
Для типографирования HTML-атрибутов необходимо включить правило `common/html/processingAttrs`.
В правиле, по умолчанию, обрабатываются атрибуты `title` и `placeholder`.
```js
var tp = new Typograf({locale: ['ru', 'en-US']});
const tp = new Typograf({locale: ['ru', 'en-US']});
tp.enableRule('common/html/processingAttrs');

// Дополнительно будем типографировать атрибуты alt и my-attr.
tp.setSetting('common/html/processingAttrs', 'attrs', ['title', 'placeholder', 'alt', 'my-attr']);
tp.setSetting(
'common/html/processingAttrs',
'attrs',
['title', 'placeholder', 'alt', 'my-attr']
);
```
6 changes: 3 additions & 3 deletions docs/api_entities.md
Expand Up @@ -11,13 +11,13 @@
## Примеры
HTML-сущности готовыми символами, по умолчанию:
```js
var tp = new Typograf({locale: ['ru', 'en-US']});
const tp = new Typograf({locale: ['ru', 'en-US']});
tp.execute('12 кг...'); // 12 кг…
```

HTML-сущности в виде имён:
```js
var tp = new Typograf({
const tp = new Typograf({
locale: ['ru', 'en-US'],
htmlEntity: {type: 'name'}
});
Expand All @@ -26,7 +26,7 @@ tp.execute('12 кг...'); // 12&nbsp;кг&hellip;

HTML-сущности в виде цифр:
```js
var tp = new Typograf({
const tp = new Typograf({
locale: ['ru', 'en-US'],
htmlEntity: {type: 'digit'}
});
Expand Down
5 changes: 4 additions & 1 deletion docs/api_fly.md
@@ -1,6 +1,9 @@
# Типографика на лету
Данный live-режим необходим, если текст типографируется на каждый ввод символа в текстовых полях.
```js
var tp = new Typograf({locale: ['ru', 'en-US'], live: true});
const tp = new Typograf({
locale: ['ru', 'en-US'],
live: true
});
```
[Подробнее](https://github.com/typograf/jquery-typograf)
6 changes: 3 additions & 3 deletions docs/api_localization.md
Expand Up @@ -6,15 +6,15 @@
// Выполняются правила "common/*" и "ru/*".
// Кавычки русские.
// Расстановка неразрывных пробелов только между русскими словами.
var tpRu = new Typograf({locale: 'ru'});
const tpRu = new Typograf({locale: 'ru'});

// Выполняются правила "common/*" и "ru/*".
// Кавычки русские.
// Расстановка неразрывных пробелов между русскими и английскими словами.
var tpRuEn = new Typograf({locale: ['ru', 'en-US']});
const tpRuEn = new Typograf({locale: ['ru', 'en-US']});

// Выполняются правила "common/*" и "en-US/*".
// Кавычки английские.
// Расстановка неразрывных пробелов между русскими и английскими словами.
var tpEnRu = new Typograf({locale: ['en-US', 'ru']});
const tpEnRu = new Typograf({locale: ['en-US', 'ru']});
```
2 changes: 1 addition & 1 deletion docs/api_nbsp.md
@@ -1,7 +1,7 @@
# Неразрывные пробелы
По умолчанию типограф не заменяет неразрывные пробелы на обычные, чтобы не удалить ранее проставленные неразрывные пробелы. Если в тексте неправильно расставлены неразрывные пробелы, включите правило `common/nbsp/replaceNbsp`.
```js
var tp = new Typograf({locale: ['ru', 'en-US']});
const tp = new Typograf({locale: ['ru', 'en-US']});
tp.enableRule('common/nbsp/replaceNbsp');
```

Expand Down
2 changes: 1 addition & 1 deletion docs/api_optalign.md
Expand Up @@ -3,7 +3,7 @@

Для включения необходимо подключить правила `ru/optalign/*`:
```js
var Typograf = require('typograf'),
const Typograf = require('typograf'),
tp = new Typograf({locale: ['ru', 'en-US']});

tp.enableRule('ru/optalign/*');
Expand Down
2 changes: 1 addition & 1 deletion docs/api_parts.md
@@ -1,6 +1,6 @@
# Отключение типографирования в участках текста
```js
var tp = new Typograf({locale: ['ru', 'en-US']});
const tp = new Typograf({locale: ['ru', 'en-US']});

// Отключить типографирование внутри тега <no-typography>
tp.addSafeTag('<no-typography>', '</no-typography>');
Expand Down
7 changes: 4 additions & 3 deletions docs/api_rules.md
@@ -1,6 +1,7 @@
## Включить или отключить правила
```js
var tp = new Typograf({locale: ['ru', 'en-US']});
const tp = new Typograf({locale: ['ru', 'en-US']});

tp.enableRule('ru/money/ruble'); // Включить правило
tp.enableRule('ru/money/*'); // Включить все правила в группе
tp.enableRule('*'); // Включить все правила
Expand All @@ -12,7 +13,7 @@ tp.disableRule('*'); // Отключить все правила

## Изменить настройку у правила
```js
var tp = new Typograf({locale: ['ru', 'en-US']});
const tp = new Typograf({locale: ['ru', 'en-US']});

// Название правила, название настройки, значение

Expand All @@ -31,7 +32,7 @@ tp.setSetting('common/nbsp/afterShortWord', 'lengthShortWord', 3);
// Типографический смайлик
Typograf.addRule({
name: 'common/other/typographicSmiley',
handler: function (text) {
handler: text => {
return text.replace(/:-\)/g, ':—)');
}
});
Expand Down
20 changes: 14 additions & 6 deletions docs/using.md
Expand Up @@ -11,7 +11,7 @@ npm install typograf
```HTML
<script src="./node_modules/typograf/dist/typograf.min.js"></script>
<script>
var tp = new Typograf({locale: ['ru', 'en-US']});
const tp = new Typograf({locale: ['ru', 'en-US']});
alert(tp.execute(' Мир - мой мир!! '));
</script>
```
Expand All @@ -22,8 +22,8 @@ npm install typograf
<script src="./node_modules/typograf/dist/typograf.min.js"></script>
<script>
(function() {
var tp = new Typograf({locale: ['ru', 'en-US']});
var elem = document.querySelector('.example');
const tp = new Typograf({locale: ['ru', 'en-US']});
const elem = document.querySelector('.example');
elem.innerHTML = tp.execute(elem.innerHTML);
})();
</script>
Expand All @@ -35,9 +35,9 @@ npm install typograf
<script src="./node_modules/typograf/dist/typograf.min.js"></script>
<script>
(function() {
var tp = new Typograf({locale: ['ru', 'en-US']});
var elem = document.querySelector('input.my-text');
document.querySelector('button.do').addEventListener('click', function() {
const tp = new Typograf({locale: ['ru', 'en-US']});
const elem = document.querySelector('input.my-text');
document.querySelector('button.do').addEventListener('click', () => {
elem.value = tp.execute(elem.value);
}, false);
})();
Expand All @@ -51,3 +51,11 @@ const tp = new Typograf({locale: ['ru', 'en-US']});

console.log(tp.execute(' Мир - мой мир!! '));
```

## ES6 Modules or TypeScript
```js
import Typograf from 'typograf';
const tp = new Typograf({locale: ['ru', 'en-US']});

console.log(tp.execute(' Мир - мой мир!! '));
```
16 changes: 12 additions & 4 deletions gulpfile.js/index.js
Expand Up @@ -11,10 +11,12 @@ const taskJsonLintGroups = require('./tasks/jsonLintGroups');
const taskJsonGroups = require('./tasks/jsonGroups');
const taskJsonRules = require('./tasks/jsonRules');

const taskJs = require('./tasks/js');
const taskTs = require('./tasks/ts');
const taskTsES6 = require('./tasks/ts.es');
const taskMinJs = require('./tasks/minJs');

const taskAllJs = require('./tasks/allJs');
const taskAllTs = require('./tasks/allTs');
const taskAllTsES6 = require('./tasks/allTs.es');
const taskAllMinJs = require('./tasks/allMinJs');

gulp.task('default', gulp.series(
Expand All @@ -25,7 +27,10 @@ gulp.task('default', gulp.series(
taskJsonLintGroups,
taskJsonGroups
),
taskJs,
gulp.parallel(
taskTs,
taskTsES6
),
gulp.parallel(
taskJsonRules,
taskMinJs
Expand All @@ -35,7 +40,10 @@ gulp.task('default', gulp.series(
gulp.task('dist',
gulp.series(
'default',
taskAllJs,
gulp.parallel(
taskAllTs,
taskAllTsES6,
),
taskAllMinJs,
function dist() {
return gulp.src(`${paths.dir.build}typograf.*`)
Expand Down
6 changes: 3 additions & 3 deletions gulpfile.js/paths.js
Expand Up @@ -5,9 +5,9 @@ module.exports = {
build: './build/',
dist: './dist/'
},
js: {
index: 'src/index.js',
all: 'src/index_all.js'
ts: {
index: 'src/index.ts',
all: 'src/index.all.ts'
},
json: {
rules: [
Expand Down
27 changes: 0 additions & 27 deletions gulpfile.js/tasks/allJs.js

This file was deleted.

0 comments on commit 15572ca

Please sign in to comment.