Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. # pretty-format
  2. Stringify any JavaScript value.
  3. - Serialize built-in JavaScript types.
  4. - Serialize application-specific data types with built-in or user-defined plugins.
  5. ## Installation
  6. ```sh
  7. $ yarn add pretty-format
  8. ```
  9. ## Usage
  10. ```js
  11. const {format: prettyFormat} = require('pretty-format'); // CommonJS
  12. ```
  13. ```js
  14. import {format as prettyFormat} from 'pretty-format'; // ES2015 modules
  15. ```
  16. ```js
  17. const val = {object: {}};
  18. val.circularReference = val;
  19. val[Symbol('foo')] = 'foo';
  20. val.map = new Map([['prop', 'value']]);
  21. val.array = [-0, Infinity, NaN];
  22. console.log(prettyFormat(val));
  23. /*
  24. Object {
  25. "array": Array [
  26. -0,
  27. Infinity,
  28. NaN,
  29. ],
  30. "circularReference": [Circular],
  31. "map": Map {
  32. "prop" => "value",
  33. },
  34. "object": Object {},
  35. Symbol(foo): "foo",
  36. }
  37. */
  38. ```
  39. ## Usage with options
  40. ```js
  41. function onClick() {}
  42. console.log(prettyFormat(onClick));
  43. /*
  44. [Function onClick]
  45. */
  46. const options = {
  47. printFunctionName: false,
  48. };
  49. console.log(prettyFormat(onClick, options));
  50. /*
  51. [Function]
  52. */
  53. ```
  54. <!-- prettier-ignore -->
  55. | key | type | default | description |
  56. | :-------------------- | :-------- | :--------- | :------------------------------------------------------ |
  57. | `callToJSON` | `boolean` | `true` | call `toJSON` method (if it exists) on objects |
  58. | `escapeRegex` | `boolean` | `false` | escape special characters in regular expressions |
  59. | `escapeString` | `boolean` | `true` | escape special characters in strings |
  60. | `highlight` | `boolean` | `false` | highlight syntax with colors in terminal (some plugins) |
  61. | `indent` | `number` | `2` | spaces in each level of indentation |
  62. | `maxDepth` | `number` | `Infinity` | levels to print in arrays, objects, elements, and so on |
  63. | `min` | `boolean` | `false` | minimize added space: no indentation nor line breaks |
  64. | `plugins` | `array` | `[]` | plugins to serialize application-specific data types |
  65. | `printBasicPrototype` | `boolean` | `false` | print the prototype for plain objects and arrays |
  66. | `printFunctionName` | `boolean` | `true` | include or omit the name of a function |
  67. | `theme` | `object` | | colors to highlight syntax in terminal |
  68. Property values of `theme` are from [ansi-styles colors](https://github.com/chalk/ansi-styles#colors)
  69. ```js
  70. const DEFAULT_THEME = {
  71. comment: 'gray',
  72. content: 'reset',
  73. prop: 'yellow',
  74. tag: 'cyan',
  75. value: 'green',
  76. };
  77. ```
  78. ## Usage with plugins
  79. The `pretty-format` package provides some built-in plugins, including:
  80. - `ReactElement` for elements from `react`
  81. - `ReactTestComponent` for test objects from `react-test-renderer`
  82. ```js
  83. // CommonJS
  84. const React = require('react');
  85. const renderer = require('react-test-renderer');
  86. const {format: prettyFormat, plugins} = require('pretty-format');
  87. const {ReactElement, ReactTestComponent} = plugins;
  88. ```
  89. ```js
  90. // ES2015 modules and destructuring assignment
  91. import React from 'react';
  92. import renderer from 'react-test-renderer';
  93. import {plugins, format as prettyFormat} from 'pretty-format';
  94. const {ReactElement, ReactTestComponent} = plugins;
  95. ```
  96. ```js
  97. const onClick = () => {};
  98. const element = React.createElement('button', {onClick}, 'Hello World');
  99. const formatted1 = prettyFormat(element, {
  100. plugins: [ReactElement],
  101. printFunctionName: false,
  102. });
  103. const formatted2 = prettyFormat(renderer.create(element).toJSON(), {
  104. plugins: [ReactTestComponent],
  105. printFunctionName: false,
  106. });
  107. /*
  108. <button
  109. onClick=[Function]
  110. >
  111. Hello World
  112. </button>
  113. */
  114. ```
  115. ## Usage in Jest
  116. For snapshot tests, Jest uses `pretty-format` with options that include some of its built-in plugins. For this purpose, plugins are also known as **snapshot serializers**.
  117. To serialize application-specific data types, you can add modules to `devDependencies` of a project, and then:
  118. In an **individual** test file, you can add a module as follows. It precedes any modules from Jest configuration.
  119. ```js
  120. import serializer from 'my-serializer-module';
  121. expect.addSnapshotSerializer(serializer);
  122. // tests which have `expect(value).toMatchSnapshot()` assertions
  123. ```
  124. For **all** test files, you can specify modules in Jest configuration. They precede built-in plugins for React, HTML, and Immutable.js data types. For example, in a `package.json` file:
  125. ```json
  126. {
  127. "jest": {
  128. "snapshotSerializers": ["my-serializer-module"]
  129. }
  130. }
  131. ```
  132. ## Writing plugins
  133. A plugin is a JavaScript object.
  134. If `options` has a `plugins` array: for the first plugin whose `test(val)` method returns a truthy value, then `prettyFormat(val, options)` returns the result from either:
  135. - `serialize(val, …)` method of the **improved** interface (available in **version 21** or later)
  136. - `print(val, …)` method of the **original** interface (if plugin does not have `serialize` method)
  137. ### test
  138. Write `test` so it can receive `val` argument of any type. To serialize **objects** which have certain properties, then a guarded expression like `val != null && …` or more concise `val && …` prevents the following errors:
  139. - `TypeError: Cannot read property 'whatever' of null`
  140. - `TypeError: Cannot read property 'whatever' of undefined`
  141. For example, `test` method of built-in `ReactElement` plugin:
  142. ```js
  143. const elementSymbol = Symbol.for('react.element');
  144. const test = val => val && val.$$typeof === elementSymbol;
  145. ```
  146. Pay attention to efficiency in `test` because `pretty-format` calls it often.
  147. ### serialize
  148. The **improved** interface is available in **version 21** or later.
  149. Write `serialize` to return a string, given the arguments:
  150. - `val` which “passed the test”
  151. - unchanging `config` object: derived from `options`
  152. - current `indentation` string: concatenate to `indent` from `config`
  153. - current `depth` number: compare to `maxDepth` from `config`
  154. - current `refs` array: find circular references in objects
  155. - `printer` callback function: serialize children
  156. ### config
  157. <!-- prettier-ignore -->
  158. | key | type | description |
  159. | :------------------ | :-------- | :------------------------------------------------------ |
  160. | `callToJSON` | `boolean` | call `toJSON` method (if it exists) on objects |
  161. | `colors` | `Object` | escape codes for colors to highlight syntax |
  162. | `escapeRegex` | `boolean` | escape special characters in regular expressions |
  163. | `escapeString` | `boolean` | escape special characters in strings |
  164. | `indent` | `string` | spaces in each level of indentation |
  165. | `maxDepth` | `number` | levels to print in arrays, objects, elements, and so on |
  166. | `min` | `boolean` | minimize added space: no indentation nor line breaks |
  167. | `plugins` | `array` | plugins to serialize application-specific data types |
  168. | `printFunctionName` | `boolean` | include or omit the name of a function |
  169. | `spacingInner` | `strong` | spacing to separate items in a list |
  170. | `spacingOuter` | `strong` | spacing to enclose a list of items |
  171. Each property of `colors` in `config` corresponds to a property of `theme` in `options`:
  172. - the key is the same (for example, `tag`)
  173. - the value in `colors` is a object with `open` and `close` properties whose values are escape codes from [ansi-styles](https://github.com/chalk/ansi-styles) for the color value in `theme` (for example, `'cyan'`)
  174. Some properties in `config` are derived from `min` in `options`:
  175. - `spacingInner` and `spacingOuter` are **newline** if `min` is `false`
  176. - `spacingInner` is **space** and `spacingOuter` is **empty string** if `min` is `true`
  177. ### Example of serialize and test
  178. This plugin is a pattern you can apply to serialize composite data types. Side note: `pretty-format` does not need a plugin to serialize arrays.
  179. ```js
  180. // We reused more code when we factored out a function for child items
  181. // that is independent of depth, name, and enclosing punctuation (see below).
  182. const SEPARATOR = ',';
  183. function serializeItems(items, config, indentation, depth, refs, printer) {
  184. if (items.length === 0) {
  185. return '';
  186. }
  187. const indentationItems = indentation + config.indent;
  188. return (
  189. config.spacingOuter +
  190. items
  191. .map(
  192. item =>
  193. indentationItems +
  194. printer(item, config, indentationItems, depth, refs), // callback
  195. )
  196. .join(SEPARATOR + config.spacingInner) +
  197. (config.min ? '' : SEPARATOR) + // following the last item
  198. config.spacingOuter +
  199. indentation
  200. );
  201. }
  202. const plugin = {
  203. test(val) {
  204. return Array.isArray(val);
  205. },
  206. serialize(array, config, indentation, depth, refs, printer) {
  207. const name = array.constructor.name;
  208. return ++depth > config.maxDepth
  209. ? '[' + name + ']'
  210. : (config.min ? '' : name + ' ') +
  211. '[' +
  212. serializeItems(array, config, indentation, depth, refs, printer) +
  213. ']';
  214. },
  215. };
  216. ```
  217. ```js
  218. const val = {
  219. filter: 'completed',
  220. items: [
  221. {
  222. text: 'Write test',
  223. completed: true,
  224. },
  225. {
  226. text: 'Write serialize',
  227. completed: true,
  228. },
  229. ],
  230. };
  231. ```
  232. ```js
  233. console.log(
  234. prettyFormat(val, {
  235. plugins: [plugin],
  236. }),
  237. );
  238. /*
  239. Object {
  240. "filter": "completed",
  241. "items": Array [
  242. Object {
  243. "completed": true,
  244. "text": "Write test",
  245. },
  246. Object {
  247. "completed": true,
  248. "text": "Write serialize",
  249. },
  250. ],
  251. }
  252. */
  253. ```
  254. ```js
  255. console.log(
  256. prettyFormat(val, {
  257. indent: 4,
  258. plugins: [plugin],
  259. }),
  260. );
  261. /*
  262. Object {
  263. "filter": "completed",
  264. "items": Array [
  265. Object {
  266. "completed": true,
  267. "text": "Write test",
  268. },
  269. Object {
  270. "completed": true,
  271. "text": "Write serialize",
  272. },
  273. ],
  274. }
  275. */
  276. ```
  277. ```js
  278. console.log(
  279. prettyFormat(val, {
  280. maxDepth: 1,
  281. plugins: [plugin],
  282. }),
  283. );
  284. /*
  285. Object {
  286. "filter": "completed",
  287. "items": [Array],
  288. }
  289. */
  290. ```
  291. ```js
  292. console.log(
  293. prettyFormat(val, {
  294. min: true,
  295. plugins: [plugin],
  296. }),
  297. );
  298. /*
  299. {"filter": "completed", "items": [{"completed": true, "text": "Write test"}, {"completed": true, "text": "Write serialize"}]}
  300. */
  301. ```
  302. ### print
  303. The **original** interface is adequate for plugins:
  304. - that **do not** depend on options other than `highlight` or `min`
  305. - that **do not** depend on `depth` or `refs` in recursive traversal, and
  306. - if values either
  307. - do **not** require indentation, or
  308. - do **not** occur as children of JavaScript data structures (for example, array)
  309. Write `print` to return a string, given the arguments:
  310. - `val` which “passed the test”
  311. - current `printer(valChild)` callback function: serialize children
  312. - current `indenter(lines)` callback function: indent lines at the next level
  313. - unchanging `config` object: derived from `options`
  314. - unchanging `colors` object: derived from `options`
  315. The 3 properties of `config` are `min` in `options` and:
  316. - `spacing` and `edgeSpacing` are **newline** if `min` is `false`
  317. - `spacing` is **space** and `edgeSpacing` is **empty string** if `min` is `true`
  318. Each property of `colors` corresponds to a property of `theme` in `options`:
  319. - the key is the same (for example, `tag`)
  320. - the value in `colors` is a object with `open` and `close` properties whose values are escape codes from [ansi-styles](https://github.com/chalk/ansi-styles) for the color value in `theme` (for example, `'cyan'`)
  321. ### Example of print and test
  322. This plugin prints functions with the **number of named arguments** excluding rest argument.
  323. ```js
  324. const plugin = {
  325. print(val) {
  326. return `[Function ${val.name || 'anonymous'} ${val.length}]`;
  327. },
  328. test(val) {
  329. return typeof val === 'function';
  330. },
  331. };
  332. ```
  333. ```js
  334. const val = {
  335. onClick(event) {},
  336. render() {},
  337. };
  338. prettyFormat(val, {
  339. plugins: [plugin],
  340. });
  341. /*
  342. Object {
  343. "onClick": [Function onClick 1],
  344. "render": [Function render 0],
  345. }
  346. */
  347. prettyFormat(val);
  348. /*
  349. Object {
  350. "onClick": [Function onClick],
  351. "render": [Function render],
  352. }
  353. */
  354. ```
  355. This plugin **ignores** the `printFunctionName` option. That limitation of the original `print` interface is a reason to use the improved `serialize` interface, described above.
  356. ```js
  357. prettyFormat(val, {
  358. plugins: [pluginOld],
  359. printFunctionName: false,
  360. });
  361. /*
  362. Object {
  363. "onClick": [Function onClick 1],
  364. "render": [Function render 0],
  365. }
  366. */
  367. prettyFormat(val, {
  368. printFunctionName: false,
  369. });
  370. /*
  371. Object {
  372. "onClick": [Function],
  373. "render": [Function],
  374. }
  375. */
  376. ```