Skip to content

Commit

Permalink
Phase 6
Browse files Browse the repository at this point in the history
  • Loading branch information
hcodes committed Nov 1, 2020
1 parent 2c3ad8d commit 85e5896
Show file tree
Hide file tree
Showing 25 changed files with 125 additions and 41 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Expand Up @@ -5,3 +5,4 @@ build/**
dist/**
node_modules/**
test/**
benchmark/**
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,7 @@

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

# v6.11.2
Expand Down
21 changes: 11 additions & 10 deletions benchmark/benchmark.js
@@ -1,17 +1,17 @@
import { readFileSync, writeFileSync } from 'fs';
import Typograf from '../build/typograf.js';
const fs = require('fs');
const Typograf = require('../build/typograf.js');

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

const text = readFileSync('./benchmark/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;
}

Expand Down Expand Up @@ -52,16 +52,17 @@ 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`);
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`);
}
});

writeFileSync('./benchmark/output.html', output);
fs.writeFileSync('./output.html', output);
2 changes: 1 addition & 1 deletion docs/RULES.en-US.md
Expand Up @@ -91,7 +91,7 @@
| 87. | [ru/optalign/comma](../src/rules/ru/optalign/comma.ts) | for comma | 1010 | default | |
| 88. | [ru/optalign/quote](../src/rules/ru/optalign/quote.ts) | for opening quotation marks | 1010 | default | |
| 89. | [ru/other/accent](../src/rules/ru/other/accent.ts) | Replacement capital letters to lowercase with addition of accent | 910 | default | |
| 90. | [ru/other/phone-number](../src/rules/ru/other/phone-number.ts) | Formatting phone numbers | 910 | default ||
| 90. | [ru/other/phoneNumber](../src/rules/ru/other/phoneNumber.ts) | Formatting phone numbers | 910 | default ||
| 91. | [ru/punctuation/ano](../src/rules/ru/punctuation/ano.ts) | Placement of commas before “а” and “но” | 410 | hide-safe-tags-html ||
| 92. | [ru/punctuation/exclamation](../src/rules/ru/punctuation/exclamation.ts) | !! → ! | 410 | default ||
| 93. | [ru/punctuation/exclamationQuestion](../src/rules/ru/punctuation/exclamationQuestion.ts) | !? → ?! | 415 | default ||
Expand Down
2 changes: 1 addition & 1 deletion docs/RULES.ru.md
Expand Up @@ -91,7 +91,7 @@
| 87. | [ru/optalign/comma](../src/rules/ru/optalign/comma.ts) | для запятой | 1010 | default | |
| 88. | [ru/optalign/quote](../src/rules/ru/optalign/quote.ts) | для открывающей кавычки | 1010 | default | |
| 89. | [ru/other/accent](../src/rules/ru/other/accent.ts) | Замена заглавной буквы на строчную с добавлением ударения | 910 | default | |
| 90. | [ru/other/phone-number](../src/rules/ru/other/phone-number.ts) | Форматирование телефонных номеров | 910 | default ||
| 90. | [ru/other/phoneNumber](../src/rules/ru/other/phoneNumber.ts) | Форматирование телефонных номеров | 910 | default ||
| 91. | [ru/punctuation/ano](../src/rules/ru/punctuation/ano.ts) | Расстановка запятых перед «а» и «но» | 410 | hide-safe-tags-html ||
| 92. | [ru/punctuation/exclamation](../src/rules/ru/punctuation/exclamation.ts) | !! → ! | 410 | default ||
| 93. | [ru/punctuation/exclamationQuestion](../src/rules/ru/punctuation/exclamationQuestion.ts) | !? → ?! | 415 | default ||
Expand Down
2 changes: 1 addition & 1 deletion docs/RULES_SORTED.en-US.md
Expand Up @@ -86,7 +86,7 @@
| 82. | [ru/date/weekday](../src/rules/ru/date/weekday.ts) | 2 Мая, Понедельник → 2 мая, понедельник | 810 | default ||
| 83. | [common/other/repeatWord](../src/rules/common/other/repeatWord.ts) | Removing repeat words | 910 | default | |
| 84. | [ru/other/accent](../src/rules/ru/other/accent.ts) | Replacement capital letters to lowercase with addition of accent | 910 | default | |
| 85. | [ru/other/phone-number](../src/rules/ru/other/phone-number.ts) | Formatting phone numbers | 910 | default ||
| 85. | [ru/other/phoneNumber](../src/rules/ru/other/phoneNumber.ts) | Formatting phone numbers | 910 | default ||
| 86. | [common/number/digitGrouping](../src/rules/common/number/digitGrouping.ts) | Divide into groups numbers with many digits | 920 | default | |
| 87. | [ru/optalign/bracket](../src/rules/ru/optalign/bracket.ts) | for opening bracket | 1010 | default | |
| 88. | [ru/optalign/comma](../src/rules/ru/optalign/comma.ts) | for comma | 1010 | default | |
Expand Down
2 changes: 1 addition & 1 deletion docs/RULES_SORTED.ru.md
Expand Up @@ -86,7 +86,7 @@
| 82. | [ru/date/weekday](../src/rules/ru/date/weekday.ts) | 2 Мая, Понедельник → 2 мая, понедельник | 810 | default ||
| 83. | [common/other/repeatWord](../src/rules/common/other/repeatWord.ts) | Удаление повтора слова | 910 | default | |
| 84. | [ru/other/accent](../src/rules/ru/other/accent.ts) | Замена заглавной буквы на строчную с добавлением ударения | 910 | default | |
| 85. | [ru/other/phone-number](../src/rules/ru/other/phone-number.ts) | Форматирование телефонных номеров | 910 | default ||
| 85. | [ru/other/phoneNumber](../src/rules/ru/other/phoneNumber.ts) | Форматирование телефонных номеров | 910 | default ||
| 86. | [common/number/digitGrouping](../src/rules/common/number/digitGrouping.ts) | Разбивать длинные числа по разрядам | 920 | default | |
| 87. | [ru/optalign/bracket](../src/rules/ru/optalign/bracket.ts) | для открывающей скобки | 1010 | default | |
| 88. | [ru/optalign/comma](../src/rules/ru/optalign/comma.ts) | для запятой | 1010 | default | |
Expand Down
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(' Мир - мой мир!! '));
```
12 changes: 10 additions & 2 deletions gulpfile.js/index.js
Expand Up @@ -12,9 +12,11 @@ const taskJsonGroups = require('./tasks/jsonGroups');
const taskJsonRules = require('./tasks/jsonRules');

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

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
),
taskTs,
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',
taskAllTs,
gulp.parallel(
taskAllTs,
taskAllTsES6,
),
taskAllMinJs,
function dist() {
return gulp.src(`${paths.dir.build}typograf.*`)
Expand Down
29 changes: 29 additions & 0 deletions gulpfile.js/tasks/allTs.es.js
@@ -0,0 +1,29 @@
'use strict';

const replace = require('@rollup/plugin-replace');
const rollup = require('rollup');
const paths = require('../paths');
const babel = require('rollup-plugin-babel');
const typescript = require('rollup-plugin-typescript');
const version = require('../../package.json').version;

async function allTsES6() {
const bundle = await rollup.rollup({
input: paths.ts.all,
plugins: [
typescript(),
babel(),
replace({
'__version__': version,
})
]
});

return bundle.write({
file: `${paths.dir.build}typograf.all.esm.js`,
format: 'es',
});
}

module.exports = allTsES6;

28 changes: 28 additions & 0 deletions gulpfile.js/tasks/ts.es.js
@@ -0,0 +1,28 @@
'use strict';

const replace = require('@rollup/plugin-replace');
const rollup = require('rollup');
const paths = require('../paths');
const babel = require('rollup-plugin-babel');
const typescript = require('rollup-plugin-typescript');
const version = require('../../package.json').version;

async function tsES6() {
const bundle = await rollup.rollup({
input: paths.ts.index,
plugins: [
typescript(),
babel(),
replace({
'__version__': version,
})
]
});

return bundle.write({
file: `${paths.dir.build}typograf.esm.js`,
format: 'es',
});
}

module.exports = tsES6;
1 change: 0 additions & 1 deletion gulpfile.js/tasks/uglify.js
Expand Up @@ -4,7 +4,6 @@ module.exports = function uglify() {
return gulpUglify({
output: {
ascii_only: true,
comments: /^!/
}
});
};
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -8,6 +8,7 @@
"url": "https://github.com/typograf/typograf"
},
"main": "dist/typograf.js",
"module": "dist/typograf.esm.js",
"homepage": "https://github.com/typograf",
"license": "MIT",
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion src/rules/ru/other/index.ts
@@ -1,7 +1,7 @@
import Typograf from '../../../typograf';

import accent from './accent';
import phoneNumber from './phone-number';
import phoneNumber from './phoneNumber';

Typograf.addRules([
accent,
Expand Down
File renamed without changes.
@@ -1,6 +1,6 @@
import { typografRuleTest } from '../../../../test/helpers';

typografRuleTest(['ru/other/phone-number', [
typografRuleTest(['ru/other/phoneNumber', [
[' тел.: +74957397000', ' тел.: +7\u00A0495\u00A0739-70-00'],
[' ГОСТ 22222 ', ' ГОСТ 22222 '],
['тел.: 812 5551234', 'тел.: (812)\u00A0555-12-34'],
Expand Down

0 comments on commit 85e5896

Please sign in to comment.