useWatermark.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import * as React from 'react';
  2. import { getStyleStr } from './utils';
  3. /**
  4. * Base size of the canvas, 1 for parallel layout and 2 for alternate layout
  5. * Only alternate layout is currently supported
  6. */
  7. export const BaseSize = 2;
  8. export const FontGap = 3;
  9. // Prevent external hidden elements from adding accent styles
  10. const emphasizedStyle = {
  11. visibility: 'visible !important'
  12. };
  13. export default function useWatermark(markStyle) {
  14. const watermarkMap = React.useRef(new Map());
  15. const appendWatermark = (base64Url, markWidth, container) => {
  16. if (container) {
  17. if (!watermarkMap.current.get(container)) {
  18. const newWatermarkEle = document.createElement('div');
  19. watermarkMap.current.set(container, newWatermarkEle);
  20. }
  21. const watermarkEle = watermarkMap.current.get(container);
  22. watermarkEle.setAttribute('style', getStyleStr(Object.assign(Object.assign(Object.assign({}, markStyle), {
  23. backgroundImage: `url('${base64Url}')`,
  24. backgroundSize: `${Math.floor(markWidth)}px`
  25. }), emphasizedStyle)));
  26. // Prevents using the browser `Hide Element` to hide watermarks
  27. watermarkEle.removeAttribute('class');
  28. watermarkEle.removeAttribute('hidden');
  29. if (watermarkEle.parentElement !== container) {
  30. container.append(watermarkEle);
  31. }
  32. }
  33. return watermarkMap.current.get(container);
  34. };
  35. const removeWatermark = container => {
  36. const watermarkEle = watermarkMap.current.get(container);
  37. if (watermarkEle && container) {
  38. container.removeChild(watermarkEle);
  39. }
  40. watermarkMap.current.delete(container);
  41. };
  42. const isWatermarkEle = ele => Array.from(watermarkMap.current.values()).includes(ele);
  43. return [appendWatermark, removeWatermark, isWatermarkEle];
  44. }