decode.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. var xtend = require('xtend');
  3. var entities = require('parse-entities');
  4. module.exports = factory;
  5. /* Factory to create an entity decoder. */
  6. function factory(ctx) {
  7. decoder.raw = decodeRaw;
  8. return decoder;
  9. /* Normalize `position` to add an `indent`. */
  10. function normalize(position) {
  11. var offsets = ctx.offset;
  12. var line = position.line;
  13. var result = [];
  14. while (++line) {
  15. if (!(line in offsets)) {
  16. break;
  17. }
  18. result.push((offsets[line] || 0) + 1);
  19. }
  20. return {
  21. start: position,
  22. indent: result
  23. };
  24. }
  25. /* Handle a warning.
  26. * See https://github.com/wooorm/parse-entities
  27. * for the warnings. */
  28. function handleWarning(reason, position, code) {
  29. if (code === 3) {
  30. return;
  31. }
  32. ctx.file.message(reason, position);
  33. }
  34. /* Decode `value` (at `position`) into text-nodes. */
  35. function decoder(value, position, handler) {
  36. entities(value, {
  37. position: normalize(position),
  38. warning: handleWarning,
  39. text: handler,
  40. reference: handler,
  41. textContext: ctx,
  42. referenceContext: ctx
  43. });
  44. }
  45. /* Decode `value` (at `position`) into a string. */
  46. function decodeRaw(value, position, options) {
  47. return entities(value, xtend(options, {
  48. position: normalize(position),
  49. warning: handleWarning
  50. }));
  51. }
  52. }