source: node_modules/minim/README.md@ d24f17c

main
Last change on this file since d24f17c was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

  • Property mode set to 100644
File size: 18.0 KB
RevLine 
[d24f17c]1# Minim
2
3
4A library for interacting with [Refract elements](https://github.com/refractproject/refract-spec).
5
6## Install
7
8```shell
9$ npm install minim
10```
11
12## About
13
14In working with the XML-based DOM, there is a limitation on what types are available in the document. Element attributes may only be strings, and element values can only be strings, mixed types, and nested elements.
15
16JSON provides additional types, which include objects, arrays, booleans, and nulls. A plain JSON document, though, provides no structure and no attributes for each property and value in the document.
17
18Refract is a JSON structure for JSON documents to make a more flexible document object model. In Refract, each element has three components:
19
201. Name of the element
211. Metadata
221. Attributes
231. Content (which can be of different elements depending on the element)
24
25An element ends up looking like this:
26
27```javascript
28const element = {
29 element: 'string',
30 content: 'bar'
31};
32```
33
34## Usage
35
36### Converting JavaScript Values into Elements
37
38```javascript
39var minim = require('minim').namespace();
40var arrayElement = minim.toElement([1, 2, 3]);
41var refract = minim.toRefract(arrayElement);
42```
43
44The `refract` variable above has the following JSON value.
45
46```json
47{
48 "element": "array",
49 "content": [
50 {
51 "element": "number",
52 "content": 1
53 },
54 {
55 "element": "number",
56 "content": 2
57 },
58 {
59 "element": "number",
60 "content": 3
61 }
62 ]
63}
64```
65
66### Converting Serialized Refract into Elements
67
68Serialized Refract can be converted back to Minim elements to make a roundtrip.
69
70```javascript
71var arrayElement1 = minim.toElement([1, 2, 3]);
72var refracted = minim.toRefract(arrayElement1);
73var arrayElement2 = minim.fromRefract(refracted);
74```
75
76Note that due to optional refracting in `meta`, anything that looks like an element in the given serialization will be loaded as such.
77
78### Extending elements
79
80You can extend elements using the `extend` static method.
81
82```javascript
83var StringElement = minim.getElementClass('string');
84var NewElement = StringElement.extend({
85 constructor: function() {
86 this.__super();
87 },
88
89 customMethod: function() {
90 // custom code here
91 }
92})
93```
94
95### Element Attributes
96
97Each Minim element provides the following attributes:
98
99- element (string) - The name of the element
100- meta (object) - The element's metadata
101- attributes (object) - The element's attributes
102- content - The element's content, e.g. a list of other elements.
103
104Additionally, convenience attributes are exposed on the element:
105
106- id (StringElement) - Shortcut for `.meta.get('id')`.
107- name (StringElement) - Shortcut for `.meta.get('name')`.
108- classes (ArrayElement) - Shortcut for `.meta.get('classes')`.
109- title (StringElement) - Shortcut for `.meta.get('title')`.
110- description (StringElement) - Shortcut for `.meta.get('description')`.
111
112### Element Methods
113
114Each Minim element provides the following methods.
115
116#### toValue
117
118The `toValue` method returns the JSON value of the Minim element.
119
120```javascript
121var arrayElement = minim.toElement([1, 2, 3]);
122var arrayValue = arrayElement.toValue(); // [1, 2, 3]
123```
124
125#### toRef
126
127The `toRef` method returns a RefElement referencing the element.
128
129```javascript
130var ref = element.toRef();
131```
132
133`toRef` accepts an optional path.
134
135```javascript
136var ref = element.toRef('attributes');
137```
138
139#### equals
140
141Allows for testing equality with the content of the element.
142
143```javascript
144var stringElement = minim.toElement("foobar");
145stringElement.equals('abcd'); // returns false
146```
147
148#### clone
149
150Creates a clone of the given instance.
151
152```javascript
153var stringElement = minim.toElement("foobar");
154var stringElementClone = stringElement.clone();
155```
156
157#### findRecursive
158
159Recursively find an element. Returns an ArrayElement containing all elements
160that match the given element name.
161
162```javascript
163const strings = element.findRecursive('string');
164```
165
166You may pass multiple element names to `findRecursive`. When multiple element
167names are passed down, minim will only find an element that is found within
168the other given elements. For example, we can pass in `member` and `string` so
169that we are recursively looking for all `string` elements that are found within a
170`member` element:
171
172```javascript
173const stringInsideMembers = element.findRecursive('member', 'string');
174```
175
176#### children
177
178The `children` property returns an `ArrayElement` containing all of the direct children elements.
179
180```javascript
181var arrayElement = minim.toElement(['a', [1, 2], 'b', 3]);
182var numbers = arrayElement.children(function(el) {
183 return el.element === 'number';
184}).toValue(); // [3]
185```
186
187#### recursiveChildren
188
189The `recursiveChildren` property returns an `ArrayElement` containing all of the children elements recursively.
190
191```javascript
192var arrayElement = minim.toElement(['a', [1, 2], 'b', 3]);
193var children = arrayElement.recursiveChildren;
194children.toValue(); // ['a', 1, 2, 'b', 3]
195```
196
197##### Chaining
198
199```javascript
200var evenNumbers = array
201 .recursiveChildren
202 .findByElement('number')
203 .filter((element) => element.toValue() % 2)
204```
205
206### Minim Elements
207
208Minim supports the following primitive elements
209
210#### NullElement
211
212This is an element for representing the `null` value.
213
214#### StringElement
215
216This is an element for representing string values.
217
218##### set
219
220The `set` method sets the value of the `StringElement` instance.
221
222```javascript
223var stringElement = minim.toElement('');
224stringElement.set('foobar');
225var value = stringElement.toValue() // toValue() returns 'foobar'
226```
227
228#### NumberElement
229
230This is an element for representing number values.
231
232##### set
233
234The `set` method sets the value of the `NumberElement` instance.
235
236```javascript
237var numberElement = minim.toElement(0);
238numberElement.set(4);
239var value = numberElement.toValue() // toValue() returns 4
240```
241
242#### BooleanElement
243
244This is an element for representing boolean values.
245
246##### set
247
248The `set` method sets the value of the `BooleanElement` instance.
249
250```javascript
251var booleanElement = minim.toElement(false);
252booleanElement.set(true);
253var value = booleanElement.toValue() // toValue() returns true
254```
255
256#### ArrayElement
257
258This is an element for representing arrays.
259
260##### Iteration
261
262The array element is iterable if the environment supports the [iteration protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable). You can then use the element in `for ... of` loops, use the spread operator, `yield*`, and destructuring assignment.
263
264```js
265const arrayElement = minim.toElement(['a', 'b', 'c']);
266
267for (let item of arrayElement) {
268 console.log(item);
269}
270```
271
272##### get
273
274The `get` method returns the item of the `ArrayElement` instance at the given index.
275
276```javascript
277var arrayElement = minim.toElement(['a', 'b', 'c']);
278var value = arrayElement.get(0) // get(0) returns item for 'a'
279```
280
281##### getValue
282
283The `getValue` method returns the value of the item of the `ArrayElement` instance at the given index.
284
285```javascript
286var arrayElement = minim.toElement(['a', 'b', 'c']);
287var value = arrayElement.getValue(0) // get(0) returns 'a'
288```
289
290##### getIndex
291
292The `getIndex` method returns the item of the array at a given index.
293
294```javascript
295var arrayElement = minim.toElement(['a', 'b', 'c']);
296var value = arrayElement.getIndex(0) // returns the item for 'a'
297```
298
299##### set
300
301The `set` method sets the value of the `ArrayElement` instance.
302
303```javascript
304var arrayElement = minim.toElement([]);
305arrayElement.set(0, 'z');
306var value = arrayElement.get(0) // get(0) returns 'z'
307```
308
309##### remove
310
311The `remove` method removes an item (specified by index) from the `ArrayElement` instance.
312
313```javascript
314var arrayElement = minim.toElement(['a', 'b', 'c']);
315arrayElement.remove(0);
316var value = arrayElement.get(0) // returns 'b'
317```
318
319##### map
320
321The `map` method may be used to map over an array. Each item given is a Minim instance.
322
323```javascript
324var arrayElement =minim.toElement(['a', 'b', 'c']);
325var newArray = arrayElement.map(function(item) {
326 return item.element;
327}); // newArray is now ['string', 'string', 'string']
328```
329
330##### filter
331
332The `filter` method may be used to filter a Minim array. This method returns a Minim array itself rather than a JavaScript array instance.
333
334```javascript
335var arrayElement = minim.toElement(['a', 'b', 'c']);
336var newArray = arrayElement.filter(function(item) {
337 return item.toValue() === 'a'
338}); // newArray.toValue() is now ['a']
339```
340
341##### reduce
342
343The `reduce` method may be used to reduce over a Minim array or object. The method takes a function and an optional beginning value.
344
345```javascript
346var numbers = minim.toElement([1, 2, 3, 4]);
347var total = numbers.reduce(function(result, item) {
348 return result.toValue() + item.toValue();
349}); // total.toValue() === 10
350```
351
352The `reduce` method also takes an initial value, which can either be a value or Minim element.
353
354```javascript
355var numbers = minim.toElement([1, 2, 3, 4]);
356var total = numbers.reduce(function(result, item) {
357 return result.toValue() + item.toValue();
358}, 10); // total.toValue() === 20
359```
360
361The `reduce` method also works with objects:
362
363```javascript
364var objNumbers = minim.toElement({a: 1, b:2, c:3, d:4});
365var total = objNumbers.reduce(function(result, item) {
366 return result.toValue() + item.toValue();
367}, 10); // total.toValue() === 20
368```
369
370The function passed to `reduce` can accept up to five optional parameters and depends on whether you are using an array element or object element:
371
372**Array**
3731. `result`: the reduced value thus far
3742. `item`: the current item in the array
3753. `index`: the zero-based index of the current item in the array
3764. `arrayElement`: the array element which contains `item` (e.g. `numbers` above)
377
378**Object**
3791. `result`: the reduced value thus far
3802. `item`: the value element of the current item in the object
3813. `key`: the key element of the current item in the object
3824. `memberElement`: the member element which contains `key` and `value`
3835. `objectElement`: the object element which contains `memberElement` (e.g. `objNumbers` above)
384
385##### forEach
386
387The `forEach` method may be used to iterate over a Minim array.
388
389```javascript
390var arrayElement = minim.toElement(['a', 'b', 'c']);
391arrayElement.forEach(function(item) {
392 console.log(item.toValue())
393}); // logs each value to console
394```
395
396##### shift
397
398The `shift` method may be used to remove an item from the start of a Minim array.
399
400```javascript
401var arrayElement = minim.toElement(['a', 'b', 'c']);
402var element = arrayElement.shift();
403console.log(element.toValue()); // a
404```
405
406##### unshift
407
408The `unshift` method may be used to inserts items to the start of a Minim array.
409
410```javascript
411var arrayElement = minim.toElement(['a', 'b', 'c']);
412arrayElement.unshift('d');
413console.log(arrayElement.toValue()); // ['d', 'a', 'b', 'c']
414```
415
416##### push
417
418The `push` method may be used to add items to a Minim array.
419
420```javascript
421var arrayElement = minim.toElement(['a', 'b', 'c']);
422arrayElement.push('d');
423console.log(arrayElement.toValue()); // ['a', 'b', 'c', 'd']
424```
425
426##### find
427
428The `find` method traverses the entire descendent element tree and returns an `ArrayElement` of all elements that match the conditional function given.
429
430```javascript
431var arrayElement = minim.toElement(['a', [1, 2], 'b', 3]);
432var numbers = arrayElement.find(function(el) {
433 return el.element === 'number'
434}).toValue(); // [1, 2, 3]
435```
436
437##### findByClass
438
439The `findByClass` method traverses the entire descendent element tree and returns an `ArrayElement` of all elements that match the given class.
440
441##### findByElement
442
443The `findByElement` method traverses the entire descendent element tree and returns an `ArrayElement` of all elements that match the given element name.
444
445##### getById
446
447Search the entire tree to find a matching ID.
448
449```javascript
450elTree.getById('some-id');
451```
452
453##### includes
454
455Test to see if a collection includes the value given. Does a deep equality check.
456
457```javascript
458var arrayElement = minim.toElement(['a', [1, 2], 'b', 3]);
459arrayElement.includes('a'); // returns true
460```
461
462##### length
463
464Returns the amount of items in the array element.
465
466```javascript
467arrayElement.length;
468```
469
470##### isEmpty
471
472Returns whether the array element is empty.
473
474```javascript
475if (arrayElement.isEmpty) {
476 console.log("We have an empty array");
477}
478```
479
480##### first
481
482Returns the first element in the collection.
483
484```javascript
485var arrayElement = minim.toElement(['a', [1, 2], 'b', 3]);
486arrayElement.first; // returns the element for "a"
487```
488
489##### second
490
491Returns the second element in the collection.
492
493```javascript
494var arrayElement = minim.toElement(['a', [1, 2], 'b', 3]);
495arrayElement.second; // returns the element for "[1, 2]"
496```
497
498##### last
499
500Returns the last element in the collection.
501
502```javascript
503var arrayElement = minim.toElement(['a', [1, 2], 'b', 3]);
504arrayElement.last; // returns the element for "3"
505```
506
507#### ObjectElement
508
509This is an element for representing objects. Objects store their items as an ordered array, so they inherit most of the methods above from the `ArrayElement`.
510
511##### get
512
513The `get` method returns the `ObjectElement` instance at the given name.
514See `getKey` and `getMember` for ways to get more instances around a key-value pair.
515
516```javascript
517var objectElement = minim.toElement({ foo: 'bar' });
518var value = objectElement.get('foo') // returns string instance for 'bar'
519```
520
521##### getValue
522
523The `getValue` method returns the value of the `ObjectElement` instance at the given name.
524
525```javascript
526var objectElement = minim.toElement({ foo: 'bar' });
527var value = objectElement.getValue('foo') // returns 'bar'
528```
529
530##### getKey
531
532The `getKey` method returns the key element of a key-value pair.
533
534```javascript
535var objectElement = minim.toElement({ foo: 'bar' });
536var key = objectElement.getKey('foo') // returns the key element instance
537```
538
539##### getMember
540
541The `getMember` method returns the entire member for a key-value pair.
542
543```javascript
544var objectElement = minim.toElement({ foo: 'bar' });
545var member = objectElement.getMember('foo') // returns the member element
546var key = member.key; // returns what getKey('foo') returns
547var value = member.value; // returns what get('foo') returns
548```
549
550##### set
551
552The `set` method sets the value of the `ObjectElement` instance.
553
554```javascript
555var objectElement = minim.toElement({});
556objectElement.set('foo', 'hello world');
557var value = objectElement.get('foo') // get('foo') returns 'hello world'
558```
559
560##### keys
561
562The `keys` method returns an array of keys.
563
564```javascript
565var objectElement = minim.toElement({ foo: 'bar' });
566var keys = objectElement.keys() // ['foo']
567```
568
569##### remove
570
571The `remove` method removes a key from the `ObjectElement` instance.
572
573```javascript
574var objectElement = minim.toElement({ foo: 'bar' });
575objectElement.remove('foo');
576var keys = objectElement.keys() // []
577```
578
579> You can use elementa.meta.remove() or element.attributes.remove() because of this.
580
581##### values
582
583The `values` method returns an array of keys.
584
585```javascript
586var objectElement = minim.toElement({ foo: 'bar' });
587var values = objectElement.values() // ['bar']
588```
589
590##### items
591
592The `items` method returns an array of key value pairs which can make iteration simpler.
593
594```js
595const objectElement = minim.toElement({ foo: 'bar' });
596
597for (let [key, value] of objectElement.items()) {
598 console.log(key, value); // foo, bar
599}
600```
601
602##### map, filter, reduce, and forEach
603
604The `map`, `filter`, and `forEach` methods work similar to the `ArrayElement` map function, but the callback receives the value, key, and member element instances. The `reduce` method receives the reduced value, value, key, member, and object element instances.
605
606See `getMember` to see more on how to interact with member elements.
607
608```js
609const objectElement = minim.toElement({ foo: 'bar' });
610const values = objectElement.map((value, key, member) => {
611 // key is an instance for foo
612 // value is an instance for bar
613 // member is an instance for the member element
614 return [key.toValue(), value.toValue()]; // ['foo', 'bar']
615});
616```
617
618### Namespace
619
620#### Namespace Methods
621
622##### `toRefract`
623
624The `toRefract` method returns the Refract value of the Minim element.
625
626Note that if any element in `meta` has metadata or attributes defined that would be lost by calling `toValue()` then that element is also converted to refract.
627
628```javascript
629var arrayElement = namespace.toElement([1, 2, 3]);
630var refract = namespace.toRefract();
631```
632
633#### Customizing Namespaces
634
635Minim allows you to register custom elements. For example, if the element name you wish to handle is called `category` and it should be handled like an array:
636
637```javascript
638var minim = require('minim').namespace();
639var ArrayElement = minim.getElementClass('array');
640
641// Register your custom element
642minim.register('category', ArrayElement);
643
644// Load serialized refract elements that includes the new element
645var elements = minim.fromRefract({
646 element: 'category',
647 meta: {},
648 attributes: {},
649 content: [
650 {
651 element: 'string',
652 meta: {},
653 attributes: {},
654 content: 'hello, world'
655 }
656 ]
657});
658
659console.log(elements.get(0).content); // hello, world
660
661// Unregister your custom element
662minim.unregister('category');
663```
664
665#### Creating Namespace Plugins
666
667It is also possible to create plugin modules that define elements for custom namespaces. Plugin modules should export a single `namespace` function that takes an `options` object which contains an existing namespace to which you can add your elements:
668
669```javascript
670var minim = require('minim').namespace();
671
672// Define your plugin module (normally done in a separate file)
673var plugin = {
674 namespace: function(options) {
675 var base = options.base;
676 var ArrayElement = base.getElementClass('array');
677
678 base.register('category', ArrayElement);
679
680 return base;
681 }
682}
683
684// Load the plugin
685minim.use(plugin);
686```
687
688The `load` property may be used in addition to the `namespace` property when a plugin is not implementing a namespace.
689
690```javascript
691var minim = require('minim').namespace();
692
693// Define your plugin module (normally done in a separate file)
694var plugin = {
695 load: function(options) {
696 // Plugin code here
697 return base;
698 }
699}
700
701// Load the plugin
702minim.use(plugin);
703```
704
705### Chaining
706
707Methods may also be chained when using getters and setters.
708
709```javascript
710var objectElement = minim.toElement({})
711 .set('name', 'John Doe')
712 .set('email', 'john@example.com')
713 .set('id', 4)
714```
Note: See TracBrowser for help on using the repository browser.