Skip to content

Commit

Permalink
Типографирование HTML-атрибутов
Browse files Browse the repository at this point in the history
  • Loading branch information
hcodes committed Apr 21, 2017
1 parent cd63a29 commit 4e08ade
Show file tree
Hide file tree
Showing 18 changed files with 158 additions and 37 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,17 @@ tp.addSafeTag('<\\?php', '\\?>');
tp.execute(text);
```


### Типографирование HTML-атрибутов
Для типографирования HTML-атрибутов необходимо включить правило `common/html/processingAttrs`.
В правиле, по умолчанию, обрабатываются атрибуты `title` и `placeholder`.
```js
var tp = new Typograf({locale: ['ru', 'en-US']});
tp.enableRule('common/html/processingAttrs');
tp.setSetting('common/html/processingAttrs', 'attrs', ['title', 'placeholder', 'alt', 'data-attr', 'my-attr']);
```


### Сжатие с UglifyJS
Если `typograf.js` сжимается вместе с другими js-файлами в `UglifyJS`,
то необходимо использовать [опцию](http://lisperator.net/uglifyjs/compress) `ascii_only: false`, иначе типограф будет работать некорректно.
Expand Down
13 changes: 6 additions & 7 deletions src/data.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,15 @@ Typograf._mix(Typograf, {
* @returns {*}
*/
Typograf.prototype.getData = function(key) {
var str = '';
var locale = this._sessionPrefs ? this._sessionPrefs.locale : this._prefs.locale;

if (key.search('/') === -1) {
if (key === 'char') {
this._locale.forEach(function(item) {
str += Typograf.getData(item + '/' + key);
}, this);

return str;
return locale.map(function(item) {
return Typograf.getData(item + '/' + key);
}).join('');
} else {
return Typograf.getData(this._locale[0] + '/' + key);
return Typograf.getData(locale[0] + '/' + key);
}
} else {
return Typograf.getData(key);
Expand Down
48 changes: 35 additions & 13 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,9 @@
*/
function Typograf(prefs) {
this._prefs = typeof prefs === 'object' ? prefs : {};
this._prefs.locale = Typograf._prepareLocale(this._prefs.locale);
this._prefs.live = this._prefs.live || false;

this._locale = Typograf._prepareLocale(this._prefs.locale);

this._safeTags = new SafeTags();

this._settings = {};
Expand Down Expand Up @@ -182,22 +181,25 @@
* @returns {string}
*/
execute: function(text, prefs) {
var that = this;

text = '' + text;

if (!text) { return ''; }

prefs = prefs || {};
this._sessionPrefs = Typograf.deepCopy(this._prefs);
this._sessionPrefs.htmlEntity = prefs.htmlEntity || this._prefs.htmlEntity || {};
this._sessionPrefs.locale = Typograf._prepareLocale(prefs.locale, this._prefs.locale);
this._sessionPrefs.lineEnding = prefs.lineEnding || this._prefs.lineEnding;

var that = this;

this._locale = Typograf._prepareLocale(prefs.locale, this._prefs.locale);

if (!this._locale.length || !this._locale[0]) {
var locale = this._sessionPrefs.locale;
if (!locale.length || !locale[0]) {
throw Error('Not defined the property "locale".');
}

if (!Typograf.hasLocale(this._locale[0])) {
throw Error('"' + this._locale[0] + '" is not supported locale.');
if (!Typograf.hasLocale(locale[0])) {
throw Error('"' + locale[0] + '" is not supported locale.');
}

text = this._removeCR(text);
Expand All @@ -220,7 +222,7 @@

text = this._executeRules(text);

text = Typograf.HtmlEntities.restore(text, prefs.htmlEntity || this._prefs.htmlEntity || {});
text = Typograf.HtmlEntities.restore(text, this._sessionPrefs.htmlEntity);

text = this._executeRules(text, 'html-entities');

Expand All @@ -230,10 +232,12 @@

text = this._executeRules(text, 'end');

text = this._fixLineEnding(text, this._sessionPrefs.lineEnding);

this._isHTML = null;
this._locale = Typograf._prepareLocale(this._prefs.locale);
this._sessionPrefs = null;

return this._fixLineEnding(text, prefs.lineEnding || this._prefs.lineEnding);
return text;
},
/**
* Get a setting.
Expand Down Expand Up @@ -323,6 +327,24 @@

return this;
},
_cloneInstance: function(ruleFilter) {
var tp = new Typograf(this._sessionPrefs || this._prefs);
this._rules.forEach(function(rule) {
var ruleName = rule.name;
if (ruleFilter && !ruleFilter(rule)) {
tp.disableRule(ruleName);
return;
}

if (this.isEnabledRule(ruleName)) {
tp.enableRule(ruleName);
} else {
tp.disableRule(ruleName);
}
}, this);

return tp;
},
_executeRules: function(text, queue) {
queue = queue || 'default';

Expand All @@ -347,7 +369,7 @@
return text;
}

if ((rlocale === 'common' || rlocale === this._locale[0]) && this.isEnabledRule(rule.name)) {
if ((rlocale === 'common' || rlocale === this._sessionPrefs.locale[0]) && this.isEnabledRule(rule.name)) {
this._onBeforeRule && this._onBeforeRule(rule.name, text);
text = rule.handler.call(this, text, this._settings[rule.name]);
this._onAfterRule && this._onAfterRule(rule.name, text);
Expand Down
3 changes: 2 additions & 1 deletion src/rules/common/html/e-mail.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ Typograf.addRule({
'$1<a href="mailto:$2@$3.$4">$2@$3.$4</a>$5'
);
},
disabled: true
disabled: true,
htmlAttrs: false
});
3 changes: 2 additions & 1 deletion src/rules/common/html/nbr.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ Typograf.addRule({
handler: function(text) {
return text.replace(/([^\n>])\n(?=[^\n])/g, '$1<br/>\n');
},
disabled: true
disabled: true,
htmlAttrs: false
});
3 changes: 2 additions & 1 deletion src/rules/common/html/p.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@ Typograf.addRule({

return buffer.join(separator);
},
disabled: true
disabled: true,
htmlAttrs: false
});
30 changes: 30 additions & 0 deletions src/rules/common/html/processingAttrs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
Typograf.addRule({
name: 'common/html/processingAttrs',
queue: 'hide-safe-tags-own', // After "hide-safe-tags-own", before "hide-safe-tags-html".
handler: function(text, settings) {
var that = this,
tp = null,
reAttrs = new RegExp('(^|\\s)(' + settings.attrs.join('|') + ')=("[^"]*?"|\'[^\']*?\')', 'gi');

return text.replace(/(<[-\w]+\s)([^>]+?)>/g, function(match, tagName, attrs) {
var resultAttrs = attrs.replace(reAttrs, function(submatch, space, attrName, attrValue) {
tp = tp || that._cloneInstance(function(rule) {
return rule.htmlAttrs !== false;
});

var lquote = attrValue[0],
rquote = attrValue[attrValue.length - 1],
value = attrValue.slice(1, -1);

return space + attrName + '=' + lquote + tp.execute(value) + rquote;
});

return tagName + resultAttrs + '>';
});
},
settings: {
attrs: ['title', 'placeholder']
},
disabled: true,
htmlAttrs: false
});
4 changes: 4 additions & 0 deletions src/rules/common/html/processingAttrs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"en-US": "Processing HTML attributes",
"ru": "Типографирование HTML-атрибутов"
}
3 changes: 2 additions & 1 deletion src/rules/common/html/url.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,6 @@ Typograf.addRule({
return firstPart + fullUrl + '</a>';
});
},
disabled: true
disabled: true,
htmlAttrs: false
});
10 changes: 8 additions & 2 deletions src/rules/common/punctuation/delDoublePunctuation.spec.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
tests.push(['common/punctuation/delDoublePunctuation', [
['У меня была только синяя краска;; но,, несмотря на это,, я затеял нарисовать охоту.', 'У меня была только синяя краска; но, несмотря на это, я затеял нарисовать охоту.'],
['Никогда не отказывайся от малого в работе:: из малого строится великое.', 'Никогда не отказывайся от малого в работе: из малого строится великое.']
[
'У меня была только синяя краска;; но,, несмотря на это,, я затеял нарисовать охоту.',
'У меня была только синяя краска; но, несмотря на это, я затеял нарисовать охоту.'
],
[
'Никогда не отказывайся от малого в работе:: из малого строится великое.',
'Никогда не отказывайся от малого в работе: из малого строится великое.'
]
]]);
2 changes: 1 addition & 1 deletion src/rules/common/punctuation/quote.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Typograf.addRule({
name: 'common/punctuation/quote',
handler: function(text, commonSettings) {
var locale = this._locale[0],
var locale = this._sessionPrefs.locale[0],
localeSettings = commonSettings[locale];

if (!localeSettings) { return text; }
Expand Down
2 changes: 1 addition & 1 deletion src/rules/common/punctuation/quoteLink.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Typograf.addRule({
queue: 'show-safe-tags-html',
index: '+5',
handler: function(text) {
var quotes = this.getSetting('common/punctuation/quote', this._locale[0]);
var quotes = this.getSetting('common/punctuation/quote', this._sessionPrefs.locale[0]);

if (!quotes) { return text; }
var entities = Typograf.HtmlEntities,
Expand Down
3 changes: 2 additions & 1 deletion src/rules/ru/optalign/bracket.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
.replace(/( |\u00A0)\(/g, '<span class="typograf-oa-sp-lbracket">$1</span><span class="typograf-oa-lbracket">(</span>')
.replace(/^\(/gm, '<span class="typograf-oa-n-lbracket">(</span>');
},
disabled: true
disabled: true,
htmlAttrs: false
}).addInnerRule({
name: name,
queue: 'start',
Expand Down
3 changes: 2 additions & 1 deletion src/rules/ru/optalign/comma.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
var re = new RegExp('([' + this.getData('char') + '\\d\u0301]+), ', 'gi');
return text.replace(re, '$1<span class="typograf-oa-comma">,</span><span class="typograf-oa-comma-sp"> </span>');
},
disabled: true
disabled: true,
htmlAttrs: false
}).addInnerRule({
name: name,
queue: 'start',
Expand Down
3 changes: 2 additions & 1 deletion src/rules/ru/optalign/quote.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
.replace(reNewLine, '$1<span class="typograf-oa-n-lquote">$2</span>')
.replace(reInside, '$1<span class="typograf-oa-sp-lquote">$2</span><span class="typograf-oa-lquote">$3</span>');
},
disabled: true
disabled: true,
htmlAttrs: false
}).addInnerRule({
name: name,
queue: 'start',
Expand Down
4 changes: 2 additions & 2 deletions src/rules/ru/punctuation/exclamation.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Typograf.addRule({
live: false,
handler: function(text) {
return text
.replace(/(^|[^!])!{2}($|[^!])/, '$1!$2')
.replace(/(^|[^!])!{4}($|[^!])/, '$1!!!$2');
.replace(/(^|[^!])!{2}($|[^!])/gm, '$1!$2')
.replace(/(^|[^!])!{4}($|[^!])/gm, '$1!!!$2');
}
});
28 changes: 24 additions & 4 deletions src/rules/ru/punctuation/exclamation.spec.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,26 @@
tests.push(['ru/punctuation/exclamation', [
['!!', '!'],
['Ура!! ', 'Ура! '],
['!!!!', '!!!'],
['Ура!!!! ', 'Ура!!! ']
[
'!!',
'!'
],
[
'Ура!! ',
'Ура! '
],
[
'Ура!!\nУра!!',
'Ура!\nУра!'
],
[
'!!!!',
'!!!'
],
[
'Ура!!!! ',
'Ура!!! '
],
[
'Ура!!!!\nУра!!!!',
'Ура!!!\nУра!!!'
]
]]);
22 changes: 22 additions & 0 deletions test/test.rules.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,4 +197,26 @@ describe('russian specific tests', function() {
assert.equal(tp.execute(item), item);
});
});

it('should processing HTML attributes', function() {
const tp = new Typograf({locale: ['ru', 'en-US']});
tp.enableRule('common/html/processingAttrs');

[
[
'<p title=" Hello world!! " placeholder=" Hello world!! "> Hello world!! </p>',
'<p title="Hello world!" placeholder="Hello world!"> Hello world! </p>'
],
[
'<p data-title=" Hello world!! "> Hello world!! </p>',
'<p data-title=" Hello world!! "> Hello world! </p>'
],
[
'<p title=" Hello world!! "> Hello world!! </p>\n<p title=" Hello world!! "> Hello world!! </p>',
'<p title="Hello world!"> Hello world! </p>\n<p title="Hello world!"> Hello world! </p>'
]
].forEach(function(item) {
assert.equal(tp.execute(item[0]), item[1]);
});
});
});

0 comments on commit 4e08ade

Please sign in to comment.