-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunorphanize.jquery.js
307 lines (259 loc) · 11.3 KB
/
unorphanize.jquery.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
//------------------------------------------------------------------------
// jQuery Unorphanize Plugin
//
// Based on https://github.com/simeydotme/jquery-unorphanize
// Plugin boilerplate from https://github.com/jquery-boilerplate/jquery-boilerplate
// CommonJS module wrapper from http://blog.npmjs.org/post/112712169830/making-your-jquery-plugin-work-better-with-npm
//------------------------------------------------------------------------
//jshint shadow:true
// This function is called immediately. The second function is passed in
// as the factory parameter to this function.
// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
;(function (factory) {
// If there is a variable named module and it has an exports property,
// then we're working in a Node-like environment. Use require to load
// the jQuery object that the module system is using and pass it in.
if ( typeof module === 'object' && typeof module.exports === 'object' ) {
factory(require('jquery'), window, document);
}
// Otherwise, we're working in a browser, so just pass in the global
// jQuery object.
else {
factory(jQuery, window, document);
}
}(function($, window, document, undefined) {
// undefined is used here as the undefined global variable in ECMAScript 3 is
// mutable (ie. it can be changed by someone else). undefined isn't really being
// passed in so we can ensure the value of it is truly undefined. In ES5, undefined
// can no longer be modified.
// window and document are passed through as local variable rather than global
// as this (slightly) quickens the resolution process and can be more efficiently
// minified (especially when both are regularly referenced in your plugin).
// Array.prototype.filter polyfill for old browsers
// Source: https://github.com/Financial-Times/polyfill-service/blob/master/polyfills/Array.prototype.filter/polyfill.js
if ( !Array.prototype.filter ) {
Array.prototype.filter = function filter(callback) {
if (this === undefined || this === null) {
throw new TypeError(this + 'is not an object');
}
if (!(callback instanceof Function)) {
throw new TypeError(callback + ' is not a function');
}
var
object = Object(this),
scope = arguments[1],
arraylike = object instanceof String ? object.split('') : object,
length = Math.max(Math.min(arraylike.length, 9007199254740991), 0) || 0,
index = -1,
result = [],
element;
while (++index < length) {
element = arraylike[index];
if (index in arraylike && callback.call(scope, element, index, object)) {
result.push(element);
}
}
return result;
};
}
// Array.prototype.indexOf polyfill
// Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill
if ( !Array.prototype.indexOf ) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('“this” is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
// Create the defaults once
var pluginName = 'unorphanize',
defaults = {
words: 2,
wrapEl: '',
className: '',
append: ''
};
// The actual plugin constructor
function Plugin(element, options) {
this.element = element;
// jQuery has an extend method which merges the contents of two or
// more objects, storing the result in the first object. The first object
// is generally empty as we don't want to alter the default options for
// future instances of the plugin
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
// Avoid Plugin.prototype conflicts
$.extend(Plugin.prototype, {
init: function() {
// Place initialization logic here
// You already have access to the DOM element and
// the options via the instance, e.g. this.element
// and this.settings
// you can add more functions like the one below and
// call them like so: this.yourOtherFunction(this.element, this.settings).
var self = this;
var $el = $(this.element);
// Exit if no text
if ( $.trim( $el.text() ).length === 0 ) {
return false;
}
// Save html of element
this.text = $.trim( $el.html() );
// Find any STARTING html tags
this.startTags = this.text.match(/<([A-Z][A-Z0-9]*)\b[^>]*>/gi);
this.startTagsCount = ( this.startTags !== null ? this.startTags.length : 0 );
// Replace STARTING tags with placeholder (e.g. __0__)
this.startPlaceholders = [];
for ( var i = 0; i < this.startTagsCount; i++ ) {
// Push placeholder to array so we can replace it later
this.startPlaceholders.push('__' + i + '__');
// Replace tag with placeholder text
this.text = this.text.replace( self.startTags[i], self.startPlaceholders[i] );
}
// Find any ENDING html tags
this.endTags = this.text.match(/<\/[A-Z][A-Z0-9]*>/gi);
this.endTagsCount = ( this.endTags !== null ? this.endTags.length : 0 );
// Replace ENDING tags with different placeholder (e.g. ~~0~~)
this.endPlaceholders = [];
for ( var i = 0; i < this.endTagsCount; i++ ) {
// Push placeholder to array so we can replace it later
this.endPlaceholders.push('~~' + i + '~~');
// Replace tag with placeholder text
this.text = this.text.replace( self.endTags[i], self.endPlaceholders[i] );
}
// Create array of words from string
this.wordArray = this.text.split(/\s+/);
// Save the _word_ positions in the original array
var wordId = 1;
this.wordPositions = [];
// Create new array without any placeholder tags, which would throw off word count
this.cleanWordArray = this.wordArray.map( function(item, i) {
// Check for a single HTML tag replacement (e.g. <br> tag --> __1__)
if ( !!item.match(/__[0-9]+__\b/gi) || !!item.match(/~~[0-9]+~~\b/gi) ) {
// Increment wordID to help us track the word positions between the two arrays
wordId++;
return false;
}
else {
// Save word position
self.wordPositions.push(i);
return item;
}
});
// Remove false values from array
this.cleanWordArray = this.cleanWordArray.filter( function(value) { return value; } );
// Make sure word count is valid
if ( typeof this.settings.words !== 'number' || this.settings.words < 1 ) {
this.settings.words = this._defaults.words;
}
// If only 1 orphan is specified, default to wrapping word, not using
else if ( this.settings.words === 1 ) {
this.settings.wrapEl = ( this.settings.wrapEl.length ? this.settings.wrapEl : 'span' );
this.settings.className = ( this.settings.className.length ? this.settings.className : 'u-nowrap' );
}
// Don't allow orphan count to exceed the number of words
else if ( this.settings.words >= this.cleanWordArray.length ) {
this.settings.words = this.cleanWordArray.length;
}
// Find word where plugin should start
this.lastWordPos = this.cleanWordArray.length - this.settings.words;
// console.log('this.lastWordPos', this.lastWordPos, this.cleanWordArray[this.lastWordPos]);
// Find word position in original array
this.lastWordIndex = this.wordPositions[ this.lastWordPos ];
// console.log('this.lastWordIndex', this.lastWordIndex, this.wordArray[ this.lastWordPos ]);
// Split the original word array into two parts
this.firstPart = self.wordArray.slice( 0, self.lastWordIndex ).join(' ');
this.lastPart = self.wordArray.slice( self.lastWordIndex ).join(' ');
// Validate settings variables
if ( typeof this.settings.wrapEl !== 'string' ) {
this.settings.wrapEl = this._defaults.wrapEl;
}
if ( typeof this.settings.className !== 'string' ) {
this.settings.className = this._defaults.className;
}
if ( typeof this.settings.append !== 'string' ) {
this.settings.append = this._defaults.append;
}
// Add wrapper element
if ( !!this.settings.wrapEl ) {
this.text = this.firstPart + ' <' + this.settings.wrapEl + ' class="' + this.settings.className + '">' + this.lastPart + this.settings.append + '</' + this.settings.wrapEl + '>';
}
// Add entities
else {
this.lastPart = this.lastPart.split(' ').join(' ');
this.text = this.firstPart + ' ' + this.lastPart;
}
// Replace the STARTING tag placeholders with the original tag code
for( var i = 0; i < this.startTagsCount; i++ ) {
var replaceRegex = new RegExp( this.startPlaceholders[i] );
this.text = this.text.replace( replaceRegex , this.startTags[i] );
}
// Replace the ENDING tag placeholders with the original tag code
for( var i = 0; i < this.endTagsCount; i++ ) {
var replaceRegex = new RegExp( this.endPlaceholders[i] );
this.text = this.text.replace( replaceRegex , this.endTags[i] );
}
// Update the element's html
$el.html( this.text );
}
});
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[pluginName] = function(options) {
return this.each(function() {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin(this, options));
}
});
};
}));