handlerLoopData.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { nanoid } from 'nanoid';
  2. import handleSelector from '../handleSelector';
  3. function generateLoopSelectors(elements, { max, attrId, frameSelector }) {
  4. const selectors = [];
  5. elements.forEach((el, index) => {
  6. if (max > 0 && selectors.length - 1 > max) return;
  7. const attrName = 'automa-loop';
  8. const attrValue = `${attrId}--${index}`;
  9. el.setAttribute(attrName, attrValue);
  10. selectors.push(`${frameSelector}[${attrName}="${attrValue}"]`);
  11. });
  12. return selectors;
  13. }
  14. export default async function loopElements(block) {
  15. const elements = await handleSelector(block);
  16. if (!elements) throw new Error('element-not-found');
  17. let frameSelector = '';
  18. if (block.data.$frameSelector) {
  19. frameSelector = `${block.data.$frameSelector} |> `;
  20. }
  21. if (block.onlyGenerate) {
  22. generateLoopSelectors(elements, {
  23. ...block.data,
  24. frameSelector,
  25. attrId: block.data.loopId,
  26. });
  27. return {};
  28. }
  29. const attrId = nanoid(5);
  30. const selectors = generateLoopSelectors(elements, {
  31. ...block.data,
  32. frameSelector,
  33. attrId,
  34. });
  35. const { origin, pathname } = window.location;
  36. return {
  37. loopId: attrId,
  38. elements: selectors,
  39. url: origin + pathname,
  40. };
  41. }