提交学习笔记专用
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.

108 lines
2.5 KiB

  1. 'use strict';
  2. /**
  3. * @typedef {object} Plugin
  4. * @prop {Set<string>} targets
  5. * @prop {Set<string>} nodeTypes
  6. * @prop {(node: import('postcss').Node) => void} detectAndResolve
  7. * @prop {(node: import('postcss').Node) => void} detectAndWarn
  8. */
  9. /**
  10. * @typedef {import('postcss').Node & {_stylehacks: {
  11. message: string,
  12. browsers: Set<string>,
  13. identifier: string,
  14. hack: string }}} NodeWithInfo
  15. */
  16. module.exports = class BasePlugin {
  17. /**
  18. * @param {string[]} targets
  19. * @param {string[]} nodeTypes
  20. * @param {import('postcss').Result=} result
  21. */
  22. constructor(targets, nodeTypes, result) {
  23. /** @type {NodeWithInfo[]} */
  24. this.nodes = [];
  25. this.targets = new Set(targets);
  26. this.nodeTypes = new Set(nodeTypes);
  27. this.result = result;
  28. }
  29. /**
  30. * @param {import('postcss').Node} node
  31. * @param {{identifier: string, hack: string}} metadata
  32. * @return {void}
  33. */
  34. push(node, metadata) {
  35. /** @type {NodeWithInfo} */ (node)._stylehacks = Object.assign(
  36. {},
  37. metadata,
  38. {
  39. message: `Bad ${metadata.identifier}: ${metadata.hack}`,
  40. browsers: this.targets,
  41. }
  42. );
  43. this.nodes.push(/** @type {NodeWithInfo} */ (node));
  44. }
  45. /**
  46. * @param {import('postcss').Node} node
  47. * @return {boolean}
  48. */
  49. any(node) {
  50. if (this.nodeTypes.has(node.type)) {
  51. this.detect(node);
  52. return /** @type {NodeWithInfo} */ (node)._stylehacks !== undefined;
  53. }
  54. return false;
  55. }
  56. /**
  57. * @param {import('postcss').Node} node
  58. * @return {void}
  59. */
  60. detectAndResolve(node) {
  61. this.nodes = [];
  62. this.detect(node);
  63. return this.resolve();
  64. }
  65. /**
  66. * @param {import('postcss').Node} node
  67. * @return {void}
  68. */
  69. detectAndWarn(node) {
  70. this.nodes = [];
  71. this.detect(node);
  72. return this.warn();
  73. }
  74. /** @param {import('postcss').Node} node */
  75. // eslint-disable-next-line no-unused-vars
  76. detect(node) {
  77. throw new Error('You need to implement this method in a subclass.');
  78. }
  79. /** @return {void} */
  80. resolve() {
  81. return this.nodes.forEach((node) => node.remove());
  82. }
  83. warn() {
  84. return this.nodes.forEach((node) => {
  85. const { message, browsers, identifier, hack } = node._stylehacks;
  86. return node.warn(
  87. /** @type {import('postcss').Result} */ (this.result),
  88. message + JSON.stringify({ browsers, identifier, hack })
  89. );
  90. });
  91. }
  92. };