← Back
Editing: postDuplicator.js
(()=>{"use strict";var e={715(e){e.exports=window.wp.blockEditor}},t={};function s(a){var o=t[a];if(void 0!==o)return o.exports;var i=t[a]={exports:{}};return e[a](i,i.exports,s),i.exports}const a=window.wp.element,o=window.wp.components,i=window.wp.i18n,n=window.wp.primitives,l=window.ReactJSXRuntime,r=(0,l.jsx)(n.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:(0,l.jsx)(n.Path,{fillRule:"evenodd",clipRule:"evenodd",d:"M5 4.5h11a.5.5 0 0 1 .5.5v11a.5.5 0 0 1-.5.5H5a.5.5 0 0 1-.5-.5V5a.5.5 0 0 1 .5-.5ZM3 5a2 2 0 0 1 2-2h11a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5Zm17 3v10.75c0 .69-.56 1.25-1.25 1.25H6v1.5h12.75a2.75 2.75 0 0 0 2.75-2.75V8H20Z"})}),c=(0,l.jsx)(n.SVG,{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,l.jsx)(n.Path,{d:"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm.5 16c0 .3-.2.5-.5.5H5c-.3 0-.5-.2-.5-.5V7h15v12zM9 10H7v2h2v-2zm0 4H7v2h2v-2zm4-4h-2v2h2v-2zm4 0h-2v2h2v-2zm-4 4h-2v2h2v-2zm4 0h-2v2h2v-2z"})}),p=({settings:e,onSettingsChange:t,postTypes:n,statusChoices:r,originalPost:p,featuredImage:d,onFeaturedImageChange:u})=>{const[m,g]=(0,a.useState)((()=>{const t={...e};return"same"===e.type&&p?.type&&(t.type=p.type),"same"===e.status&&p?.status&&(t.status=p.status),t})()),[f,h]=(0,a.useState)(!1),[_,x]=(0,a.useState)(""),[y,w]=(0,a.useState)(""),[v,S]=(0,a.useState)(!1),[j,b]=(0,a.useState)([]),[D,P]=(0,a.useState)(!1),k=window.postDuplicatorVars?.currentUser,C=window.postDuplicatorVars?.postTypesAuthorSupport||{},T=window.postDuplicatorVars?.postTypesHierarchicalSupport||{},I=()=>"same"===m.type?p?.type:m.type,N=()=>{const e=I();return!0===T[e]},[E,M]=(0,a.useState)((()=>{const e=p?.type;return!1!==C[e]?k?.id?String(k.id):j.length>0?j[0].value:"":""})()),[$,V]=(0,a.useState)(""),[U,z]=(0,a.useState)([]),[B,A]=(0,a.useState)((new Date).toISOString()),[H,R]=(0,a.useState)(""),[L,F]=(0,a.useState)(!1),O=(0,a.useRef)(null),W=(0,a.useRef)(null);(0,a.useEffect)(()=>{(async()=>{if(0===j.length&&!D){P(!0);try{const e=window.postDuplicatorVars?.restUrl||"",t=window.postDuplicatorVars?.nonce||"";if(!e||!t)return console.error("Missing REST URL or nonce for users fetch"),void P(!1);const s=`${e}users`,a=await fetch(s,{method:"GET",headers:{"X-WP-Nonce":t,"Content-Type":"application/json"}});if(a.ok){const e=await a.json();Array.isArray(e)?b(e):console.error("Invalid users response format:",e)}else{const e=await a.text();console.error("Error fetching users:",a.status,a.statusText,e)}}catch(e){console.error("Error fetching users:",e)}finally{P(!1)}}})()},[]);const{MediaUpload:G,MediaUploadCheck:X}=(()=>{try{const e=s(715);if(e&&e.MediaUpload&&e.MediaUploadCheck&&"function"==typeof e.MediaUpload&&"function"==typeof e.MediaUploadCheck)return{MediaUpload:e.MediaUpload,MediaUploadCheck:e.MediaUploadCheck}}catch(e){}return{MediaUpload:null,MediaUploadCheck:null}})();let Z=!0;try{if(void 0!==window.wp&&window.wp.data&&"function"==typeof window.wp.data.select){const e=window.wp.data.select("core/editor");Z=!e||"function"!=typeof e.getCurrentPost}}catch(e){Z=!0}const J=e=>e.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^\w\-]/g,"").replace(/\-\-+/g,"-").replace(/^-+/,"").replace(/-+$/,""),q=e=>J(e),K=(e,s)=>{const a={...m,[e]:s};"timestamp"===e&&"custom"!==s&&(a.customDate=null),g(a),t(a)};(0,a.useEffect)(()=>{if(!v&&p?.title&&p?.slug){const s=e.fullTitle||`${p.title} ${e.title||""}`;x(s.trim());const a=e.fullSlug||`${p.slug}-${e.slug||"copy"}`;w(a);const o={...e,fullTitle:s.trim(),fullSlug:a};g(o),t(o);const i=p?.type;let n,l="";!1!==C[i]&&(l="current_user"===e.post_author?String(k?.id||""):String(p.authorId||k?.id||"")),M(l);let r=!1;if(e.customDate?(n=e.customDate,r=!1):"duplicate"===e.timestamp&&p?.date?(n=p.date,r=!0):(n=(new Date).toISOString(),r=!0),e.time_offset&&r){const t=new Date(n),s=864e5*(e.time_offset_days||0)+36e5*(e.time_offset_hours||0)+6e4*(e.time_offset_minutes||0)+1e3*(e.time_offset_seconds||0);"newer"===e.time_offset_direction?t.setTime(t.getTime()+s):t.setTime(t.getTime()-s),n=t.toISOString()}A(n),R(Q(n));const c=p?.parent||0;V(c>0?String(c):""),K("selectedParentId",c>0?c:null),S(!0)}},[p,v,e,k]),(0,a.useEffect)(()=>{(async()=>{if(!p?.type)return void z([]);const e="same"===m.type?p.type:m.type;try{const t=await fetch(`${window.postDuplicatorVars.restUrl}parent-posts?post_type=${e}&exclude_id=${p.id}`,{headers:{"X-WP-Nonce":window.postDuplicatorVars.nonce}});if(t.ok){const e=await t.json(),s=e=>{const t=e.level||0;return 0===t?e.title:`${"—".repeat(t)+" "}${e.title}`},a=[{label:(0,i.__)("— No Parent —","post-duplicator"),value:""},...e.map(e=>({label:s(e),value:String(e.id),level:e.level||0}))];z(a),p?.parentPost&&p.parent>0&&(e.some(e=>e.id===p.parent)||(a.splice(1,0,{label:p.parentPost.title,value:String(p.parent),level:0}),z(a)))}}catch(e){console.error("Error fetching parent posts:",e),z([{label:(0,i.__)("— No Parent —","post-duplicator"),value:""}])}})()},[p?.type,m.type,p?.id,p?.parent,p?.parentPost]),(0,a.useEffect)(()=>{const t={...e};"same"===e.type&&p?.type&&(t.type=p.type),"same"===e.status&&p?.status&&(t.status=p.status),g(t)},[e,p]),(0,a.useEffect)(()=>{if(!v)return;const e=I(),t=!1!==C[e];if(t||""===E){if(t&&""===E&&k?.id){const e=String(k.id);M(e),K("selectedAuthorId",parseInt(e))}}else M(""),K("selectedAuthorId",null)},[m.type,v]),(0,a.useEffect)(()=>{v&&(N()||""===$||(V(""),K("selectedParentId",null)))},[m.type,v]);const Q=e=>new Date(e).toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Y=e=>Array.isArray(e)?e:Object.entries(e).map(([e,t])=>({value:e,label:t})),ee=()=>{if(void 0===window.wp||!window.wp.media)return console.error("WordPress media library is not available. Make sure wp_enqueue_media() is called."),void alert((0,i.__)("Media library is not available. Please refresh the page.","post-duplicator"));const e=window.wp.media({title:(0,i.__)("Select or Upload Featured Image","post-duplicator"),button:{text:(0,i.__)("Use this image","post-duplicator")},multiple:!1,library:{type:"image"}});e.on("select",()=>{const t=e.state().get("selection").first().toJSON(),s={id:t.id,url:t.url,thumbnail:t.sizes?.thumbnail?.url||t.url,alt:t.alt||""};u&&u(s)}),e.open()},te=e=>{const t=d?.alt||"",s=d?.url?.split("/").pop()||"",a=`editor-post-featured-image-${d?.id||"new"}-describedby`,n=t||(0,i.__)("The current image has no alternative text.","post-duplicator")+(s?` ${(0,i.__)("The file name is:","post-duplicator")} ${s}`:"");return(0,l.jsxs)("div",{className:"editor-post-featured-image__container",children:[d&&(0,l.jsx)("div",{id:a,className:"hidden",children:n}),d?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(o.Button,{type:"button",className:"components-button editor-post-featured-image__preview is-next-40px-default-size",onClick:e,"aria-label":(0,i.__)("Edit or replace the featured image","post-duplicator"),"aria-describedby":a,"aria-haspopup":"dialog",children:(0,l.jsx)("img",{className:"editor-post-featured-image__preview-image",src:d.url,alt:n})}),(0,l.jsxs)(o.__experimentalHStack,{className:"editor-post-featured-image__actions",children:[(0,l.jsx)(o.Button,{type:"button",className:"components-button editor-post-featured-image__action is-next-40px-default-size",onClick:e,"aria-haspopup":"dialog",children:(0,i.__)("Replace","post-duplicator")}),(0,l.jsx)(o.Button,{type:"button",className:"components-button editor-post-featured-image__action is-next-40px-default-size",onClick:()=>{u&&u(null)},children:(0,i.__)("Remove","post-duplicator")})]})]}):(0,l.jsx)(o.Button,{variant:"secondary",onClick:e,__next40pxDefaultSize:!0,children:(0,i.__)("Set featured image","post-duplicator")}),o.DropZone&&(0,l.jsx)(o.DropZone,{onFilesDrop:t=>{t.length>0&&e()},className:"components-drop-zone",children:(0,l.jsx)("div",{className:"components-drop-zone__content",children:(0,l.jsxs)("div",{className:"components-drop-zone__content-inner",children:[(0,l.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"24",height:"24",className:"components-drop-zone__content-icon","aria-hidden":"true",focusable:"false",children:(0,l.jsx)("path",{d:"M18.5 15v3.5H13V6.7l4.5 4.1 1-1.1-6.2-5.8-5.8 5.8 1 1.1 4-4v11.7h-6V15H4v5h16v-5z"})}),(0,l.jsx)("span",{className:"components-drop-zone__content-text",children:(0,i.__)("Drop files to upload","post-duplicator")})]})})})]})};return(0,l.jsxs)(o.__experimentalVStack,{className:"duplicate-settings-fields",spacing:"20px",children:[(0,l.jsxs)(o.__experimentalHStack,{spacing:"16px",alignment:"stretch",className:"duplicate-settings-fields__top",children:[(0,l.jsxs)(o.__experimentalVStack,{className:"duplicate-settings-fields__title",children:[(0,l.jsx)(o.TextControl,{label:(0,i.__)("Title","post-duplicator"),value:_,onChange:e=>{if(x(e),!f&&p?.title){const s=q(e);w(s);const a={...m,fullTitle:e,fullSlug:s};g(a),t(a)}else K("fullTitle",e)},__nextHasNoMarginBottom:!0,__next40pxDefaultSize:!0,style:{flex:1}}),(0,l.jsx)(o.TextControl,{label:(0,i.__)("Slug","post-duplicator"),value:y,onChange:e=>{w(e),h(!0),K("fullSlug",e)},onBlur:()=>{if(y&&""!==y.trim()){const e=J(y);w(e),K("fullSlug",e)}else{const e=q(_);w(e),K("fullSlug",e),h(!1)}},__nextHasNoMarginBottom:!0,__next40pxDefaultSize:!0})]}),(0,l.jsx)("div",{className:"duplicate-settings-fields__featured-image",style:{minWidth:"200px",width:"35%",flex:"0 0 auto"},children:(()=>{if(!Z&&G&&X)return(0,l.jsx)(X,{children:(0,l.jsx)(G,{onSelect:e=>{const t={id:e.id,url:e.url,thumbnail:e.sizes?.thumbnail?.url||e.url,alt:e.alt||""};u&&u(t)},allowedTypes:["image"],value:d?.id,render:({open:e})=>te(e)})});try{return te(()=>ee())}catch(e){return console.error("Error rendering featured image UI:",e),(0,l.jsxs)("div",{children:[(0,l.jsxs)("p",{children:["Error rendering featured image UI: ",e.message]}),(0,l.jsx)(o.Button,{variant:"secondary",onClick:()=>ee(),__next40pxDefaultSize:!0,children:(0,i.__)("Set featured image","post-duplicator")})]})}})()})]}),(0,l.jsxs)(o.__experimentalHStack,{spacing:"16px",alignment:"stretch",children:[(0,l.jsx)(o.SelectControl,{label:(0,i.__)("Post Type","post-duplicator"),value:m.type,options:Y((()=>{const e={...n};if(p?.type&&!e[p.type]){const t=(window.postDuplicatorVars?.allPostTypes||[]).find(e=>e.id===p.type);if(t)e[p.type]=t.label;else{const t=p.type.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");e[p.type]=t}}const t={};return e.same&&(t.same=e.same,delete e.same),Object.entries(e).sort((e,t)=>e[1].localeCompare(t[1],void 0,{sensitivity:"base"})).forEach(([e,s])=>{t[e]=s}),t})()),onChange:e=>K("type",e),__nextHasNoMarginBottom:!0,__next40pxDefaultSize:!0}),(0,l.jsx)(o.SelectControl,{label:(0,i.__)("Post Status","post-duplicator"),value:m.status,options:Y(r),onChange:e=>K("status",e),__nextHasNoMarginBottom:!0,__next40pxDefaultSize:!0}),(0,l.jsx)(o.SelectControl,{label:(0,i.__)("Post Parent","post-duplicator"),value:$||"",options:U,onChange:e=>{V(e),K("selectedParentId",e?parseInt(e):null)},disabled:!N(),__nextHasNoMarginBottom:!0,__next40pxDefaultSize:!0})]}),(0,l.jsxs)(o.__experimentalHStack,{spacing:"16px",alignment:"stretch",children:[(0,l.jsx)(o.SelectControl,{label:(0,i.__)("Post Author","post-duplicator"),value:E||"",options:[{label:(0,i.__)("No Author","post-duplicator"),value:""},...j],onChange:e=>{M(e),K("selectedAuthorId",e?parseInt(e):null)},__nextHasNoMarginBottom:!0,__next40pxDefaultSize:!0}),(0,l.jsxs)("div",{ref:O,style:{flex:1,position:"relative"},children:[(0,l.jsx)(o.TextControl,{label:(0,i.__)("Post Date","post-duplicator"),value:H,onChange:e=>{R(e)},onBlur:()=>{try{const e=new Date(H);if(isNaN(e.getTime()))R(Q(B));else{const s=e.toISOString();A(s),R(Q(s));const a={...m,timestamp:"custom",customDate:s};g(a),t(a)}}catch(e){R(Q(B))}},__nextHasNoMarginBottom:!0,__next40pxDefaultSize:!0}),(0,l.jsx)(o.Button,{ref:W,onClick:()=>F(!L),"aria-expanded":L,icon:c,style:{position:"absolute",right:"2px",top:"26px",minWidth:"36px",height:"36px",padding:"0"},variant:"tertiary"}),L&&(0,l.jsx)(o.Popover,{anchorRef:O,placement:"bottom-start",offset:8,onClose:()=>F(!1),children:(0,l.jsx)("div",{style:{padding:"16px"},children:(0,l.jsx)(o.DateTimePicker,{currentDate:B,onChange:e=>{(e=>{const s=e instanceof Date?e.toISOString():new Date(e).toISOString();A(s),R(Q(s));const a={...m,timestamp:"custom",customDate:s};g(a),t(a)})(e),F(!1)},is12Hour:!1})})})]})]})]})},d=({taxonomy:e,selectedTermIds:t,onChange:s})=>{const[n,r]=(0,a.useState)(()=>(e.terms||[]).map(e=>e.name)),c=(0,a.useRef)((e=>{const t={},s={};return(e||[]).forEach(e=>{t[e.id]=e,s[e.name]=e}),{byId:t,byName:s}})(e.terms)),p=(0,a.useRef)(null),d=(0,a.useRef)(null),u=(0,a.useRef)(0),m=(0,a.useRef)(!1),g=e=>{const t=c.current;(e||[]).forEach(e=>{t.byId[e.id]=e,t.byName[e.name]=e})};(0,a.useEffect)(()=>{g(e.terms)},[e.terms]);const f=(0,a.useCallback)(async t=>{const s=window.postDuplicatorVars?.restUrl||"",a=window.postDuplicatorVars?.nonce||"";if(!s||!a)return;d.current&&d.current.abort();const o=new AbortController;d.current=o;const i=++u.current,n=new URLSearchParams({taxonomy:e.slug,number:String(20)});t&&n.set("search",t);try{const e=await fetch(`${s}search-terms?${n.toString()}`,{method:"GET",headers:{"X-WP-Nonce":a},signal:o.signal});if(!e.ok||i!==u.current)return;const t=await e.json();if(!Array.isArray(t))return;g(t),r(t.map(e=>e.name))}catch(e){"AbortError"!==e.name&&console.error("Error searching terms:",e)}},[e.slug]);(0,a.useEffect)(()=>()=>{p.current&&clearTimeout(p.current),d.current&&d.current.abort()},[]);const h=(t||[]).map(e=>c.current.byId[e]?.name).filter(Boolean);return(0,l.jsxs)("div",{onFocus:()=>{m.current||(m.current=!0,f(""))},children:[(0,l.jsx)("label",{style:{display:"block",marginBottom:"8px",fontWeight:500},children:e.label}),(0,l.jsx)(o.FormTokenField,{value:h,suggestions:n,placeholder:(0,i.__)("Type to search terms","post-duplicator"),onInputChange:e=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{m.current=!0,f(e.trim())},300)},onChange:e=>{const t=e.map(e=>{const t=c.current.byName[e];return t?t.id:null}).filter(e=>null!==e);s(t)},__experimentalValidateInput:e=>Boolean(c.current.byName[e]),__experimentalExpandOnFocus:!0,__experimentalShowHowTo:!1,__nextHasNoMarginBottom:!0,__next40pxDefaultSize:!0,maxSuggestions:20})]})},u=({taxonomies:e,onChange:t,enabled:s,onToggle:n})=>{const[r,c]=(0,a.useState)(!1),[p,u]=(0,a.useState)({});if((0,a.useEffect)(()=>{if(e&&e.length>0){const t={};e.forEach(e=>{t[e.slug]=e.assignedTermIds||[]}),u(t)}},[e]),!e||0===e.length)return null;const m=e.length,g=Object.values(p).reduce((e,t)=>e+t.length,0);return(0,l.jsxs)("div",{className:"duplicate-post-modal__taxonomy-section",style:{opacity:s?1:.5},children:[(0,l.jsxs)("div",{className:"duplicate-post-modal__section-header",onClick:e=>{e.target.closest(".components-toggle-control")||c(!r)},style:{display:"flex",alignItems:"center",gap:"12px",padding:"12px",cursor:"pointer",borderBottom:r?"1px solid rgba(0, 0, 0, 0.1)":"none"},children:[(0,l.jsx)(o.ToggleControl,{checked:s,onChange:n,__nextHasNoMarginBottom:!0}),(0,l.jsxs)("div",{style:{flex:1},children:[(0,l.jsx)("span",{className:"duplicate-post-modal__section-label",children:(0,i.__)("Taxonomies","post-duplicator")}),s&&(0,l.jsxs)("span",{className:"duplicate-post-modal__section-count",children:[" ","(",m," ",(0,i.__)("taxonomies","post-duplicator"),","," ",g," ",(0,i.__)("terms","post-duplicator"),")"]})]})]}),r&&(0,l.jsx)("div",{className:"duplicate-post-modal__section-content",style:{padding:"16px"},children:(0,l.jsx)(o.__experimentalVStack,{spacing:"20px",children:e.map(e=>(0,l.jsx)(d,{taxonomy:e,selectedTermIds:p[e.slug]||[],onChange:s=>((e,s)=>{const a={...p,[e]:s};u(a),t&&t(a)})(e.slug,s)},e.slug))})})]})},m=(0,l.jsx)(n.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:(0,l.jsx)(n.Path,{fillRule:"evenodd",clipRule:"evenodd",d:"M12 5.5A2.25 2.25 0 0 0 9.878 7h4.244A2.251 2.251 0 0 0 12 5.5ZM12 4a3.751 3.751 0 0 0-3.675 3H5v1.5h1.27l.818 8.997a2.75 2.75 0 0 0 2.739 2.501h4.347a2.75 2.75 0 0 0 2.738-2.5L17.73 8.5H19V7h-3.325A3.751 3.751 0 0 0 12 4Zm4.224 4.5H7.776l.806 8.861a1.25 1.25 0 0 0 1.245 1.137h4.347a1.25 1.25 0 0 0 1.245-1.137l.805-8.861Z"})}),g=({customMeta:e,onChange:t,enabled:s,onToggle:n})=>{const[r,c]=(0,a.useState)(!1),[p,d]=(0,a.useState)([]);(0,a.useEffect)(()=>{e&&e.length>0?d(e.map(e=>({key:e.key,value:e.value,type:e.type||"string",isSerialized:e.isSerialized||!1,originalValue:e.originalValue||e.value,isDeleted:!1}))):d([])},[e]);const u=p.filter(e=>!e.isDeleted).length,g=(e,s,a)=>{const o=[...p];if(o[e]={...o[e],[s]:a},"value"===s&&("array"===o[e].type||"object"===o[e].type))try{const t=JSON.parse(a);o[e].type=Array.isArray(t)?"array":"object"}catch(e){}if(d(o),t){const e=o.filter(e=>!e.isDeleted).map(e=>({key:e.key,value:e.value,type:e.type,isSerialized:e.isSerialized}));t(e)}};return e&&0!==e.length?(0,l.jsxs)("div",{className:"duplicate-post-modal__custom-meta-section",style:{opacity:s?1:.5},children:[(0,l.jsxs)("div",{className:"duplicate-post-modal__section-header",onClick:e=>{e.target.closest(".components-toggle-control")||c(!r)},style:{display:"flex",alignItems:"center",gap:"12px",padding:"12px",cursor:"pointer",borderBottom:r?"1px solid rgba(0, 0, 0, 0.1)":"none"},children:[(0,l.jsx)(o.ToggleControl,{checked:s,onChange:n,__nextHasNoMarginBottom:!0}),(0,l.jsxs)("div",{style:{flex:1},children:[(0,l.jsx)("span",{className:"duplicate-post-modal__section-label",children:(0,i.__)("Custom Meta","post-duplicator")}),s&&(0,l.jsxs)("span",{className:"duplicate-post-modal__section-count",children:[" ","(",u," ",(0,i.__)("fields","post-duplicator"),")"]})]})]}),r&&(0,l.jsx)("div",{className:"duplicate-post-modal__section-content",style:{padding:"16px"},children:(0,l.jsxs)(o.__experimentalVStack,{spacing:"16px",children:[p.map((e,s)=>!e.isDeleted&&(0,l.jsx)("div",{style:{padding:"12px",border:"1px solid rgba(0, 0, 0, 0.1)",borderRadius:"4px"},children:(0,l.jsxs)(o.__experimentalHStack,{spacing:"8px",alignment:"top",children:[(0,l.jsx)("div",{style:{flex:1},children:(0,l.jsx)(o.TextControl,{label:(0,i.__)("Key","post-duplicator"),value:e.key,onChange:e=>g(s,"key",e),__nextHasNoMarginBottom:!0,__next40pxDefaultSize:!0})}),(0,l.jsx)("div",{style:{flex:2},children:"array"===e.type||"object"===e.type?(0,l.jsx)(o.TextareaControl,{label:(0,i.__)("Value (JSON)","post-duplicator"),value:e.value,onChange:e=>g(s,"value",e),onBlur:e=>((e,t)=>{const s=p[e];if("array"===s.type||"object"===s.type)try{JSON.parse(t)}catch(t){g(e,"value",s.value)}})(s,e.target.value),rows:6,__nextHasNoMarginBottom:!0,__next40pxDefaultSize:!0}):(0,l.jsx)(o.TextareaControl,{label:(0,i.__)("Value","post-duplicator"),value:e.value,onChange:e=>g(s,"value",e),rows:3,__nextHasNoMarginBottom:!0,__next40pxDefaultSize:!0})}),(0,l.jsx)("div",{children:(0,l.jsx)(o.Button,{icon:m,variant:"tertiary",onClick:()=>(e=>{const s=[...p];if(s[e].isDeleted=!0,d(s),t){const e=s.filter(e=>!e.isDeleted).map(e=>({key:e.key,value:e.value,type:e.type,isSerialized:e.isSerialized}));t(e)}})(s),label:(0,i.__)("Delete field","post-duplicator"),style:{marginTop:"32px"}})})]})},s)),(0,l.jsx)(o.Button,{variant:"secondary",onClick:()=>{const e=[...p,{key:"",value:"",type:"string",isSerialized:!1,originalValue:"",isDeleted:!1}];d(e)},style:{alignSelf:"flex-start"},children:(0,i.__)("Add Field","post-duplicator")})]})})]}):null},f=(0,l.jsx)(n.SVG,{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,l.jsx)(n.Path,{d:"M6.5 12.4L12 8l5.5 4.4-.9 1.2L12 10l-4.5 3.6-1-1.2z"})}),h=(0,l.jsx)(n.SVG,{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,l.jsx)(n.Path,{d:"M17.5 11.6L12 16l-5.5-4.4.9-1.2L12 14l4.5-3.6 1 1.2z"})}),_=({post:e,index:t,onUpdate:s,onDelete:n,onToggleExpand:r,isExpanded:c,showDelete:d=!0,postTypes:_,statusChoices:x,siteUrl:y,currentUser:w,defaultSettings:v})=>{const[S,j]=(0,a.useState)(e.settings||v),[b,D]=(0,a.useState)(!0),[P,k]=(0,a.useState)(!0),[C,T]=(0,a.useState)({}),[I,N]=(0,a.useState)([]),[E,M]=(0,a.useState)(e.originalPost?.featuredImage||null),[$,V]=(0,a.useState)(!1),U=void 0!==c?c:$;(0,a.useEffect)(()=>{if(e.originalPost?.taxonomies){const t={};e.originalPost.taxonomies.forEach(e=>{t[e.slug]=e.assignedTermIds||[]}),T(t)}else T({})},[e.originalPost]),(0,a.useEffect)(()=>{e.originalPost?.customMeta?N(e.originalPost.customMeta.map(e=>({key:e.key,value:e.value,type:e.type||"string",isSerialized:e.isSerialized||!1}))):N([])},[e.originalPost]),(0,a.useEffect)(()=>{e.originalPost?.featuredImage?M(e.originalPost.featuredImage):M(null)},[e.originalPost]),(0,a.useEffect)(()=>{s&&s({...e,settings:S,taxonomyData:C,customMetaData:I,featuredImage:E,includeTaxonomies:b,includeCustomMeta:P})},[S,C,I,E,b,P]);const z=()=>{r?r(e.id):V(!$)},B=(()=>{if(S?.fullTitle)return S.fullTitle;const t=S?.title||(0,i.__)("Copy","post-duplicator");return`${e.originalPost?.title||""} ${t}`})(),A=E?.thumbnail||E?.url||null;return(0,l.jsxs)("div",{className:"duplicate-post-modal__post-item "+(U?"duplicate-post-modal__post-item--expanded":"duplicate-post-modal__post-item--collapsed"),children:[(0,l.jsx)("div",{className:"duplicate-post-modal__post-item-header",onClick:e=>{e.target.closest(".duplicate-post-modal__post-item-actions")||z()},children:(0,l.jsxs)(o.__experimentalHStack,{spacing:"12px",alignment:"center",children:[A&&(0,l.jsx)("img",{src:A,alt:"",className:"duplicate-post-modal__post-item-thumbnail"}),(0,l.jsx)("h3",{className:"duplicate-post-modal__post-item-title",children:B}),(0,l.jsxs)("div",{className:"duplicate-post-modal__post-item-actions",onClick:e=>e.stopPropagation(),children:[(0,l.jsx)(o.Button,{icon:U?f:h,variant:"tertiary",onClick:e=>{e.stopPropagation(),z()},label:U?(0,i.__)("Collapse","post-duplicator"):(0,i.__)("Expand","post-duplicator")}),d&&(0,l.jsx)(o.Button,{icon:m,variant:"tertiary",onClick:t=>{t.stopPropagation(),n&&n(e.id)},label:(0,i.__)("Remove","post-duplicator")})]})]})}),U&&(0,l.jsx)("div",{className:"duplicate-post-modal__post-item-content",children:(0,l.jsxs)(o.__experimentalVStack,{spacing:"20px",children:[(0,l.jsx)(p,{settings:S,onSettingsChange:j,postTypes:_,statusChoices:x,originalPost:e.originalPost,featuredImage:E,onFeaturedImageChange:M}),e.originalPost?.taxonomies&&e.originalPost.taxonomies.length>0&&(0,l.jsx)(u,{taxonomies:e.originalPost.taxonomies,onChange:e=>{T(e)},enabled:b,onToggle:D}),e.originalPost?.customMeta&&e.originalPost.customMeta.length>0&&(0,l.jsx)(g,{customMeta:e.originalPost.customMeta,onChange:e=>{N(e)},enabled:P,onToggle:k})]})})]})},x=({posts:e,onPostsChange:t,postTypes:s,statusChoices:i,siteUrl:n,currentUser:r,defaultSettings:c,isMultipleClonesMode:p=!1})=>{const[d,u]=(0,a.useState)(new Set),m=s=>{const a=e.map(e=>e.id===s.id?s:e);t&&t(a)},g=s=>{if(p){const t=e.filter(e=>e.isDuplicate);if(t.length<=1&&t.some(e=>e.id===s))return}const a=e.filter(e=>e.id!==s);t&&t(a);const o=new Set(d);o.delete(s),u(o)},f=e=>{const t=new Set(d);t.has(e)?t.delete(e):t.add(e),u(t)};if(!e||0===e.length)return null;const h=t=>!p||!!t.isDuplicate&&e.filter(e=>e.isDuplicate).length>1;return(0,l.jsx)(o.__experimentalVStack,{spacing:"12px",className:"duplicate-post-modal__post-list",children:e.map((e,t)=>(0,l.jsx)(_,{post:e,index:t,onUpdate:m,onDelete:g,onToggleExpand:f,isExpanded:d.has(e.id),showDelete:h(e),postTypes:s,statusChoices:i,siteUrl:n,currentUser:r,defaultSettings:c},e.id))})},y=()=>{const e=[{id:"email-customizer",name:"Email Customizer",tagline:(0,i.__)("Transform standard Gravity Forms notifications into stunning, on-brand emails using the familiar WordPress editor to build your templates.","post-duplicator"),cta:(0,i.__)("Learn More →","post-duplicator"),image:"/wp-content/plugins/post-duplicator/assets/img/marketing/email-customizer-bordered.svg",url:"https://www.metaphorcreations.com/wordpress-plugins/email-customizer/?campaign=post-duplicator&ref=266"}],[t]=(0,a.useState)(()=>{const t=Math.floor(Math.random()*e.length);return e[t]});return(0,l.jsxs)("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",className:"duplicate-post-modal__marketing-banner",children:[(0,l.jsx)("div",{className:"duplicate-post-modal__marketing-banner-image",children:(0,l.jsx)("img",{src:t.image,alt:t.name})}),(0,l.jsxs)("div",{className:"duplicate-post-modal__marketing-banner-content",children:[(0,l.jsx)("div",{className:"duplicate-post-modal__marketing-banner-title",children:t.name}),(0,l.jsx)("div",{className:"duplicate-post-modal__marketing-banner-tagline",children:t.tagline})]}),(0,l.jsx)("div",{className:"duplicate-post-modal__marketing-banner-cta",children:t.cta})]})},w=({isOpen:e,onClose:t,onDuplicate:s,originalPost:n,postsToDuplicate:c,mode:d="single",defaultSettings:m,postTypes:f,statusChoices:h,siteUrl:_,currentUser:w,isLoadingPostData:v=!1,initialDuplicationResult:S=null})=>{const j=window.postDuplicatorVars?.postTypesPublicSupport||{},b="bulk"===d||c&&c.length>0||S&&Array.isArray(S),[D,P]=(0,a.useState)("multiple-clones"===d),[k,C]=(0,a.useState)(2),T=()=>c&&c.length>0?c:n?[{id:`post-${n.id}`,originalPost:n,settings:{...m},isDuplicate:!1}]:[],[I,N]=(0,a.useState)(T()),[E,M]=(0,a.useState)(m),[$,V]=(0,a.useState)(!1),[U,z]=(0,a.useState)(!0),[B,A]=(0,a.useState)(!0),[H,R]=(0,a.useState)({}),[L,F]=(0,a.useState)([]),[O,W]=(0,a.useState)(null),[G,X]=(0,a.useState)("idle"),[Z,J]=(0,a.useState)(null),[q,K]=(0,a.useState)(""),[Q,Y]=(0,a.useState)([]),[ee,te]=(0,a.useState)(0),se=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(e&&!se.current)if(S)M(m),Array.isArray(S)?(Y(S),X("complete"),N([])):(S.postId&&J(S.postId),S.title&&K(S.title),W(S.featuredImage||null),S.postType&&M({...m,type:S.postType===n?.type?"same":S.postType}),X("complete"),N([]));else{M(m),z(!0),A(!0),X("idle"),J(null),K(""),Y([]);const e=T();N(e),P("multiple-clones"===d),C(2)}!e&&se.current&&(te(e=>e+1),M(m),z(!0),A(!0),R({}),F([]),W(null),Y([])),se.current=e},[e,m,d,S]),(0,a.useEffect)(()=>{S&&(Array.isArray(S)?(Y(S),X("complete")):(S.postId&&J(S.postId),S.title&&K(S.title),W(S.featuredImage||null),S.postType&&M(e=>({...e,type:S.postType===n?.type?"same":S.postType})),X("complete")))},[S,n]),(0,a.useEffect)(()=>{if(e&&"idle"===G){const e=T();N(e)}},[n,c,e,G]),I.filter(e=>e.isDuplicate).length;const ae=(0,a.useRef)(k),oe=(0,a.useRef)(!1);(0,a.useEffect)(()=>{ae.current=k},[k]),(0,a.useEffect)(()=>{if(D&&!b&&"idle"===G&&!oe.current){const e=I.filter(e=>e.isDuplicate).length;e<ae.current&&e>=1&&(oe.current=!0,C(e),setTimeout(()=>{oe.current=!1},0))}},[I,D,b,G]);const ie=(e,t,s)=>{if(!t.time_offset)return null;let a;a="duplicate"===t.timestamp&&s?.date?new Date(s.date):new Date;const o=(864e5*(t.time_offset_days||0)+36e5*(t.time_offset_hours||0)+6e4*(t.time_offset_minutes||0)+1e3*(t.time_offset_seconds||0))*(e+1);return"newer"===t.time_offset_direction?a.setTime(a.getTime()+o):a.setTime(a.getTime()-o),a.toISOString()};if((0,a.useEffect)(()=>{if(!D||b||"idle"!==G)return;const e=I.find(e=>!e.isDuplicate);if(!e)return;if(!m.time_offset)return;const t=I.map((t,s)=>{if(!t.isDuplicate)return t;const a=I.filter(e=>e.isDuplicate).findIndex(e=>e.id===t.id);if(-1===a)return t;const o=ie(a,m,e.originalPost);return o?{...t,settings:{...t.settings,customDate:o,timestamp:"custom"}}:t});t.some((e,t)=>e.settings?.customDate!==I[t]?.settings?.customDate)&&N(t)},[m.time_offset,m.time_offset_days,m.time_offset_hours,m.time_offset_minutes,m.time_offset_seconds,m.time_offset_direction,m.timestamp,D,b,G]),(0,a.useEffect)(()=>{if(!oe.current)if(D&&!b&&"idle"===G){const e=I.find(e=>!e.isDuplicate);if(!e)return;const t=I.filter(e=>e.isDuplicate),s=Math.max(1,k);if(t.length!==s){oe.current=!0;const a=[];for(let o=0;o<s;o++){const s=t[o];if(s)a.push(s);else{const t=ie(o,m,e.originalPost),s={...m};t&&(s.customDate=t,s.timestamp="custom"),a.push({id:`clone-${e.originalPost.id}-${o}`,originalPost:e.originalPost,settings:s,isDuplicate:!0})}}N([e,...a]),ae.current=s,setTimeout(()=>{oe.current=!1},0)}}else if(!D&&!b&&I.length>1&&"idle"===G){const e=I.find(e=>!e.isDuplicate)||I[0];e&&N([{...e,isDuplicate:!1}])}},[D,b,k,G]),(0,a.useEffect)(()=>{if(!e||"idle"!==G||D||b)return;const t=I[0]?.originalPost||n;if(t){if(t?.taxonomies){const e={};t.taxonomies.forEach(t=>{e[t.slug]=t.assignedTermIds||[]}),R(e)}else R({});F(t?.customMeta?t.customMeta.map(e=>({key:e.key,value:e.value,type:e.type||"string",isSerialized:e.isSerialized||!1})):[]),W(t?.featuredImage?t.featuredImage:null)}},[e,n,G,D,b,I]),(0,a.useEffect)(()=>{const t=D||b?I[0]?.featuredImage||null:O;if(e){const e=setTimeout(()=>{const e=document.querySelector(".duplicate-post-modal.components-modal__frame"),s=e?.closest(".components-modal__screen-overlay");s&&s.classList.add("duplicate-post-modal-overlay"),t&&e&&e.style.setProperty("--featured-image-url",`url(${t.thumbnail||t.url})`)},0);return()=>{clearTimeout(e);const t=document.querySelector(".duplicate-post-modal.components-modal__frame"),s=t?.closest(".components-modal__screen-overlay");s&&s.classList.remove("duplicate-post-modal-overlay")}}},[O,I,D,b,e]),!e)return null;const ne=()=>{"duplicating"!==G&&("complete"===G&&(X("idle"),J(null),K("")),t())},le=I[0]?.originalPost||n,re=D||b?I[0]?.featuredImage||null:O,ce=c&&0!==c.length||!n||"idle"!==G?null:(0,l.jsx)(o.__experimentalHStack,{spacing:"4px",style:{flex:0},children:(0,l.jsx)(o.Button,{icon:r,size:"compact",variant:D?"primary":"secondary",onClick:()=>{const e=!D;P(e),e&&k<2&&C(2)},label:D?(0,i.__)("Multiple Clone","post-duplicator"):(0,i.__)("Single Clone","post-duplicator"),isPressed:D})});return(0,l.jsxs)(o.Modal,{title:(()=>{if(b)return(0,i.__)("Duplicate Posts","post-duplicator");if(D){const e=I[0]?.originalPost||n,t=e?.featuredImage?.thumbnail||e?.featuredImage?.url;return e?.title?t?(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[(0,l.jsx)("img",{src:t,alt:"",style:{width:"40px",height:"40px",objectFit:"cover",borderRadius:"4px",flexShrink:0}}),(0,l.jsx)("span",{children:(0,i.__)(`Duplicate: ${e.title}`,"post-duplicator")})]}):(0,i.__)(`Duplicate: ${e.title}`,"post-duplicator"):(0,i.__)("Duplicate Post","post-duplicator")}const e=I[0]?.originalPost||n;return e?.title?E.fullTitle?E.fullTitle:`${e.title} ${E.title}`:""})(),onRequestClose:ne,headerActions:ce,className:"duplicate-post-modal "+(re?"duplicate-post-modal--has-featured-image":""),size:"large",style:{borderRadius:0},children:[(0,l.jsx)("div",{className:"duplicate-post-modal__content",style:{paddingBottom:"idle"===G?"77px":"0"},children:v?(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"60px 20px",minHeight:"200px"},children:[(0,l.jsx)(o.Spinner,{}),(0,l.jsx)("p",{style:{marginTop:"16px",color:"#646970"},children:b||c&&c.length>0?(0,i.__)("Loading posts data...","post-duplicator"):(0,i.__)("Loading post data...","post-duplicator")})]}):"idle"===G?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(o.__experimentalVStack,{className:"duplicate-post-modal__settings",spacing:"20px",children:[D&&!b&&(!c||0===c.length)&&n&&(0,l.jsx)("div",{className:"duplicate-post-modal__clone-count",children:(0,l.jsx)(o.__experimentalNumberControl,{label:(0,i.__)("Number of Clones","post-duplicator"),value:k,onChange:e=>{const t=Math.max(1,Math.min(50,parseInt(e)||1));C(t)},min:1,max:50,__nextHasNoMarginBottom:!0,__next40pxDefaultSize:!0})}),!D&&!b&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(p,{settings:E,onSettingsChange:M,postTypes:f,statusChoices:h,originalPost:le,featuredImage:O,onFeaturedImageChange:W},`duplicate-settings-${le?.id||0}-${ee}`),le?.taxonomies&&le.taxonomies.length>0&&(0,l.jsx)(u,{taxonomies:le.taxonomies,onChange:e=>{R(e)},enabled:U,onToggle:z}),le?.customMeta&&le.customMeta.length>0&&(0,l.jsx)(g,{customMeta:le.customMeta,onChange:e=>{F(e)},enabled:B,onToggle:A})]}),(D||b)&&(0,l.jsx)(x,{posts:D&&!b?I.filter(e=>e.isDuplicate):I,onPostsChange:e=>{if(D&&!b){if(e.filter(e=>e.isDuplicate).length<1)return;const t=I.find(e=>!e.isDuplicate);N(t?[t,...e]:e)}else N(e)},postTypes:f,statusChoices:h,siteUrl:_,currentUser:w,defaultSettings:m,isMultipleClonesMode:D&&!b})]}),(0,l.jsx)(y,{})]}):(0,l.jsxs)("div",{className:"duplicate-post-modal__status",children:[!D&&!b&&(0,l.jsxs)("div",{className:"duplicate-post-modal__status-item",children:[(()=>{const e=O||S&&S.featuredImage;return e&&(e.thumbnail||e.url)?(0,l.jsx)("img",{src:e.thumbnail||e.url,alt:"",className:"duplicate-post-modal__status-thumbnail"}):null})(),(0,l.jsx)("h3",{className:"duplicate-post-modal__status-title",children:q}),(0,l.jsx)("div",{className:"duplicate-post-modal__status-actions",children:"duplicating"===G?(0,l.jsx)(o.Spinner,{}):(0,l.jsxs)(l.Fragment,{children:[(()=>{const e=Z||S&&S.postId;if(!e)return null;let t;t=S&&S.postType?S.postType:"same"===E.type?n?.type:E.type;const s=!1!==j[t],a=S?.permalink||Q[0]?.permalink||`${_}/?p=${e}`;return s&&(0,l.jsx)(o.Button,{variant:"secondary",onClick:()=>window.open(a,"_blank"),children:(0,i.__)("View Post","post-duplicator")})})(),(()=>{const e=Z||S&&S.postId;if(!e)return null;let t;t=S&&S.postType?S.postType:"same"===E.type?n?.type:E.type;const s=t&&"post"!==t?`${_}/wp-admin/post.php?post=${e}&action=edit&post_type=${t}`:`${_}/wp-admin/post.php?post=${e}&action=edit`;return(0,l.jsx)(o.Button,{variant:"primary",onClick:()=>{window.open(s,"_blank")},children:(0,i.__)("Edit Post","post-duplicator")})})()]})})]}),(D||b)&&(0,l.jsxs)(o.__experimentalVStack,{spacing:"12px",className:"duplicate-post-modal__success-list",children:["duplicating"===G&&(0,l.jsxs)("div",{style:{textAlign:"center",padding:"20px"},children:[(0,l.jsx)(o.Spinner,{}),(0,l.jsx)("p",{style:{marginTop:"12px"},children:(0,i.__)("Duplicating posts...","post-duplicator")})]}),"complete"===G&&0===Q.length&&(0,l.jsx)("div",{style:{textAlign:"center",padding:"20px"},children:(0,l.jsx)("p",{children:(0,i.__)("No posts were duplicated.","post-duplicator")})}),Q.length>0&&Q.map((e,t)=>(0,l.jsx)("div",{className:"duplicate-post-modal__success-item "+(e.success?"":"duplicate-post-modal__success-item--error"),children:e.success?(0,l.jsxs)(l.Fragment,{children:[e.featuredImage&&(0,l.jsx)("img",{src:e.featuredImage.thumbnail||e.featuredImage.url,alt:"",className:"duplicate-post-modal__status-thumbnail"}),(0,l.jsx)("h3",{className:"duplicate-post-modal__status-title",children:e.title}),(0,l.jsxs)("div",{className:"duplicate-post-modal__status-actions",children:[(()=>{const t=e.postType||e.originalPost?.type,s=!1!==j[t],a=e.permalink||`${_}/?p=${e.postId}`;return s&&(0,l.jsx)(o.Button,{variant:"secondary",onClick:()=>window.open(a,"_blank"),children:(0,i.__)("View Post","post-duplicator")})})(),(0,l.jsx)(o.Button,{variant:"primary",onClick:()=>{const t=e.postType||e.originalPost?.type,s=t&&"post"!==t?`${_}/wp-admin/post.php?post=${e.postId}&action=edit&post_type=${t}`:`${_}/wp-admin/post.php?post=${e.postId}&action=edit`;window.open(s,"_blank")},children:(0,i.__)("Edit Post","post-duplicator")})]})]}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("h3",{className:"duplicate-post-modal__status-title",children:e.title||e.originalPost?.title||(0,i.__)("Unknown Post","post-duplicator")}),(0,l.jsxs)("div",{className:"duplicate-post-modal__status-error",children:[(0,i.__)("Error:","post-duplicator")," ",e.error]})]})},t))]})]})}),"idle"===G&&(0,l.jsxs)(o.__experimentalHStack,{alignment:"right",className:"duplicate-post-modal__footer",style:{position:"absolute",bottom:"0px",left:"0",padding:"20px",borderTop:"1px solid rgba(0, 0, 0, 0.1)",background:"#FFF"},children:[(0,l.jsx)(o.Button,{variant:"tertiary",onClick:ne,disabled:$||v,children:(0,i.__)("Cancel","post-duplicator")}),(0,l.jsx)(o.Button,{variant:"primary",onClick:async()=>{if(0===I.length)return;V(!0),X("duplicating"),Y([]);const e=[];if(D||b){const t=D&&!b?I.filter(e=>e.isDuplicate):I;for(let a=0;a<t.length;a++){const o=t[a],n=o.settings||m,l=o.taxonomyData||{},r=o.customMetaData||[],c=o.featuredImage||null,p=void 0===o.includeTaxonomies||o.includeTaxonomies,d=void 0===o.includeCustomMeta||o.includeCustomMeta,u=n.fullTitle||`${o.originalPost.title} ${n.title||(0,i.__)("Copy","post-duplicator")}`;try{const t={...n,includeTaxonomies:p,includeCustomMeta:d,...p?{taxonomyData:l}:{},customMetaData:r,featuredImageId:c?.id||null};await new Promise((a,i)=>{s(o.originalPost.id,t,{onSuccess:t=>{const s="same"===n.type?o.originalPost.type:n.type;e.push({success:!0,postId:t.duplicate_id,permalink:t.permalink,title:u,originalPost:o.originalPost,featuredImage:c,postType:s}),Y([...e]),a(t)},onError:t=>{console.error(`Error duplicating post ${o.originalPost.id}:`,t),e.push({success:!1,error:t.message||t.data?.message||"Unknown error",title:u,originalPost:o.originalPost}),Y([...e]),a(null)}})})}catch(t){e.push({success:!1,error:t.message||"Unknown error",title:u,originalPost:o.originalPost}),Y([...e])}}X("complete"),V(!1)}else{const t=I[0],a=E.fullTitle||`${t.originalPost.title} ${E.title}`;K(a);try{const o=void 0!==E.selectedParentId?E.selectedParentId:t.originalPost?.parent>0?t.originalPost.parent:null,i={...E,includeTaxonomies:U,includeCustomMeta:B,...U?{taxonomyData:H}:{},customMetaData:L,featuredImageId:O?.id||null,selectedParentId:o};await new Promise((o,n)=>{s(t.originalPost.id,i,{onSuccess:s=>{const i="same"===E.type?t.originalPost.type:E.type;e.push({success:!0,postId:s.duplicate_id,permalink:s.permalink,title:a,originalPost:t.originalPost,featuredImage:O,postType:i}),Y(e),J(s.duplicate_id),X("complete"),V(!1),o(s)},onError:s=>{console.error("Error duplicating:",s),e.push({success:!1,error:s.message||s.data?.message||"Unknown error",originalPost:t.originalPost}),Y(e),X("complete"),V(!1),n(s)}})})}catch(e){}}},disabled:$||v||0===I.length,isBusy:$,children:$?(0,i.__)("Duplicating...","post-duplicator"):(()=>{if(b||D){const e=D&&!b?k:I.length;return(0,i.__)(`Duplicate ${e} ${1===e?"Post":"Posts"}`,"post-duplicator")}const e=I[0]?.originalPost||n,t="same"===E.type?e?.type:E.type;let s=f[t];if(!s&&t){const e=(window.postDuplicatorVars?.allPostTypes||[]).find(e=>e.id===t);s=e?.label||t}else s||(s=t);return(0,i.__)(`Duplicate ${s}`,"post-duplicator")})()})]})]})},v=async(e,t,s={})=>{const{onSuccess:a,onError:o}=s,i=Number.parseInt(t?.selectedParentId,10),n=Number.isFinite(i)&&i>0?i:null;try{const s=await fetch(`${postDuplicatorVars.restUrl}duplicate-post`,{method:"POST",headers:{"X-WP-Nonce":postDuplicatorVars.nonce,"Content-Type":"application/json"},body:JSON.stringify({original_id:e,...t,selectedParentId:n})});if(!s.ok){const e=await s.json(),t=new Error(e.message||"Failed to duplicate post");throw t.data=e,t}const o=await s.json();return o.duplicate_id&&a&&a(o),o}catch(e){throw console.error("Error duplicating post:",e),o&&o(e),e}};function S(e,t="error"){const s=document.createElement("div");s.classList.add("my-snackbar",`my-snackbar--${t}`),s.textContent=e,document.body.appendChild(s),setTimeout(()=>{s.classList.add("my-snackbar--hide"),s.addEventListener("transitionend",()=>s.remove())},3e3)}const j=async(e,t="post")=>{const s=await fetch(`${postDuplicatorVars.restUrl}post-full-data/${e}`,{headers:{"X-WP-Nonce":postDuplicatorVars.nonce}});if(!s.ok)throw new Error("Failed to fetch post data");const a=await s.json();let o=[],i=[];try{const t=await fetch(`${postDuplicatorVars.restUrl}post-data/${e}`,{headers:{"X-WP-Nonce":postDuplicatorVars.nonce}});if(t.ok){const e=await t.json();o=e.taxonomies||[],i=e.customMeta||[]}}catch(e){console.error("Error fetching post data:",e)}return{id:a.id,title:a.title,type:a.type,status:a.status,slug:a.slug,date:a.date,author:a.author,authorId:a.authorId,parent:a.parent||0,parentPost:a.parentPost,taxonomies:o,customMeta:i,featuredImage:a.featuredImage}},b=()=>{const[e,t]=(0,a.useState)(!1),[s,o]=(0,a.useState)(null),[i,n]=(0,a.useState)(null),[r,c]=(0,a.useState)("single"),[p,d]=(0,a.useState)(!1),[u,m]=(0,a.useState)(!1),[g,f]=(0,a.useState)(null),h=()=>{if(window.location.href.includes("nestedpages")){const e=new URL(window.location.href);e.searchParams.set("pd_refresh",Date.now()),window.location.replace(e.toString())}else window.location.reload()};return(0,a.useEffect)(()=>{const e=async e=>{if(e.target.classList.contains("m4c-duplicate-post")){e.preventDefault();const s=e.target.getAttribute("data-postid"),a=e.target.getAttribute("data-posttype")||"post";if("basic"===(postDuplicatorVars.mode||"advanced")){m(!0);try{const e=await j(s,a);let i={};e.taxonomies&&e.taxonomies.forEach(e=>{i[e.slug]=e.assignedTermIds||[]});const n=(e.customMeta||[]).map(e=>({key:e.key,value:e.value,type:e.type||"string",isSerialized:e.isSerialized||!1})),l={...postDuplicatorVars.defaultSettings,includeTaxonomies:!0,includeCustomMeta:!0,taxonomyData:i,customMetaData:n,featuredImageId:e.featuredImage?.id||null,selectedParentId:e.parent>0?e.parent:null};await v(s,l,{onSuccess:async s=>{m(!1);const i=window.location.href.includes("/wp-admin/post.php")&&window.location.href.includes("action=edit")?postDuplicatorVars.singleAfterDuplicationAction||"notice":postDuplicatorVars.listSingleAfterDuplicationAction||"notice",n="same"===l.type?a:l.type,r=`${e.title} ${postDuplicatorVars.defaultSettings.title}`;let p=null;if("notice"===i)try{const e=await fetch(`${postDuplicatorVars.restUrl}post-full-data/${s.duplicate_id}`,{headers:{"X-WP-Nonce":postDuplicatorVars.nonce}});e.ok&&(p=(await e.json()).featuredImage||null)}catch(e){console.error("Error fetching duplicated post featured image:",e)}if("notice"===i)d(!0),o(e),f({postId:s.duplicate_id,permalink:s.permalink,title:r,featuredImage:p||e.featuredImage,postType:n}),c("single"),t(!0);else if("new_tab"===i){const e="post"!==n?`${postDuplicatorVars.siteUrl}/wp-admin/post.php?post=${s.duplicate_id}&action=edit&post_type=${n}`:`${postDuplicatorVars.siteUrl}/wp-admin/post.php?post=${s.duplicate_id}&action=edit`;window.open(e,"_blank")}else if("same_tab"===i){const e="post"!==n?`${postDuplicatorVars.siteUrl}/wp-admin/post.php?post=${s.duplicate_id}&action=edit&post_type=${n}`:`${postDuplicatorVars.siteUrl}/wp-admin/post.php?post=${s.duplicate_id}&action=edit`;window.location.href=e}else"refresh"===i&&(d(!0),h())},onError:e=>{m(!1),S(`Error duplicating post: ${e.message||e.data?.message||"Unknown error"}`,"error")}})}catch(e){console.error("Error in basic mode duplication:",e),m(!1),S("Failed to duplicate post. Please try again.","error")}}else{o(null),n(null),c("single"),m(!0),t(!0);try{const e=await j(s,a);o(e),m(!1)}catch(e){console.error("Error fetching post:",e),m(!1),t(!1),S("Error loading post data. Please try again.","error")}}}};return document.body.addEventListener("click",e),()=>{document.body.removeEventListener("click",e)}},[]),(0,a.useEffect)(()=>{const e=async e=>{const{postIds:s,postType:a}=e.detail;if(s&&0!==s.length)if("basic"===(postDuplicatorVars.mode||"advanced")){m(!0),"notice"===(postDuplicatorVars.listMultipleAfterDuplicationAction||"notice")&&(c("bulk"),t(!0));try{const e=s.map(e=>j(e,a).catch(t=>(console.error(`Error fetching post ${e}:`,t),null))),o=(await Promise.all(e)).filter(e=>null!==e);if(0===o.length)return m(!1),t(!1),void S("Error loading post data. Please try again.","error");const i=[];for(const e of o)try{let t={};e.taxonomies&&e.taxonomies.forEach(e=>{t[e.slug]=e.assignedTermIds||[]});const s=(e.customMeta||[]).map(e=>({key:e.key,value:e.value,type:e.type||"string",isSerialized:e.isSerialized||!1})),a={...postDuplicatorVars.defaultSettings,includeTaxonomies:!0,includeCustomMeta:!0,taxonomyData:t,customMetaData:s,featuredImageId:e.featuredImage?.id||null,selectedParentId:e.parent>0?e.parent:null},o="same"===a.type?e.type:a.type,n=`${e.title} ${postDuplicatorVars.defaultSettings.title}`;await v(e.id,a,{onSuccess:t=>{i.push({success:!0,postId:t.duplicate_id,permalink:t.permalink,title:n,originalPost:e,featuredImage:e.featuredImage,postType:o})},onError:t=>{i.push({success:!1,error:t.message||t.data?.message||"Unknown error",title:n,originalPost:e})}})}catch(t){console.error(`Error duplicating post ${e.id}:`,t),i.push({success:!1,error:t.message||"Unknown error",title:`${e.title} ${postDuplicatorVars.defaultSettings.title}`,originalPost:e})}m(!1);const n=postDuplicatorVars.listMultipleAfterDuplicationAction||"notice";"notice"===n?(d(!0),f(i)):"refresh"===n&&(d(!0),h())}catch(e){console.error("Error in bulk duplication:",e),m(!1),t(!1),S("Error duplicating posts. Please try again.","error")}}else{n(null),o(null),c("bulk"),m(!0),t(!0);try{const e=s.map(e=>j(e,a).catch(t=>(console.error(`Error fetching post ${e}:`,t),null))),o=(await Promise.all(e)).filter(e=>null!==e);if(0===o.length)return m(!1),t(!1),void S("Error loading post data. Please try again.","error");const i=o.map((e,t)=>({id:`bulk-${e.id}-${t}`,originalPost:e,settings:{...postDuplicatorVars.defaultSettings},isDuplicate:!1}));n(i),m(!1)}catch(e){console.error("Error fetching posts:",e),m(!1),t(!1),S("Error loading post data. Please try again.","error")}}};return document.addEventListener("m4c:bulk-duplicate",e),()=>{document.removeEventListener("m4c:bulk-duplicate",e)}},[]),(0,l.jsx)(w,{isOpen:e,onClose:()=>{const e=p&&(window.location.href.includes("/wp-admin/edit.php")||!1===window.location.href.includes("/wp-admin/post.php"));t(!1),o(null),n(null),d(!1),m(!1),f(null),e&&h()},onDuplicate:async(e,t,s)=>{await v(e,t,{onSuccess:e=>{d(!0),s?.onSuccess&&s.onSuccess(e)},onError:e=>{S(`Error duplicating post: ${e.message||e.data?.message||"Unknown error"}`,"error"),s?.onError&&s.onError(e)}})},originalPost:s,postsToDuplicate:i,mode:r,defaultSettings:postDuplicatorVars.defaultSettings,postTypes:postDuplicatorVars.postTypes,statusChoices:postDuplicatorVars.statusChoices,siteUrl:postDuplicatorVars.siteUrl,currentUser:postDuplicatorVars.currentUser,isLoadingPostData:u,initialDuplicationResult:g})};document.addEventListener("DOMContentLoaded",function(){const e=document.createElement("div");e.id="duplicate-post-modal-root",document.body.appendChild(e),"function"==typeof a.createRoot?(0,a.createRoot)(e).render((0,l.jsx)(b,{})):(0,a.render)((0,l.jsx)(b,{}),e)})})();
Save File
Cancel