{"version":3,"file":"openConfirmDelete.cjs","sources":["../../../../../src/components/lib/modals/openConfirmDelete.ts"],"sourcesContent":["import { reqOptions } from \"../helpFunction\";\nimport { openToast } from \"./modals\";\n\n/**\n * API response interface for error handling\n */\ninterface ApiErrorResponse {\n  detail?: string;\n  [key: string]: any;\n}\n\n/**\n * Opens a confirmation modal for deleting an item\n * @example\n *\n * const handleDelete = async (option) => {\n *   const endpoint = `${API_HOST_URL}assessments/${handle}/assessment-link-tree-destroy/${option.id}/`;\n *   const confirm = await openConfirmDelete(\n *     option.title,\n *     token,\n *     endpoint,\n *     true,\n *     reqOptions,\n *   );\n *\n *   if (confirm) {\n *     // Update objects\n *     const newObjects = data.filter((i) => i.id !== option.id);\n *     setData(newObjects);\n *   }\n * };\n *\n * @property {string} message The name of the item to be deleted\n * @property {string} token Authentication token for the API request\n * @property {string} url API endpoint for deletion\n * @property {boolean} pop Whether to show a popup confirmation (default: true)\n * @returns Promise that resolves to boolean indicating success or failure\n */\nexport const openConfirmDelete = (\n  message: string,\n  token: string,\n  url: string,\n  pop: boolean = true\n): Promise<boolean> => {\n  return new Promise<boolean>((resolve) => {\n    // Create modal element reference ID for cleanup\n    const modalId = \"ihub-confirm-modal\";\n\n    // Track event listeners for cleanup\n    const listeners: Array<{\n      element: HTMLElement | Document;\n      type: string;\n      handler: EventListenerOrEventListenerObject;\n    }> = [];\n\n    /**\n     * Helper function to add event listeners that will be tracked for cleanup\n     */\n    const addTrackedListener = <T extends Event>(\n      element: HTMLElement | Document,\n      type: string,\n      handler: (event: T) => void\n    ): void => {\n      const wrappedHandler = (event: Event) => handler(event as T);\n      element.addEventListener(type, wrappedHandler);\n      listeners.push({ element, type, handler: wrappedHandler });\n    };\n\n    /**\n     * Removes the modal from the DOM and cleans up event listeners\n     */\n    const cleanup = (): void => {\n      // Clean up all tracked event listeners\n      listeners.forEach(({ element, type, handler }) => {\n        element.removeEventListener(type, handler);\n      });\n\n      // Remove the modal element\n      const modalElement = document.getElementById(modalId);\n      if (modalElement) {\n        // Remove global event handlers before removing the element\n        for (const handlerName of [\n          \"handleInput\",\n          \"handleCancel\",\n          \"handleConfirm\",\n        ]) {\n          if ((window as any)[handlerName]) {\n            delete (window as any)[handlerName];\n          }\n        }\n        modalElement.remove();\n      }\n    };\n\n    /**\n     * Handles the deletion API request\n     */\n    const handleSubmit = async (): Promise<void> => {\n      try {\n        // Delete the object from the DB if user confirms\n        const requestOptions = reqOptions(\"DELETE\", null, token);\n        const request = await fetch(url, requestOptions);\n\n        if (request.status === 204) {\n          openToast(`${message} was successfully deleted.`);\n          cleanup();\n          resolve(true);\n          return;\n        } else if (request.status === 401) {\n          openToast(\"You don't have permission to delete this item.\", 401);\n        } else {\n          const res = (await request.json()) as ApiErrorResponse;\n          openToast(\n            res.detail ||\n              \"Couldn't delete the item. You can report the issue with the feedback button.\",\n            request.status\n          );\n        }\n      } catch (error) {\n        openToast(\n          `Error deleting item: ${\n            error instanceof Error ? error.message : \"Unknown error\"\n          }`,\n          500\n        );\n      }\n\n      resolve(false);\n    };\n\n    // If no popup needed, just submit and return\n    if (!pop) {\n      handleSubmit();\n      return;\n    }\n\n    // Templates for the copy button states\n    const copiedState = `\n        <div class=\"ihub-copy-status ihub-copy-success\">\n          <svg class=\"ihub-icon\" focusable=\"false\" aria-hidden=\"true\" viewBox=\"0 0 24 24\" data-testid=\"CheckIcon\">\n            <path d=\"M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z\"></path>\n          </svg>\n          <span>Copied!</span>\n        </div>\n      `.trim();\n\n    const unCopiedState = `\n        <div class=\"ihub-copy-status\">\n          <svg class=\"ihub-icon\" focusable=\"false\" aria-hidden=\"true\" viewBox=\"0 0 24 24\" data-testid=\"ContentCopyIcon\">\n            <path d=\"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z\"></path>\n          </svg>\n          <span class=\"ihub-fs-sm\">Copy Text</span>\n        </div>\n      `.trim();\n\n    // Create or get the modal container\n    let modalContainer = document.getElementById(modalId);\n    if (!modalContainer) {\n      modalContainer = document.createElement(\"div\");\n      modalContainer.id = modalId;\n    }\n\n    // Create modal content with proper ihub- prefixed classes\n    const modalContent = `\n        <section class=\"ihub-modal ihub-modal-open\" aria-labelledby=\"delete-modal-title\" role=\"dialog\" aria-modal=\"true\">\n          <div class=\"ihub-modal-content\">\n            <h4 id=\"delete-modal-title\" class=\"ihub-modal-title\">Delete confirmation</h4>\n            <p class=\"ihub-warning-text\">\n              Unexpected bad things will happen if you don't read this!\n            </p>\n            <p class=\"ihub-modal-description\">\n              This action cannot be undone. This will permanently delete the\n              <strong>${message}</strong> repository, feedbacks, schedules, and remove all team\n              associations.\n            </p>\n  \n            <div class=\"ihub-confirm-row\">\n              <p class=\"ihub-confirm-instruction\">Please type <strong class=\"ihub-confirm-value\">${message}</strong> to confirm.</p>\n              <button type=\"button\" id=\"ihub-copy-btn\" class=\"ihub-copy-btn\" aria-label=\"Copy confirmation text\">\n                ${unCopiedState}\n              </button>\n            </div>\n  \n            <div class=\"ihub-input-wrapper\">\n              <input \n                type=\"text\" \n                id=\"ihub-delete-input\" \n                class=\"ihub-delete-input\" \n                aria-label=\"Confirmation text\"\n                placeholder=\"Type the text to confirm deletion\"\n              />\n            </div>\n            \n            <div class=\"ihub-modal-actions\">\n              <button \n                type=\"button\" \n                id=\"ihub-cancel-btn\" \n                class=\"ihub-cancel-btn\"\n                aria-label=\"Cancel deletion\"\n              >\n                Cancel\n              </button>\n              <button \n                type=\"button\" \n                disabled \n                id=\"ihub-delete-btn\" \n                class=\"ihub-delete-btn\"\n                aria-label=\"Confirm deletion\"\n              >\n                Delete\n              </button>\n            </div>\n          </div>\n        </section>\n      `.trim();\n\n    // Set modal content and add to document\n    modalContainer.innerHTML = modalContent;\n    document.body.appendChild(modalContainer);\n\n    // Get DOM elements\n    const copyBtn = document.getElementById(\"ihub-copy-btn\");\n    const deleteBtn = document.getElementById(\n      \"ihub-delete-btn\"\n    ) as HTMLButtonElement | null;\n    const cancelBtn = document.getElementById(\"ihub-cancel-btn\");\n    const deleteInput = document.getElementById(\n      \"ihub-delete-input\"\n    ) as HTMLInputElement | null;\n    const modalElement = document.querySelector(\".ihub-modal\");\n\n    // Set up copy button functionality\n    if (copyBtn) {\n      const copyClickHandler = () => {\n        navigator.clipboard\n          .writeText(message)\n          .then(() => {\n            if (copyBtn) {\n              copyBtn.innerHTML = copiedState;\n              setTimeout(() => {\n                if (copyBtn) {\n                  copyBtn.innerHTML = unCopiedState;\n                }\n              }, 2000);\n            }\n          })\n          .catch((err) => console.error(\"Unable to copy to clipboard\", err));\n      };\n\n      addTrackedListener(copyBtn, \"click\", copyClickHandler);\n    }\n\n    // Set up input validation\n    if (deleteInput) {\n      const inputHandler = (e: Event) => {\n        const input = e.target as HTMLInputElement;\n        if (deleteBtn) {\n          deleteBtn.disabled = input.value !== message;\n        }\n      };\n\n      addTrackedListener(deleteInput, \"input\", inputHandler);\n    }\n\n    // Set up cancel button\n    if (cancelBtn) {\n      const cancelHandler = () => {\n        cleanup();\n        resolve(false);\n      };\n\n      addTrackedListener(cancelBtn, \"click\", cancelHandler);\n    }\n\n    // Set up delete button\n    if (deleteBtn) {\n      const deleteHandler = () => {\n        handleSubmit();\n      };\n\n      addTrackedListener(deleteBtn, \"click\", deleteHandler);\n    }\n\n    // Close modal when clicking outside (only if clicking directly on the modal background)\n    if (modalElement) {\n      const modalClickHandler = (e: MouseEvent) => {\n        if (e.target === modalElement) {\n          cleanup();\n          resolve(false);\n        }\n      };\n\n      addTrackedListener<MouseEvent>(\n        modalElement as HTMLElement,\n        \"click\",\n        modalClickHandler\n      );\n    }\n\n    // Handle escape key to cancel\n    const handleEscapeKey = (e: KeyboardEvent) => {\n      if (e.key === \"Escape\") {\n        cleanup();\n        resolve(false);\n      }\n    };\n\n    // Add escape key listener to our tracked listeners\n    addTrackedListener<KeyboardEvent>(document, \"keydown\", handleEscapeKey);\n  });\n};\n"],"names":["message","token","url","pop","arguments","length","undefined","Promise","resolve","modalId","listeners","addTrackedListener","element","type","handler","wrappedHandler","event","addEventListener","push","cleanup","forEach","_ref","removeEventListener","modalElement","document","getElementById","_i","_arr","handlerName","window","remove","handleSubmit","_ref2","_asyncToGenerator","_regenerator","m","_callee","requestOptions","request","res","_t","w","_context","p","n","reqOptions","fetch","v","status","openToast","concat","a","json","detail","Error","apply","this","copiedState","trim","unCopiedState","modalContainer","createElement","id","modalContent","innerHTML","body","appendChild","copyBtn","deleteBtn","cancelBtn","deleteInput","querySelector","navigator","clipboard","writeText","then","setTimeout","err","console","error","e","input","target","disabled","value","key"],"mappings":"6NAsCiC,SAC/BA,EACAC,EACAC,GAEoB,IADpBC,IAAeC,UAAAC,OAAA,QAAAC,IAAAF,UAAA,KAAAA,UAAA,GAEf,OAAO,IAAIG,QAAiB,SAACC,GAE3B,IAAMC,EAAU,qBAGVC,EAID,GAKCC,EAAqB,SACzBC,EACAC,EACAC,GAEA,IAAMC,EAAiB,SAACC,GAAY,OAAKF,EAAQE,EAAW,EAC5DJ,EAAQK,iBAAiBJ,EAAME,GAC/BL,EAAUQ,KAAK,CAAEN,QAAAA,EAASC,KAAAA,EAAMC,QAASC,KAMrCI,EAAU,WAEdT,EAAUU,QAAQ,SAAAC,GAA+B,IAA5BT,EAAOS,EAAPT,QAASC,EAAIQ,EAAJR,KAAMC,EAAOO,EAAPP,QAClCF,EAAQU,oBAAoBT,EAAMC,EACpC,GAGA,IAAMS,EAAeC,SAASC,eAAehB,GAC7C,GAAIc,EAAc,CAEhB,IAAA,IAAAG,EAAAC,EAAAA,EAA0B,CACxB,cACA,eACA,iBACDD,EAAAC,EAAAtB,OAAAqB,IAAE,CAJE,IAAME,EAAWD,EAAAD,GAKfG,OAAeD,WACVC,OAAeD,EAE1B,CACDL,EAAaO,QACd,GAMGC,EAAY,WAAA,IAAAC,EAAAC,EAA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