diff --git a/classifai.php b/classifai.php index ae888bb23..83637ffa5 100644 --- a/classifai.php +++ b/classifai.php @@ -4,7 +4,7 @@ * Plugin URI: https://github.com/10up/classifai * Update URI: https://classifaiplugin.com * Description: Enhance your WordPress content with Artificial Intelligence and Machine Learning services. - * Version: 2.2.0 + * Version: 2.2.1 * Requires at least: 5.7 * Requires PHP: 7.4 * Author: 10up diff --git a/config.php b/config.php index 85d1ebb91..31759e718 100644 --- a/config.php +++ b/config.php @@ -4,7 +4,7 @@ * declared here instead of a Class. */ -$plugin_version = '2.2.0'; +$plugin_version = '2.2.1'; if ( file_exists( __DIR__ . '/.commit' ) ) { $plugin_version .= '-' . file_get_contents( __DIR__ . '/.commit' ); diff --git a/dist/editor-ocr.asset.php b/dist/editor-ocr.asset.php index 84a5d7edb..3453c2ebe 100644 --- a/dist/editor-ocr.asset.php +++ b/dist/editor-ocr.asset.php @@ -1 +1 @@ - array('wp-api-fetch', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-compose', 'wp-data', 'wp-element', 'wp-hooks', 'wp-i18n'), 'version' => 'cb24a9f6886a387dccbc'); + array('wp-api-fetch', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-compose', 'wp-data', 'wp-element', 'wp-hooks', 'wp-i18n'), 'version' => '042da824a7c565fcbef1'); diff --git a/dist/editor-ocr.js b/dist/editor-ocr.js index 621467b7f..50287bd45 100644 --- a/dist/editor-ocr.js +++ b/dist/editor-ocr.js @@ -1 +1 @@ -(()=>{"use strict";const e=window.wp.element,t=window.wp.data,c=window.wp.blocks,n=window.wp.apiFetch,o=window.wp.hooks,i=window.wp.compose,r=window.wp.blockEditor,a=window.wp.components,l=window.wp.i18n,{find:s,debounce:d}=lodash,p=(0,e.createElement)("span",{className:"dashicons dashicons-editor-paste-text"}),m=async(e,n,o)=>{if(!o)return;const{getBlockIndex:i}=(0,t.select)("core/block-editor"),r=(0,c.createBlock)("core/group",{anchor:`classifai-ocr-${n}`,className:"is-style-classifai-ocr-text"}),a=(0,c.createBlock)("core/paragraph",{content:o});await(0,t.dispatch)("core/block-editor").insertBlock(r,i(e)+1),(0,t.dispatch)("core/block-editor").insertBlock(a,0,r.clientId)},u=function(e){let c=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];if(0===c.length){const{getBlocks:e}=(0,t.select)("core/block-editor");c=e()}return!!s(c,(t=>t.attributes.anchor===`classifai-ocr-${e}`))},f=(0,i.createHigherOrderComponent)((t=>c=>{const[o,i]=(0,e.useState)(!1),{attributes:s,clientId:d,isSelected:f,name:b,setAttributes:h}=c;return f&&"core/image"==b?(!s.ocrChecked&&s.id&&(async e=>{const t=await(0,n.apiFetch)({path:`/wp/v2/media/${e}`});return!(!Object.prototype.hasOwnProperty.call(t,"classifai_has_ocr")||!t.classifai_has_ocr)&&!!(Object.prototype.hasOwnProperty.call(t,"description")&&Object.prototype.hasOwnProperty.call(t.description,"rendered")&&t.description.rendered)&&t.description.rendered.replace(/(<([^>]+)>)/gi,"").replace(/(\r\n|\n|\r)/gm,"").trim()})(s.id).then((e=>{e?(h({ocrScannedText:e,ocrChecked:!0}),i(!0)):h({ocrChecked:!0})})),(0,e.createElement)(e.Fragment,null,(0,e.createElement)(t,c),s.ocrScannedText&&(0,e.createElement)(r.BlockControls,null,(0,e.createElement)(a.ToolbarGroup,null,(0,e.createElement)(a.ToolbarButton,{label:(0,l.__)("Insert scanned text into content","classifai"),icon:p,onClick:()=>m(d,s.id,s.ocrScannedText),disabled:u(s.id)}))),o&&(0,e.createElement)(a.Modal,{title:(0,l.__)("ClassifAI detected text in your image","classifai")},(0,e.createElement)("p",null,(0,l.__)("Would you like to insert the scanned text under this image block? This enhances search indexing and accessibility for your readers.","classifai")),(0,e.createElement)(a.Flex,{align:"flex-end",justify:"flex-end"},(0,e.createElement)(a.FlexItem,null,(0,e.createElement)(a.Button,{isPrimary:!0,onClick:()=>{m(d,s.id,s.ocrScannedText),i(!1)}},(0,l.__)("Insert text","classifai"))),(0,e.createElement)(a.FlexItem,null,(0,e.createElement)(a.Button,{isSecondary:!0,onClick:()=>i(!1)},(0,l.__)("Dismiss","classifai"))))))):(0,e.createElement)(t,c)}),"imageOcrControl");(0,o.addFilter)("editor.BlockEdit","classifai/image-processing-ocr",f),(0,o.addFilter)("blocks.registerBlockType","classifai/image-processing-ocr",((e,t)=>("core/image"!==t||e.attributes&&(e.attributes.ocrScannedText={type:"string",default:""},e.attributes.ocrChecked={type:"boolean",default:!1}),e))),wp.blocks.registerBlockStyle("core/group",{name:"classifai-ocr-text",label:(0,l.__)("Scanned Text from Image","classifai")});{let e,c=[];(0,t.subscribe)(d((()=>{const n=(0,t.select)("core/block-editor"),r=n.getSelectedBlock(),a=n.getBlocks();if(null===r)return i(),void(e=r);if(r!==e&&!c.includes(r.clientId))if(i(),e=r,"core/image"===r.name){const e=s(a,(e=>e.attributes.anchor===`classifai-ocr-${r.attributes.id}`));void 0!==e&&o([e.clientId,r.clientId])}else{const e=n.getBlock(n.getBlockHierarchyRootClientId(r.clientId));if("core/group"===e.name){let t=/classifai-ocr-([0-9]+)/.exec(e.attributes.anchor);if(null!==t){[,t]=t;const c=s(a,(e=>e.attributes.id==t));void 0!==c&&o([c.clientId,e.clientId])}}}}),100));const n=()=>{const e=document.head||document.getElementsByTagName("head")[0],t=document.createElement("style");return t.setAttribute("id","classifai-ocr-style"),e.appendChild(t),t},o=e=>{var t;const o=null!==(t=document.getElementById("classifai-ocr-style"))&&void 0!==t?t:n(),i=`${e.map((e=>`#block-${e}:before`)).join(", ")} {\n\t\t\tcontent: "";\n\t\t\tposition: absolute;\n\t\t\tdisplay: block;\n\t\t\ttop: 0;\n\t\t\tleft: -15px;\n\t\t\tbottom: 0;\n\t\t\tborder-left: 4px solid #cfe7f3;\n\t\t\tmix-blend-mode: difference;\n\t\t\topacity: 0.25;\n\t\t}`;o.appendChild(document.createTextNode(i)),c=e},i=()=>{if(0===c.length)return;const e=document.getElementById("classifai-ocr-style");e&&(e.innerText=""),c=[]}}})(); \ No newline at end of file +(()=>{"use strict";const e=window.wp.element,t=window.wp.data,c=window.wp.blocks,n=window.wp.apiFetch,o=window.wp.hooks,i=window.wp.compose,r=window.wp.blockEditor,a=window.wp.components,l=window.wp.i18n,{find:s,debounce:d}=lodash,p=(0,e.createElement)("span",{className:"dashicons dashicons-editor-paste-text"}),m=async(e,n,o)=>{if(!o)return;const{getBlockIndex:i}=(0,t.select)("core/block-editor"),r=(0,c.createBlock)("core/group",{anchor:`classifai-ocr-${n}`,className:"is-style-classifai-ocr-text"}),a=(0,c.createBlock)("core/paragraph",{content:o});await(0,t.dispatch)("core/block-editor").insertBlock(r,i(e)+1),(0,t.dispatch)("core/block-editor").insertBlock(a,0,r.clientId)},u=(e,c=[])=>{if(0===c.length){const{getBlocks:e}=(0,t.select)("core/block-editor");c=e()}return!!s(c,(t=>t.attributes.anchor===`classifai-ocr-${e}`))},f=(0,i.createHigherOrderComponent)((t=>c=>{const[o,i]=(0,e.useState)(!1),{attributes:s,clientId:d,isSelected:f,name:b,setAttributes:h}=c;return f&&"core/image"==b?(!s.ocrChecked&&s.id&&(async e=>{const t=await(0,n.apiFetch)({path:`/wp/v2/media/${e}`});return!(!Object.prototype.hasOwnProperty.call(t,"classifai_has_ocr")||!t.classifai_has_ocr)&&!!(Object.prototype.hasOwnProperty.call(t,"description")&&Object.prototype.hasOwnProperty.call(t.description,"rendered")&&t.description.rendered)&&t.description.rendered.replace(/(<([^>]+)>)/gi,"").replace(/(\r\n|\n|\r)/gm,"").trim()})(s.id).then((e=>{e?(h({ocrScannedText:e,ocrChecked:!0}),i(!0)):h({ocrChecked:!0})})),(0,e.createElement)(e.Fragment,null,(0,e.createElement)(t,c),s.ocrScannedText&&(0,e.createElement)(r.BlockControls,null,(0,e.createElement)(a.ToolbarGroup,null,(0,e.createElement)(a.ToolbarButton,{label:(0,l.__)("Insert scanned text into content","classifai"),icon:p,onClick:()=>m(d,s.id,s.ocrScannedText),disabled:u(s.id)}))),o&&(0,e.createElement)(a.Modal,{title:(0,l.__)("ClassifAI detected text in your image","classifai")},(0,e.createElement)("p",null,(0,l.__)("Would you like to insert the scanned text under this image block? This enhances search indexing and accessibility for your readers.","classifai")),(0,e.createElement)(a.Flex,{align:"flex-end",justify:"flex-end"},(0,e.createElement)(a.FlexItem,null,(0,e.createElement)(a.Button,{isPrimary:!0,onClick:()=>{m(d,s.id,s.ocrScannedText),i(!1)}},(0,l.__)("Insert text","classifai"))),(0,e.createElement)(a.FlexItem,null,(0,e.createElement)(a.Button,{isSecondary:!0,onClick:()=>i(!1)},(0,l.__)("Dismiss","classifai"))))))):(0,e.createElement)(t,c)}),"imageOcrControl");(0,o.addFilter)("editor.BlockEdit","classifai/image-processing-ocr",f),(0,o.addFilter)("blocks.registerBlockType","classifai/image-processing-ocr",((e,t)=>("core/image"!==t||e.attributes&&(e.attributes.ocrScannedText={type:"string",default:""},e.attributes.ocrChecked={type:"boolean",default:!1}),e))),wp.blocks.registerBlockStyle("core/group",{name:"classifai-ocr-text",label:(0,l.__)("Scanned Text from Image","classifai")});{let e,c=[];(0,t.subscribe)(d((()=>{const n=(0,t.select)("core/block-editor"),r=n.getSelectedBlock(),a=n.getBlocks();if(null===r)return i(),void(e=r);if(r!==e&&!c.includes(r.clientId))if(i(),e=r,"core/image"===r.name){const e=s(a,(e=>e.attributes.anchor===`classifai-ocr-${r.attributes.id}`));void 0!==e&&o([e.clientId,r.clientId])}else{const e=n.getBlock(n.getBlockHierarchyRootClientId(r.clientId));if("core/group"===e.name){let t=/classifai-ocr-([0-9]+)/.exec(e.attributes.anchor);if(null!==t){[,t]=t;const c=s(a,(e=>e.attributes.id==t));void 0!==c&&o([c.clientId,e.clientId])}}}}),100));const n=()=>{const e=document.head||document.getElementsByTagName("head")[0],t=document.createElement("style");return t.setAttribute("id","classifai-ocr-style"),e.appendChild(t),t},o=e=>{var t;const o=null!==(t=document.getElementById("classifai-ocr-style"))&&void 0!==t?t:n(),i=`${e.map((e=>`#block-${e}:before`)).join(", ")} {\n\t\t\tcontent: "";\n\t\t\tposition: absolute;\n\t\t\tdisplay: block;\n\t\t\ttop: 0;\n\t\t\tleft: -15px;\n\t\t\tbottom: 0;\n\t\t\tborder-left: 4px solid #cfe7f3;\n\t\t\tmix-blend-mode: difference;\n\t\t\topacity: 0.25;\n\t\t}`;o.appendChild(document.createTextNode(i)),c=e},i=()=>{if(0===c.length)return;const e=document.getElementById("classifai-ocr-style");e&&(e.innerText=""),c=[]}}})(); \ No newline at end of file diff --git a/dist/gutenberg-plugin.asset.php b/dist/gutenberg-plugin.asset.php index ce06c537f..2cfd9b3f7 100644 --- a/dist/gutenberg-plugin.asset.php +++ b/dist/gutenberg-plugin.asset.php @@ -1 +1 @@ - array('react', 'wp-components', 'wp-data', 'wp-edit-post', 'wp-element', 'wp-i18n', 'wp-notices', 'wp-plugins'), 'version' => '14f14f09ab771106d147'); + array('react', 'wp-components', 'wp-data', 'wp-edit-post', 'wp-element', 'wp-i18n', 'wp-notices', 'wp-plugins'), 'version' => '537cd07d7ba20cbf9477'); diff --git a/dist/gutenberg-plugin.js b/dist/gutenberg-plugin.js index 554e8672f..9681d3da9 100644 --- a/dist/gutenberg-plugin.js +++ b/dist/gutenberg-plugin.js @@ -1,3 +1,3 @@ -(()=>{"use strict";const e=window.wp.element,t=window.React;var s;function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;t0&&void 0!==arguments[0]?arguments[0]:p,t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"SET_AUDIO_ID":return{...e,audioId:t.id};case"SET_PROCESSING_STATUS":return{...e,isProcessing:t.status}}return e},actions:{setAudioId:e=>({type:"SET_AUDIO_ID",id:e}),setIsProcessing:e=>({type:"SET_PROCESSING_STATUS",status:e})},selectors:{getAudioId:e=>e.audioId,getIsProcessing:e=>e.isProcessing}});(0,r.register)(g);const{classifaiEmbeddingData:f,classifaiPostData:y}=window,_=()=>(0,e.createElement)(l.Icon,{className:"components-panel__icon",icon:o,size:24}),m=()=>{const t=(0,r.useSelect)((e=>e("core/editor").getEditedPostAttribute("classifai_process_content"))),{editPost:s}=(0,r.useDispatch)("core/editor"),i="no"===t?"no":"yes";return(0,e.createElement)(l.ToggleControl,{label:(0,a.__)("Process content on update","classifai"),help:"yes"===i?(0,a.__)("ClassifAI language processing is enabled","classifai"):(0,a.__)("ClassifAI language processing is disabled","classifai"),checked:"yes"===i,onChange:e=>{s({classifai_process_content:e?"yes":"no"})}})},w=async e=>{const{select:t,dispatch:s}=wp.data,i=t("core/editor").getCurrentPostId(),o=t("core/editor").getCurrentPostType(),n=t("core/editor").getPostTypeLabel()||(0,a.__)("Post","classifai");if(e&&e.terms){let r=!1;const c=Object.keys(e.terms),l={};if(c.forEach((s=>{let i=s;"post_tag"===s&&(i="tags"),"category"===s&&(i="categories");const o=[...t("core/editor").getEditedPostAttribute(s)||[],...e.terms[s].map((e=>Number.parseInt(e)))].filter(((e,t,s)=>s.indexOf(e)===t));o&&o.length&&(r=!0,l[i]=o)})),r){const e=await t("core/editor").isEditedPostDirty();await s("core").editEntityRecord("postType",o,i,l),e||await s("core").saveEditedEntityRecord("postType",o,i),s("core/notices").createSuccessNotice((0,a.sprintf)(/** translators: %s is post type label. */ +(()=>{"use strict";const e=window.wp.element,t=window.React;var s;function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;t({type:"SET_AUDIO_ID",id:e}),setIsProcessing:e=>({type:"SET_PROCESSING_STATUS",status:e})},selectors:{getAudioId:e=>e.audioId,getIsProcessing:e=>e.isProcessing}});(0,r.register)(g);const{classifaiEmbeddingData:f,classifaiPostData:y}=window,_=()=>(0,e.createElement)(l.Icon,{className:"components-panel__icon",icon:o,size:24}),m=()=>{const t=(0,r.useSelect)((e=>e("core/editor").getEditedPostAttribute("classifai_process_content"))),{editPost:s}=(0,r.useDispatch)("core/editor"),i="no"===t?"no":"yes";return(0,e.createElement)(l.ToggleControl,{label:(0,a.__)("Process content on update","classifai"),help:"yes"===i?(0,a.__)("ClassifAI language processing is enabled","classifai"):(0,a.__)("ClassifAI language processing is disabled","classifai"),checked:"yes"===i,onChange:e=>{s({classifai_process_content:e?"yes":"no"})}})},w=async e=>{const{select:t,dispatch:s}=wp.data,i=t("core/editor").getCurrentPostId(),o=t("core/editor").getCurrentPostType(),n=t("core/editor").getPostTypeLabel()||(0,a.__)("Post","classifai");if(e&&e.terms){let r=!1;const c=Object.keys(e.terms),l={};if(c.forEach((s=>{let i=s;"post_tag"===s&&(i="tags"),"category"===s&&(i="categories");const o=[...t("core/editor").getEditedPostAttribute(s)||[],...e.terms[s].map((e=>Number.parseInt(e)))].filter(((e,t,s)=>s.indexOf(e)===t));o&&o.length&&(r=!0,l[i]=o)})),r){const e=await t("core/editor").isEditedPostDirty();await s("core").editEntityRecord("postType",o,i,l),e||await s("core").saveEditedEntityRecord("postType",o,i),s("core/notices").createSuccessNotice((0,a.sprintf)(/** translators: %s is post type label. */ (0,a.__)("%s classified successfully.","classifai"),n),{type:"snackbar"})}}},P=()=>{if("yes"==("no"===(0,r.useSelect)((e=>e("core/editor").getEditedPostAttribute("classifai_process_content")))?"no":"yes"))return null;const t=wp.data.select("core/editor").getCurrentPostId(),s=wp.data.select("core/editor").getPostTypeLabel()||(0,a.__)("Post","classifai"),i=(0,a.sprintf)(/** translators: %s Post type label */ -(0,a.__)("Classify %s","classifai"),s);return(0,e.createElement)(e.Fragment,null,(0,e.createElement)(l.Button,{variant:"secondary","data-id":t,onClick:e=>(e=>{let{button:t,endpoint:s,callback:i=!1,buttonText:o=(0,a.__)("Rescan","classifai")}=e;const r=t.getAttribute("data-id"),[c]=t.parentNode.getElementsByClassName("spinner"),[l]=t.parentNode.getElementsByClassName("error"),d=`${s}${r}`;t.setAttribute("disabled","disabled"),c.style.display="inline-block",c.classList.add("is-active"),l.style.display="none",wp.apiRequest({path:d}).then((e=>{t.removeAttribute("disabled"),c.style.display="none",c.classList.remove("is-active"),t.textContent=o,i&&i(e)}),(e=>{const s=n(e,"responseJSON",{code:"unknown_error",message:(0,a.__)("An unknown error occurred.","classifai")});c.style.display="none",c.classList.remove("is-active"),t.removeAttribute("disabled"),t.textContent=o,l.style.display="inline-block",l.textContent=`Error: ${s.message}`}))})({button:e.target,endpoint:"/classifai/v1/generate-tags/",callback:w,buttonText:i})},i),(0,e.createElement)("span",{className:"spinner",style:{display:"none",float:"none"}}),(0,e.createElement)("span",{className:"error",style:{display:"none",color:"#bc0b0b",padding:"5px"}}))};let h="";const b=t=>{const[s,i]=(0,e.useState)(!1),[o,n]=(0,e.useState)((new Date).getTime());let c=!1;const d="yes"===(0,r.useSelect)((e=>e("core/editor").getEditedPostAttribute("classifai_synthesize_speech"))),u=(0,r.useSelect)((e=>e("core/editor").getCurrentPostType())),p=(0,r.useSelect)((e=>e(g).getIsProcessing()));"undefined"!=typeof classifaiTextToSpeechData&&classifaiTextToSpeechData.supportedPostTypes.includes(u)&&(c=!0);const f=(0,r.useSelect)((e=>e("core/editor").getEditedPostAttribute("classifai_post_audio_id"))),y=t.audioId||f,_=(0,r.useSelect)((e=>e("core").getEntityRecords("postType","attachment",{include:[y]}))),m=_&&_.length>0&&_[0].source_url,w=(0,e.useRef)(!1);(0,e.useEffect)((()=>{const e=document.getElementById("classifai-audio-preview");e&&(s?e.play():e.pause())}),[s]),(0,e.useEffect)((()=>{p&&(w.current=!0),w.current&&!p&&n((new Date).getTime())}),[p]);const P=`${m}?ver=${o}`;let h="controls-play";return p?h="format-audio":s&&(h="controls-pause"),(0,e.createElement)(e.Fragment,null,(0,e.createElement)(l.ToggleControl,{label:(0,a.__)("Generate audio for this post.","classifai"),help:c?(0,a.__)("ClassifAI will generate audio for the post when it is published or updated.","classifai"):(0,a.__)("Text to Speech generation is disabled for this post type.","classifai"),checked:c&&d,onChange:e=>{wp.data.dispatch("core/editor").editPost({classifai_synthesize_speech:e?"yes":"no"})},disabled:!c}),m&&(0,e.createElement)("audio",{id:"classifai-audio-preview",src:P,onEnded:()=>i(!1)}),m&&d&&(0,e.createElement)(l.BaseControl,{id:"classifai-audio-controls",help:p?"":(0,a.__)("Preview the generated audio.","classifai")},(0,e.createElement)(l.Button,{id:"classifai-audio-controls__preview-btn",icon:(0,e.createElement)(l.Icon,{icon:h}),variant:"secondary",onClick:()=>i(!s),disabled:p,isBusy:p},p?(0,a.__)("Generating audio..","classifai"):(0,a.__)("Preview","classifai"))))};let E=!1;wp.data.subscribe((function(){const{select:e}=wp.data;if("yes"!==e("core/editor").getEditedPostAttribute("classifai_synthesize_speech"))return;let t=e("core/editor").isSavingPost();const s=e("core/editor").isAutosavingPost(),i=e("core/editor").getCurrentPostId();t=t&&!s,t&&!E&&(E=!0),!t&&E&&((async e=>{const{select:t,dispatch:s}=wp.data,i=`${wpApiSettings.root}classifai/v1/synthesize-speech/${e}`;if(t(g).getIsProcessing())return;s(g).setIsProcessing(!0);const o=await fetch(i,{headers:new Headers({"X-WP-Nonce":wpApiSettings.nonce})});if(200!==o.status)return s(g).setIsProcessing(!1),!1;const a=await o.json();if(a.success)return s(g).setAudioId(a.audio_id),s(g).setIsProcessing(!1),h&&(s(u.store).removeNotice(h),h=""),!0;h=a.code,s("core/notices").createErrorNotice(a.message,{id:h}),s(g).setIsProcessing(!1)})(i),E=!1)})),(0,d.registerPlugin)("classifai-plugin",{render:()=>{const t=(0,r.useSelect)((e=>e("core/editor").getCurrentPostType())),s=(0,r.useSelect)((e=>e("core/editor").getCurrentPostAttribute("status"))),i=(0,r.useSelect)((e=>e("core/editor").getEditedPostAttribute("classifai_post_audio_id"))),o=(0,r.useSelect)((e=>e(g).getAudioId()))||i,n=y&&y.NLUEnabled,l=f&&f.enabled,d=y&&y.supportedPostTypes&&y.supportedPostTypes.includes(t),u=f&&f.supportedPostTypes&&f.supportedPostTypes.includes(t),p=y&&y.supportedPostStatues&&y.supportedPostStatues.includes(s),w=f&&f.supportedPostStatues&&f.supportedPostStatues.includes(s),h=y&&!(y.noPermissions&&1===parseInt(y.noPermissions))&&n&&d&&p,E=f&&!(f.noPermissions&&1===parseInt(f.noPermissions))&&l&&u&&w;return(0,e.createElement)(c.PluginDocumentSettingPanel,{title:(0,a.__)("ClassifAI","classifai"),icon:_,className:"classifai-panel"},(0,e.createElement)(e.Fragment,null,(h||E)&&(0,e.createElement)(e.Fragment,null,(0,e.createElement)(m,null),h&&(0,e.createElement)(P,null))),(0,e.createElement)(b,{audioId:o}))}})})(); \ No newline at end of file +(0,a.__)("Classify %s","classifai"),s);return(0,e.createElement)(e.Fragment,null,(0,e.createElement)(l.Button,{variant:"secondary","data-id":t,onClick:e=>(({button:e,endpoint:t,callback:s=!1,buttonText:i=(0,a.__)("Rescan","classifai")})=>{const o=e.getAttribute("data-id"),[r]=e.parentNode.getElementsByClassName("spinner"),[c]=e.parentNode.getElementsByClassName("error"),l=`${t}${o}`;e.setAttribute("disabled","disabled"),r.style.display="inline-block",r.classList.add("is-active"),c.style.display="none",wp.apiRequest({path:l}).then((t=>{e.removeAttribute("disabled"),r.style.display="none",r.classList.remove("is-active"),e.textContent=i,s&&s(t)}),(t=>{const s=n(t,"responseJSON",{code:"unknown_error",message:(0,a.__)("An unknown error occurred.","classifai")});r.style.display="none",r.classList.remove("is-active"),e.removeAttribute("disabled"),e.textContent=i,c.style.display="inline-block",c.textContent=`Error: ${s.message}`}))})({button:e.target,endpoint:"/classifai/v1/generate-tags/",callback:w,buttonText:i})},i),(0,e.createElement)("span",{className:"spinner",style:{display:"none",float:"none"}}),(0,e.createElement)("span",{className:"error",style:{display:"none",color:"#bc0b0b",padding:"5px"}}))};let h="";const b=t=>{const[s,i]=(0,e.useState)(!1),[o,n]=(0,e.useState)((new Date).getTime());let c=!1;const d="yes"===(0,r.useSelect)((e=>e("core/editor").getEditedPostAttribute("classifai_synthesize_speech"))),u=(0,r.useSelect)((e=>e("core/editor").getCurrentPostType())),p=(0,r.useSelect)((e=>e(g).getIsProcessing()));"undefined"!=typeof classifaiTextToSpeechData&&classifaiTextToSpeechData.supportedPostTypes.includes(u)&&(c=!0);const f=(0,r.useSelect)((e=>e("core/editor").getEditedPostAttribute("classifai_post_audio_id"))),y=t.audioId||f,_=(0,r.useSelect)((e=>e("core").getEntityRecords("postType","attachment",{include:[y]}))),m=_&&_.length>0&&_[0].source_url,w=(0,e.useRef)(!1);(0,e.useEffect)((()=>{const e=document.getElementById("classifai-audio-preview");e&&(s?e.play():e.pause())}),[s]),(0,e.useEffect)((()=>{p&&(w.current=!0),w.current&&!p&&n((new Date).getTime())}),[p]);const P=`${m}?ver=${o}`;let h="controls-play";return p?h="format-audio":s&&(h="controls-pause"),(0,e.createElement)(e.Fragment,null,(0,e.createElement)(l.ToggleControl,{label:(0,a.__)("Generate audio for this post.","classifai"),help:c?(0,a.__)("ClassifAI will generate audio for the post when it is published or updated.","classifai"):(0,a.__)("Text to Speech generation is disabled for this post type.","classifai"),checked:c&&d,onChange:e=>{wp.data.dispatch("core/editor").editPost({classifai_synthesize_speech:e?"yes":"no"})},disabled:!c}),m&&(0,e.createElement)("audio",{id:"classifai-audio-preview",src:P,onEnded:()=>i(!1)}),m&&d&&(0,e.createElement)(l.BaseControl,{id:"classifai-audio-controls",help:p?"":(0,a.__)("Preview the generated audio.","classifai")},(0,e.createElement)(l.Button,{id:"classifai-audio-controls__preview-btn",icon:(0,e.createElement)(l.Icon,{icon:h}),variant:"secondary",onClick:()=>i(!s),disabled:p,isBusy:p},p?(0,a.__)("Generating audio..","classifai"):(0,a.__)("Preview","classifai"))))};let E=!1;wp.data.subscribe((function(){const{select:e}=wp.data;if("yes"!==e("core/editor").getEditedPostAttribute("classifai_synthesize_speech"))return;let t=e("core/editor").isSavingPost();const s=e("core/editor").isAutosavingPost(),i=e("core/editor").getCurrentPostId();t=t&&!s,t&&!E&&(E=!0),!t&&E&&((async e=>{const{select:t,dispatch:s}=wp.data,i=`${wpApiSettings.root}classifai/v1/synthesize-speech/${e}`;if(t(g).getIsProcessing())return;s(g).setIsProcessing(!0);const o=await fetch(i,{headers:new Headers({"X-WP-Nonce":wpApiSettings.nonce})});if(200!==o.status)return s(g).setIsProcessing(!1),!1;const a=await o.json();if(a.success)return s(g).setAudioId(a.audio_id),s(g).setIsProcessing(!1),h&&(s(u.store).removeNotice(h),h=""),!0;h=a.code,s("core/notices").createErrorNotice(a.message,{id:h}),s(g).setIsProcessing(!1)})(i),E=!1)})),(0,d.registerPlugin)("classifai-plugin",{render:()=>{const t=(0,r.useSelect)((e=>e("core/editor").getCurrentPostType())),s=(0,r.useSelect)((e=>e("core/editor").getCurrentPostAttribute("status"))),i=(0,r.useSelect)((e=>e("core/editor").getEditedPostAttribute("classifai_post_audio_id"))),o=(0,r.useSelect)((e=>e(g).getAudioId()))||i,n=y&&y.NLUEnabled,l=f&&f.enabled,d=y&&y.supportedPostTypes&&y.supportedPostTypes.includes(t),u=f&&f.supportedPostTypes&&f.supportedPostTypes.includes(t),p=y&&y.supportedPostStatues&&y.supportedPostStatues.includes(s),w=f&&f.supportedPostStatues&&f.supportedPostStatues.includes(s),h=y&&!(y.noPermissions&&1===parseInt(y.noPermissions))&&n&&d&&p,E=f&&!(f.noPermissions&&1===parseInt(f.noPermissions))&&l&&u&&w;return(0,e.createElement)(c.PluginDocumentSettingPanel,{title:(0,a.__)("ClassifAI","classifai"),icon:_,className:"classifai-panel"},(0,e.createElement)(e.Fragment,null,(h||E)&&(0,e.createElement)(e.Fragment,null,(0,e.createElement)(m,null),h&&(0,e.createElement)(P,null))),(0,e.createElement)(b,{audioId:o}))}})})(); \ No newline at end of file diff --git a/dist/language-processing.asset.php b/dist/language-processing.asset.php index dd0c8435c..ddf30f60a 100644 --- a/dist/language-processing.asset.php +++ b/dist/language-processing.asset.php @@ -1 +1 @@ - array(), 'version' => 'aba5eaf8a28a5faf337f'); + array(), 'version' => '14d95e43e9d9289dd558'); diff --git a/dist/language-processing.js b/dist/language-processing.js index c4751c4b2..ee835f580 100644 --- a/dist/language-processing.js +++ b/dist/language-processing.js @@ -1 +1 @@ -(()=>{var e={529:e=>{var t;window,t=function(){return function(){"use strict";var e={282:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.clearChoices=t.activateChoices=t.filterChoices=t.addChoice=void 0;var n=i(883);t.addChoice=function(e){var t=e.value,i=e.label,s=e.id,r=e.groupId,o=e.disabled,a=e.elementId,c=e.customProperties,l=e.placeholder,h=e.keyCode;return{type:n.ACTION_TYPES.ADD_CHOICE,value:t,label:i,id:s,groupId:r,disabled:o,elementId:a,customProperties:c,placeholder:l,keyCode:h}},t.filterChoices=function(e){return{type:n.ACTION_TYPES.FILTER_CHOICES,results:e}},t.activateChoices=function(e){return void 0===e&&(e=!0),{type:n.ACTION_TYPES.ACTIVATE_CHOICES,active:e}},t.clearChoices=function(){return{type:n.ACTION_TYPES.CLEAR_CHOICES}}},783:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.addGroup=void 0;var n=i(883);t.addGroup=function(e){var t=e.value,i=e.id,s=e.active,r=e.disabled;return{type:n.ACTION_TYPES.ADD_GROUP,value:t,id:i,active:s,disabled:r}}},464:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.highlightItem=t.removeItem=t.addItem=void 0;var n=i(883);t.addItem=function(e){var t=e.value,i=e.label,s=e.id,r=e.choiceId,o=e.groupId,a=e.customProperties,c=e.placeholder,l=e.keyCode;return{type:n.ACTION_TYPES.ADD_ITEM,value:t,label:i,id:s,choiceId:r,groupId:o,customProperties:a,placeholder:c,keyCode:l}},t.removeItem=function(e,t){return{type:n.ACTION_TYPES.REMOVE_ITEM,id:e,choiceId:t}},t.highlightItem=function(e,t){return{type:n.ACTION_TYPES.HIGHLIGHT_ITEM,id:e,highlighted:t}}},137:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.setIsLoading=t.resetTo=t.clearAll=void 0;var n=i(883);t.clearAll=function(){return{type:n.ACTION_TYPES.CLEAR_ALL}},t.resetTo=function(e){return{type:n.ACTION_TYPES.RESET_TO,state:e}},t.setIsLoading=function(e){return{type:n.ACTION_TYPES.SET_IS_LOADING,isLoading:e}}},373:function(e,t,i){var n=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,s=0,r=t.length;s=0?this._store.getGroupById(s):null;return this._store.dispatch((0,l.highlightItem)(i,!0)),t&&this.passedElement.triggerEvent(d.EVENTS.highlightItem,{id:i,value:o,label:c,groupValue:h&&h.value?h.value:null}),this},e.prototype.unhighlightItem=function(e){if(!e||!e.id)return this;var t=e.id,i=e.groupId,n=void 0===i?-1:i,s=e.value,r=void 0===s?"":s,o=e.label,a=void 0===o?"":o,c=n>=0?this._store.getGroupById(n):null;return this._store.dispatch((0,l.highlightItem)(t,!1)),this.passedElement.triggerEvent(d.EVENTS.highlightItem,{id:t,value:r,label:a,groupValue:c&&c.value?c.value:null}),this},e.prototype.highlightAll=function(){var e=this;return this._store.items.forEach((function(t){return e.highlightItem(t)})),this},e.prototype.unhighlightAll=function(){var e=this;return this._store.items.forEach((function(t){return e.unhighlightItem(t)})),this},e.prototype.removeActiveItemsByValue=function(e){var t=this;return this._store.activeItems.filter((function(t){return t.value===e})).forEach((function(e){return t._removeItem(e)})),this},e.prototype.removeActiveItems=function(e){var t=this;return this._store.activeItems.filter((function(t){return t.id!==e})).forEach((function(e){return t._removeItem(e)})),this},e.prototype.removeHighlightedItems=function(e){var t=this;return void 0===e&&(e=!1),this._store.highlightedActiveItems.forEach((function(i){t._removeItem(i),e&&t._triggerChange(i.value)})),this},e.prototype.showDropdown=function(e){var t=this;return this.dropdown.isActive||requestAnimationFrame((function(){t.dropdown.show(),t.containerOuter.open(t.dropdown.distanceFromTopWindow),!e&&t._canSearch&&t.input.focus(),t.passedElement.triggerEvent(d.EVENTS.showDropdown,{})})),this},e.prototype.hideDropdown=function(e){var t=this;return this.dropdown.isActive?(requestAnimationFrame((function(){t.dropdown.hide(),t.containerOuter.close(),!e&&t._canSearch&&(t.input.removeActiveDescendant(),t.input.blur()),t.passedElement.triggerEvent(d.EVENTS.hideDropdown,{})})),this):this},e.prototype.getValue=function(e){void 0===e&&(e=!1);var t=this._store.activeItems.reduce((function(t,i){var n=e?i.value:i;return t.push(n),t}),[]);return this._isSelectOneElement?t[0]:t},e.prototype.setValue=function(e){var t=this;return this.initialised?(e.forEach((function(e){return t._setChoiceOrItem(e)})),this):this},e.prototype.setChoiceByValue=function(e){var t=this;return!this.initialised||this._isTextElement||(Array.isArray(e)?e:[e]).forEach((function(e){return t._findAndSelectChoiceByValue(e)})),this},e.prototype.setChoices=function(e,t,i,n){var s=this;if(void 0===e&&(e=[]),void 0===t&&(t="value"),void 0===i&&(i="label"),void 0===n&&(n=!1),!this.initialised)throw new ReferenceError("setChoices was called on a non-initialized instance of Choices");if(!this._isSelectElement)throw new TypeError("setChoices can't be used with INPUT based Choices");if("string"!=typeof t||!t)throw new TypeError("value parameter must be a name of 'value' field in passed objects");if(n&&this.clearChoices(),"function"==typeof e){var r=e(this);if("function"==typeof Promise&&r instanceof Promise)return new Promise((function(e){return requestAnimationFrame(e)})).then((function(){return s._handleLoadingState(!0)})).then((function(){return r})).then((function(e){return s.setChoices(e,t,i,n)})).catch((function(e){s.config.silent||console.error(e)})).then((function(){return s._handleLoadingState(!1)})).then((function(){return s}));if(!Array.isArray(r))throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: ".concat(typeof r));return this.setChoices(r,t,i,!1)}if(!Array.isArray(e))throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices");return this.containerOuter.removeLoadingState(),this._startLoading(),e.forEach((function(e){if(e.choices)s._addGroup({id:e.id?parseInt("".concat(e.id),10):null,group:e,valueKey:t,labelKey:i});else{var n=e;s._addChoice({value:n[t],label:n[i],isSelected:!!n.selected,isDisabled:!!n.disabled,placeholder:!!n.placeholder,customProperties:n.customProperties})}})),this._stopLoading(),this},e.prototype.clearChoices=function(){return this._store.dispatch((0,a.clearChoices)()),this},e.prototype.clearStore=function(){return this._store.dispatch((0,h.clearAll)()),this},e.prototype.clearInput=function(){var e=!this._isSelectOneElement;return this.input.clear(e),!this._isTextElement&&this._canSearch&&(this._isSearching=!1,this._store.dispatch((0,a.activateChoices)(!0))),this},e.prototype._render=function(){if(!this._store.isLoading()){this._currentState=this._store.state;var e=this._currentState.choices!==this._prevState.choices||this._currentState.groups!==this._prevState.groups||this._currentState.items!==this._prevState.items,t=this._isSelectElement,i=this._currentState.items!==this._prevState.items;e&&(t&&this._renderChoices(),i&&this._renderItems(),this._prevState=this._currentState)}},e.prototype._renderChoices=function(){var e=this,t=this._store,i=t.activeGroups,n=t.activeChoices,s=document.createDocumentFragment();if(this.choiceList.clear(),this.config.resetScrollPosition&&requestAnimationFrame((function(){return e.choiceList.scrollToTop()})),i.length>=1&&!this._isSearching){var r=n.filter((function(e){return!0===e.placeholder&&-1===e.groupId}));r.length>=1&&(s=this._createChoicesFragment(r,s)),s=this._createGroupsFragment(i,n,s)}else n.length>=1&&(s=this._createChoicesFragment(n,s));if(s.childNodes&&s.childNodes.length>0){var o=this._store.activeItems,a=this._canAddItem(o,this.input.value);if(a.response)this.choiceList.append(s),this._highlightChoice();else{var c=this._getTemplate("notice",a.notice);this.choiceList.append(c)}}else{var l=void 0;c=void 0,this._isSearching?(c="function"==typeof this.config.noResultsText?this.config.noResultsText():this.config.noResultsText,l=this._getTemplate("notice",c,"no-results")):(c="function"==typeof this.config.noChoicesText?this.config.noChoicesText():this.config.noChoicesText,l=this._getTemplate("notice",c,"no-choices")),this.choiceList.append(l)}},e.prototype._renderItems=function(){var e=this._store.activeItems||[];this.itemList.clear();var t=this._createItemsFragment(e);t.childNodes&&this.itemList.append(t)},e.prototype._createGroupsFragment=function(e,t,i){var n=this;return void 0===i&&(i=document.createDocumentFragment()),this.config.shouldSort&&e.sort(this.config.sorter),e.forEach((function(e){var s=function(e){return t.filter((function(t){return n._isSelectOneElement?t.groupId===e.id:t.groupId===e.id&&("always"===n.config.renderSelectedChoices||!t.selected)}))}(e);if(s.length>=1){var r=n._getTemplate("choiceGroup",e);i.appendChild(r),n._createChoicesFragment(s,i,!0)}})),i},e.prototype._createChoicesFragment=function(e,t,i){var s=this;void 0===t&&(t=document.createDocumentFragment()),void 0===i&&(i=!1);var r=this.config,o=r.renderSelectedChoices,a=r.searchResultLimit,c=r.renderChoiceLimit,l=this._isSearching?f.sortByScore:this.config.sorter,h=function(e){if("auto"!==o||s._isSelectOneElement||!e.selected){var i=s._getTemplate("choice",e,s.config.itemSelectText);t.appendChild(i)}},u=e;"auto"!==o||this._isSelectOneElement||(u=e.filter((function(e){return!e.selected})));var d=u.reduce((function(e,t){return t.placeholder?e.placeholderChoices.push(t):e.normalChoices.push(t),e}),{placeholderChoices:[],normalChoices:[]}),p=d.placeholderChoices,m=d.normalChoices;(this.config.shouldSort||this._isSearching)&&m.sort(l);var g=u.length,v=this._isSelectOneElement?n(n([],p,!0),m,!0):m;this._isSearching?g=a:c&&c>0&&!i&&(g=c);for(var _=0;_=n){var o=s?this._searchChoices(e):0;this.passedElement.triggerEvent(d.EVENTS.search,{value:e,resultCount:o})}else r&&(this._isSearching=!1,this._store.dispatch((0,a.activateChoices)(!0)))}},e.prototype._canAddItem=function(e,t){var i=!0,n="function"==typeof this.config.addItemText?this.config.addItemText(t):this.config.addItemText;if(!this._isSelectOneElement){var s=(0,f.existsInArray)(e,t);this.config.maxItemCount>0&&this.config.maxItemCount<=e.length&&(i=!1,n="function"==typeof this.config.maxItemText?this.config.maxItemText(this.config.maxItemCount):this.config.maxItemText),!this.config.duplicateItemsAllowed&&s&&i&&(i=!1,n="function"==typeof this.config.uniqueItemText?this.config.uniqueItemText(t):this.config.uniqueItemText),this._isTextElement&&this.config.addItems&&i&&"function"==typeof this.config.addItemFilter&&!this.config.addItemFilter(t)&&(i=!1,n="function"==typeof this.config.customAddItemText?this.config.customAddItemText(t):this.config.customAddItemText)}return{response:i,notice:n}},e.prototype._searchChoices=function(e){var t="string"==typeof e?e.trim():e,i="string"==typeof this._currentValue?this._currentValue.trim():this._currentValue;if(t.length<1&&t==="".concat(i," "))return 0;var s=this._store.searchableChoices,r=t,c=Object.assign(this.config.fuseOptions,{keys:n([],this.config.searchFields,!0),includeMatches:!0}),l=new o.default(s,c).search(r);return this._currentValue=t,this._highlightPosition=0,this._isSearching=!0,this._store.dispatch((0,a.filterChoices)(l)),l.length},e.prototype._addEventListeners=function(){var e=document.documentElement;e.addEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.addEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.addEventListener("mousedown",this._onMouseDown,!0),e.addEventListener("click",this._onClick,{passive:!0}),e.addEventListener("touchmove",this._onTouchMove,{passive:!0}),this.dropdown.element.addEventListener("mouseover",this._onMouseOver,{passive:!0}),this._isSelectOneElement&&(this.containerOuter.element.addEventListener("focus",this._onFocus,{passive:!0}),this.containerOuter.element.addEventListener("blur",this._onBlur,{passive:!0})),this.input.element.addEventListener("keyup",this._onKeyUp,{passive:!0}),this.input.element.addEventListener("focus",this._onFocus,{passive:!0}),this.input.element.addEventListener("blur",this._onBlur,{passive:!0}),this.input.element.form&&this.input.element.form.addEventListener("reset",this._onFormReset,{passive:!0}),this.input.addEventListeners()},e.prototype._removeEventListeners=function(){var e=document.documentElement;e.removeEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.removeEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.removeEventListener("mousedown",this._onMouseDown,!0),e.removeEventListener("click",this._onClick),e.removeEventListener("touchmove",this._onTouchMove),this.dropdown.element.removeEventListener("mouseover",this._onMouseOver),this._isSelectOneElement&&(this.containerOuter.element.removeEventListener("focus",this._onFocus),this.containerOuter.element.removeEventListener("blur",this._onBlur)),this.input.element.removeEventListener("keyup",this._onKeyUp),this.input.element.removeEventListener("focus",this._onFocus),this.input.element.removeEventListener("blur",this._onBlur),this.input.element.form&&this.input.element.form.removeEventListener("reset",this._onFormReset),this.input.removeEventListeners()},e.prototype._onKeyDown=function(e){var t=e.keyCode,i=this._store.activeItems,n=this.input.isFocussed,s=this.dropdown.isActive,r=this.itemList.hasChildren(),o=String.fromCharCode(t),a=/[^\x00-\x1F]/.test(o),c=d.KEY_CODES.BACK_KEY,l=d.KEY_CODES.DELETE_KEY,h=d.KEY_CODES.ENTER_KEY,u=d.KEY_CODES.A_KEY,p=d.KEY_CODES.ESC_KEY,f=d.KEY_CODES.UP_KEY,m=d.KEY_CODES.DOWN_KEY,g=d.KEY_CODES.PAGE_UP_KEY,v=d.KEY_CODES.PAGE_DOWN_KEY;switch(this._isTextElement||s||!a||(this.showDropdown(),this.input.isFocussed||(this.input.value+=e.key.toLowerCase())),t){case u:return this._onSelectKey(e,r);case h:return this._onEnterKey(e,i,s);case p:return this._onEscapeKey(s);case f:case g:case m:case v:return this._onDirectionKey(e,s);case l:case c:return this._onDeleteKey(e,i,n)}},e.prototype._onKeyUp=function(e){var t=e.target,i=e.keyCode,n=this.input.value,s=this._store.activeItems,r=this._canAddItem(s,n),o=d.KEY_CODES.BACK_KEY,c=d.KEY_CODES.DELETE_KEY;if(this._isTextElement)if(r.notice&&n){var l=this._getTemplate("notice",r.notice);this.dropdown.element.innerHTML=l.outerHTML,this.showDropdown(!0)}else this.hideDropdown(!0);else{var h=(i===o||i===c)&&t&&!t.value,u=!this._isTextElement&&this._isSearching,p=this._canSearch&&r.response;h&&u?(this._isSearching=!1,this._store.dispatch((0,a.activateChoices)(!0))):p&&this._handleSearch(this.input.rawValue)}this._canSearch=this.config.searchEnabled},e.prototype._onSelectKey=function(e,t){var i=e.ctrlKey,n=e.metaKey;(i||n)&&t&&(this._canSearch=!1,this.config.removeItems&&!this.input.value&&this.input.element===document.activeElement&&this.highlightAll())},e.prototype._onEnterKey=function(e,t,i){var n=e.target,s=d.KEY_CODES.ENTER_KEY,r=n&&n.hasAttribute("data-button");if(this._isTextElement&&n&&n.value){var o=this.input.value;this._canAddItem(t,o).response&&(this.hideDropdown(!0),this._addItem({value:o}),this._triggerChange(o),this.clearInput())}if(r&&(this._handleButtonAction(t,n),e.preventDefault()),i){var a=this.dropdown.getChild(".".concat(this.config.classNames.highlightedState));a&&(t[0]&&(t[0].keyCode=s),this._handleChoiceAction(t,a)),e.preventDefault()}else this._isSelectOneElement&&(this.showDropdown(),e.preventDefault())},e.prototype._onEscapeKey=function(e){e&&(this.hideDropdown(!0),this.containerOuter.focus())},e.prototype._onDirectionKey=function(e,t){var i=e.keyCode,n=e.metaKey,s=d.KEY_CODES.DOWN_KEY,r=d.KEY_CODES.PAGE_UP_KEY,o=d.KEY_CODES.PAGE_DOWN_KEY;if(t||this._isSelectOneElement){this.showDropdown(),this._canSearch=!1;var a=i===s||i===o?1:-1,c="[data-choice-selectable]",l=void 0;if(n||i===o||i===r)l=a>0?this.dropdown.element.querySelector("".concat(c,":last-of-type")):this.dropdown.element.querySelector(c);else{var h=this.dropdown.element.querySelector(".".concat(this.config.classNames.highlightedState));l=h?(0,f.getAdjacentEl)(h,c,a):this.dropdown.element.querySelector(c)}l&&((0,f.isScrolledIntoView)(l,this.choiceList.element,a)||this.choiceList.scrollToChildElement(l,a),this._highlightChoice(l)),e.preventDefault()}},e.prototype._onDeleteKey=function(e,t,i){var n=e.target;this._isSelectOneElement||n.value||!i||(this._handleBackspace(t),e.preventDefault())},e.prototype._onTouchMove=function(){this._wasTap&&(this._wasTap=!1)},e.prototype._onTouchEnd=function(e){var t=(e||e.touches[0]).target;this._wasTap&&this.containerOuter.element.contains(t)&&((t===this.containerOuter.element||t===this.containerInner.element)&&(this._isTextElement?this.input.focus():this._isSelectMultipleElement&&this.showDropdown()),e.stopPropagation()),this._wasTap=!0},e.prototype._onMouseDown=function(e){var t=e.target;if(t instanceof HTMLElement){if(_&&this.choiceList.element.contains(t)){var i=this.choiceList.element.firstElementChild,n="ltr"===this._direction?e.offsetX>=i.offsetWidth:e.offsetX0&&this.unhighlightAll(),this.containerOuter.removeFocusState(),this.hideDropdown(!0))},e.prototype._onFocus=function(e){var t,i=this,n=e.target;n&&this.containerOuter.element.contains(n)&&((t={})[d.TEXT_TYPE]=function(){n===i.input.element&&i.containerOuter.addFocusState()},t[d.SELECT_ONE_TYPE]=function(){i.containerOuter.addFocusState(),n===i.input.element&&i.showDropdown(!0)},t[d.SELECT_MULTIPLE_TYPE]=function(){n===i.input.element&&(i.showDropdown(!0),i.containerOuter.addFocusState())},t)[this.passedElement.element.type]()},e.prototype._onBlur=function(e){var t,i=this,n=e.target;if(n&&this.containerOuter.element.contains(n)&&!this._isScrollingOnIe){var s=this._store.activeItems.some((function(e){return e.highlighted}));((t={})[d.TEXT_TYPE]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),s&&i.unhighlightAll(),i.hideDropdown(!0))},t[d.SELECT_ONE_TYPE]=function(){i.containerOuter.removeFocusState(),(n===i.input.element||n===i.containerOuter.element&&!i._canSearch)&&i.hideDropdown(!0)},t[d.SELECT_MULTIPLE_TYPE]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),i.hideDropdown(!0),s&&i.unhighlightAll())},t)[this.passedElement.element.type]()}else this._isScrollingOnIe=!1,this.input.element.focus()},e.prototype._onFormReset=function(){this._store.dispatch((0,h.resetTo)(this._initialState))},e.prototype._highlightChoice=function(e){var t=this;void 0===e&&(e=null);var i=Array.from(this.dropdown.element.querySelectorAll("[data-choice-selectable]"));if(i.length){var n=e;Array.from(this.dropdown.element.querySelectorAll(".".concat(this.config.classNames.highlightedState))).forEach((function(e){e.classList.remove(t.config.classNames.highlightedState),e.setAttribute("aria-selected","false")})),n?this._highlightPosition=i.indexOf(n):(n=i.length>this._highlightPosition?i[this._highlightPosition]:i[i.length-1])||(n=i[0]),n.classList.add(this.config.classNames.highlightedState),n.setAttribute("aria-selected","true"),this.passedElement.triggerEvent(d.EVENTS.highlightChoice,{el:n}),this.dropdown.isActive&&(this.input.setActiveDescendant(n.id),this.containerOuter.setActiveDescendant(n.id))}},e.prototype._addItem=function(e){var t=e.value,i=e.label,n=void 0===i?null:i,s=e.choiceId,r=void 0===s?-1:s,o=e.groupId,a=void 0===o?-1:o,c=e.customProperties,h=void 0===c?{}:c,u=e.placeholder,p=void 0!==u&&u,f=e.keyCode,m=void 0===f?-1:f,g="string"==typeof t?t.trim():t,v=this._store.items,_=n||g,y=r||-1,E=a>=0?this._store.getGroupById(a):null,b=v?v.length+1:1;this.config.prependValue&&(g=this.config.prependValue+g.toString()),this.config.appendValue&&(g+=this.config.appendValue.toString()),this._store.dispatch((0,l.addItem)({value:g,label:_,id:b,choiceId:y,groupId:a,customProperties:h,placeholder:p,keyCode:m})),this._isSelectOneElement&&this.removeActiveItems(b),this.passedElement.triggerEvent(d.EVENTS.addItem,{id:b,value:g,label:_,customProperties:h,groupValue:E&&E.value?E.value:null,keyCode:m})},e.prototype._removeItem=function(e){var t=e.id,i=e.value,n=e.label,s=e.customProperties,r=e.choiceId,o=e.groupId,a=o&&o>=0?this._store.getGroupById(o):null;t&&r&&(this._store.dispatch((0,l.removeItem)(t,r)),this.passedElement.triggerEvent(d.EVENTS.removeItem,{id:t,value:i,label:n,customProperties:s,groupValue:a&&a.value?a.value:null}))},e.prototype._addChoice=function(e){var t=e.value,i=e.label,n=void 0===i?null:i,s=e.isSelected,r=void 0!==s&&s,o=e.isDisabled,c=void 0!==o&&o,l=e.groupId,h=void 0===l?-1:l,u=e.customProperties,d=void 0===u?{}:u,p=e.placeholder,f=void 0!==p&&p,m=e.keyCode,g=void 0===m?-1:m;if(null!=t){var v=this._store.choices,_=n||t,y=v?v.length+1:1,E="".concat(this._baseId,"-").concat(this._idNames.itemChoice,"-").concat(y);this._store.dispatch((0,a.addChoice)({id:y,groupId:h,elementId:E,value:t,label:_,disabled:c,customProperties:d,placeholder:f,keyCode:g})),r&&this._addItem({value:t,label:_,choiceId:y,customProperties:d,placeholder:f,keyCode:g})}},e.prototype._addGroup=function(e){var t=this,i=e.group,n=e.id,s=e.valueKey,r=void 0===s?"value":s,o=e.labelKey,a=void 0===o?"label":o,l=(0,f.isType)("Object",i)?i.choices:Array.from(i.getElementsByTagName("OPTION")),h=n||Math.floor((new Date).valueOf()*Math.random()),u=!!i.disabled&&i.disabled;l?(this._store.dispatch((0,c.addGroup)({value:i.label,id:h,active:!0,disabled:u})),l.forEach((function(e){var i=e.disabled||e.parentNode&&e.parentNode.disabled;t._addChoice({value:e[r],label:(0,f.isType)("Object",e)?e[a]:e.innerHTML,isSelected:e.selected,isDisabled:i,groupId:h,customProperties:e.customProperties,placeholder:e.placeholder})}))):this._store.dispatch((0,c.addGroup)({value:i.label,id:i.id,active:!1,disabled:i.disabled}))},e.prototype._getTemplate=function(e){for(var t,i=[],s=1;s0?this.element.scrollTop+o-s:e.offsetTop;requestAnimationFrame((function(){i._animateScroll(a,t)}))}},e.prototype._scrollDown=function(e,t,i){var n=(i-e)/t,s=n>1?n:1;this.element.scrollTop=e+s},e.prototype._scrollUp=function(e,t,i){var n=(e-i)/t,s=n>1?n:1;this.element.scrollTop=e-s},e.prototype._animateScroll=function(e,t){var i=this,s=n.SCROLLING_SPEED,r=this.element.scrollTop,o=!1;t>0?(this._scrollDown(r,s,e),re&&(o=!0)),o&&requestAnimationFrame((function(){i._animateScroll(e,t)}))},e}();t.default=s},730:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0});var n=i(799),s=function(){function e(e){var t=e.element,i=e.classNames;if(this.element=t,this.classNames=i,!(t instanceof HTMLInputElement||t instanceof HTMLSelectElement))throw new TypeError("Invalid element passed");this.isDisabled=!1}return Object.defineProperty(e.prototype,"isActive",{get:function(){return"active"===this.element.dataset.choice},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dir",{get:function(){return this.element.dir},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.element.value},set:function(e){this.element.value=e},enumerable:!1,configurable:!0}),e.prototype.conceal=function(){this.element.classList.add(this.classNames.input),this.element.hidden=!0,this.element.tabIndex=-1;var e=this.element.getAttribute("style");e&&this.element.setAttribute("data-choice-orig-style",e),this.element.setAttribute("data-choice","active")},e.prototype.reveal=function(){this.element.classList.remove(this.classNames.input),this.element.hidden=!1,this.element.removeAttribute("tabindex");var e=this.element.getAttribute("data-choice-orig-style");e?(this.element.removeAttribute("data-choice-orig-style"),this.element.setAttribute("style",e)):this.element.removeAttribute("style"),this.element.removeAttribute("data-choice"),this.element.value=this.element.value},e.prototype.enable=function(){this.element.removeAttribute("disabled"),this.element.disabled=!1,this.isDisabled=!1},e.prototype.disable=function(){this.element.setAttribute("disabled",""),this.element.disabled=!0,this.isDisabled=!0},e.prototype.triggerEvent=function(e,t){(0,n.dispatchEvent)(this.element,e,t)},e}();t.default=s},541:function(e,t,i){var n,s=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function __(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(__.prototype=t.prototype,new __)}),r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var o=function(e){function t(t){var i=t.element,n=t.classNames,s=t.delimiter,r=e.call(this,{element:i,classNames:n})||this;return r.delimiter=s,r}return s(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.element.value},set:function(e){this.element.setAttribute("value",e),this.element.value=e},enumerable:!1,configurable:!0}),t}(r(i(730)).default);t.default=o},982:function(e,t,i){var n,s=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function __(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(__.prototype=t.prototype,new __)}),r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var o=function(e){function t(t){var i=t.element,n=t.classNames,s=t.template,r=e.call(this,{element:i,classNames:n})||this;return r.template=s,r}return s(t,e),Object.defineProperty(t.prototype,"placeholderOption",{get:function(){return this.element.querySelector('option[value=""]')||this.element.querySelector("option[placeholder]")},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"optionGroups",{get:function(){return Array.from(this.element.getElementsByTagName("OPTGROUP"))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"options",{get:function(){return Array.from(this.element.options)},set:function(e){var t=this,i=document.createDocumentFragment();e.forEach((function(e){return n=e,s=t.template(n),void i.appendChild(s);var n,s})),this.appendDocFragment(i)},enumerable:!1,configurable:!0}),t.prototype.appendDocFragment=function(e){this.element.innerHTML="",this.element.appendChild(e)},t}(r(i(730)).default);t.default=o},883:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.SCROLLING_SPEED=t.SELECT_MULTIPLE_TYPE=t.SELECT_ONE_TYPE=t.TEXT_TYPE=t.KEY_CODES=t.ACTION_TYPES=t.EVENTS=void 0,t.EVENTS={showDropdown:"showDropdown",hideDropdown:"hideDropdown",change:"change",choice:"choice",search:"search",addItem:"addItem",removeItem:"removeItem",highlightItem:"highlightItem",highlightChoice:"highlightChoice",unhighlightItem:"unhighlightItem"},t.ACTION_TYPES={ADD_CHOICE:"ADD_CHOICE",FILTER_CHOICES:"FILTER_CHOICES",ACTIVATE_CHOICES:"ACTIVATE_CHOICES",CLEAR_CHOICES:"CLEAR_CHOICES",ADD_GROUP:"ADD_GROUP",ADD_ITEM:"ADD_ITEM",REMOVE_ITEM:"REMOVE_ITEM",HIGHLIGHT_ITEM:"HIGHLIGHT_ITEM",CLEAR_ALL:"CLEAR_ALL",RESET_TO:"RESET_TO",SET_IS_LOADING:"SET_IS_LOADING"},t.KEY_CODES={BACK_KEY:46,DELETE_KEY:8,ENTER_KEY:13,A_KEY:65,ESC_KEY:27,UP_KEY:38,DOWN_KEY:40,PAGE_UP_KEY:33,PAGE_DOWN_KEY:34},t.TEXT_TYPE="text",t.SELECT_ONE_TYPE="select-one",t.SELECT_MULTIPLE_TYPE="select-multiple",t.SCROLLING_SPEED=4},789:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_CONFIG=t.DEFAULT_CLASSNAMES=void 0;var n=i(799);t.DEFAULT_CLASSNAMES={containerOuter:"choices",containerInner:"choices__inner",input:"choices__input",inputCloned:"choices__input--cloned",list:"choices__list",listItems:"choices__list--multiple",listSingle:"choices__list--single",listDropdown:"choices__list--dropdown",item:"choices__item",itemSelectable:"choices__item--selectable",itemDisabled:"choices__item--disabled",itemChoice:"choices__item--choice",placeholder:"choices__placeholder",group:"choices__group",groupHeading:"choices__heading",button:"choices__button",activeState:"is-active",focusState:"is-focused",openState:"is-open",disabledState:"is-disabled",highlightedState:"is-highlighted",selectedState:"is-selected",flippedState:"is-flipped",loadingState:"is-loading",noResults:"has-no-results",noChoices:"has-no-choices"},t.DEFAULT_CONFIG={items:[],choices:[],silent:!1,renderChoiceLimit:-1,maxItemCount:-1,addItems:!0,addItemFilter:null,removeItems:!0,removeItemButton:!1,editItems:!1,allowHTML:!0,duplicateItemsAllowed:!0,delimiter:",",paste:!0,searchEnabled:!0,searchChoices:!0,searchFloor:1,searchResultLimit:4,searchFields:["label","value"],position:"auto",resetScrollPosition:!0,shouldSort:!0,shouldSortItems:!1,sorter:n.sortByAlpha,placeholder:!0,placeholderValue:null,searchPlaceholderValue:null,prependValue:null,appendValue:null,renderSelectedChoices:"auto",loadingText:"Loading...",noResultsText:"No results found",noChoicesText:"No choices to choose from",itemSelectText:"Press to select",uniqueItemText:"Only unique values can be added",customAddItemText:"Only values matching specific conditions can be added",addItemText:function(e){return'Press Enter to add "'.concat((0,n.sanitise)(e),'"')},maxItemText:function(e){return"Only ".concat(e," values can be added")},valueComparer:function(e,t){return e===t},fuseOptions:{includeScore:!0},labelId:"",callbackOnInit:null,callbackOnCreateTemplates:null,classNames:t.DEFAULT_CLASSNAMES}},18:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},978:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},948:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},359:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},285:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},533:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},187:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,s)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),s=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0}),s(i(18),t),s(i(978),t),s(i(948),t),s(i(359),t),s(i(285),t),s(i(533),t),s(i(287),t),s(i(132),t),s(i(837),t),s(i(598),t),s(i(369),t),s(i(37),t),s(i(47),t),s(i(923),t),s(i(876),t)},287:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},132:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},837:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},598:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},37:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},369:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},47:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},923:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},876:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},799:function(e,t){var i;Object.defineProperty(t,"__esModule",{value:!0}),t.parseCustomProperties=t.diff=t.cloneObject=t.existsInArray=t.dispatchEvent=t.sortByScore=t.sortByAlpha=t.strToEl=t.sanitise=t.isScrolledIntoView=t.getAdjacentEl=t.wrap=t.isType=t.getType=t.generateId=t.generateChars=t.getRandomNumber=void 0,t.getRandomNumber=function(e,t){return Math.floor(Math.random()*(t-e)+e)},t.generateChars=function(e){return Array.from({length:e},(function(){return(0,t.getRandomNumber)(0,36).toString(36)})).join("")},t.generateId=function(e,i){var n=e.id||e.name&&"".concat(e.name,"-").concat((0,t.generateChars)(2))||(0,t.generateChars)(4);return n=n.replace(/(:|\.|\[|\]|,)/g,""),"".concat(i,"-").concat(n)},t.getType=function(e){return Object.prototype.toString.call(e).slice(8,-1)},t.isType=function(e,i){return null!=i&&(0,t.getType)(i)===e},t.wrap=function(e,t){return void 0===t&&(t=document.createElement("div")),e.parentNode&&(e.nextSibling?e.parentNode.insertBefore(t,e.nextSibling):e.parentNode.appendChild(t)),t.appendChild(e)},t.getAdjacentEl=function(e,t,i){void 0===i&&(i=1);for(var n="".concat(i>0?"next":"previous","ElementSibling"),s=e[n];s;){if(s.matches(t))return s;s=s[n]}return s},t.isScrolledIntoView=function(e,t,i){return void 0===i&&(i=1),!!e&&(i>0?t.scrollTop+t.offsetHeight>=e.offsetTop+e.offsetHeight:e.offsetTop>=t.scrollTop)},t.sanitise=function(e){return"string"!=typeof e?e:e.replace(/&/g,"&").replace(/>/g,">").replace(/-1?e.map((function(e){var t=e;return t.id===parseInt("".concat(o.choiceId),10)&&(t.selected=!0),t})):e;case"REMOVE_ITEM":var a=n;return a.choiceId&&a.choiceId>-1?e.map((function(e){var t=e;return t.id===parseInt("".concat(a.choiceId),10)&&(t.selected=!1),t})):e;case"FILTER_CHOICES":var c=n;return e.map((function(e){var t=e;return t.active=c.results.some((function(e){var i=e.item,n=e.score;return i.id===t.id&&(t.score=n,!0)})),t}));case"ACTIVATE_CHOICES":var l=n;return e.map((function(e){var t=e;return t.active=l.active,t}));case"CLEAR_CHOICES":return t.defaultState;default:return e}}},871:function(e,t){var i=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,s=0,r=t.length;s0?"treeitem":"option"),Object.assign(E.dataset,{choice:"",id:d,value:p,selectText:i}),v?(E.classList.add(h),E.dataset.choiceDisabled="",E.setAttribute("aria-disabled","true")):(E.classList.add(c),E.dataset.choiceSelectable=""),E},input:function(e,t){var i=e.classNames,n=i.input,s=i.inputCloned,r=Object.assign(document.createElement("input"),{type:"search",name:"search_terms",className:"".concat(n," ").concat(s),autocomplete:"off",autocapitalize:"off",spellcheck:!1});return r.setAttribute("role","textbox"),r.setAttribute("aria-autocomplete","list"),r.setAttribute("aria-label",t),r},dropdown:function(e){var t=e.classNames,i=t.list,n=t.listDropdown,s=document.createElement("div");return s.classList.add(i,n),s.setAttribute("aria-expanded","false"),s},notice:function(e,t,i){var n,s=e.allowHTML,r=e.classNames,o=r.item,a=r.itemChoice,c=r.noResults,l=r.noChoices;void 0===i&&(i="");var h=[o,a];return"no-choices"===i?h.push(l):"no-results"===i&&h.push(c),Object.assign(document.createElement("div"),((n={})[s?"innerHTML":"innerText"]=t,n.className=h.join(" "),n))},option:function(e){var t=e.label,i=e.value,n=e.customProperties,s=e.active,r=e.disabled,o=new Option(t,i,!1,s);return n&&(o.dataset.customProperties="".concat(n)),o.disabled=!!r,o}};t.default=i},996:function(e){var t=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||function(e){return e.$$typeof===i}(e)}(e)},i="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function n(e,t){return!1!==t.clone&&t.isMergeableObject(e)?a((i=e,Array.isArray(i)?[]:{}),e,t):e;var i}function s(e,t,i){return e.concat(t).map((function(e){return n(e,i)}))}function r(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter((function(t){return e.propertyIsEnumerable(t)})):[]}(e))}function o(e,t){try{return t in e}catch(e){return!1}}function a(e,i,c){(c=c||{}).arrayMerge=c.arrayMerge||s,c.isMergeableObject=c.isMergeableObject||t,c.cloneUnlessOtherwiseSpecified=n;var l=Array.isArray(i);return l===Array.isArray(e)?l?c.arrayMerge(e,i,c):function(e,t,i){var s={};return i.isMergeableObject(e)&&r(e).forEach((function(t){s[t]=n(e[t],i)})),r(t).forEach((function(r){(function(e,t){return o(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,r)||(o(e,r)&&i.isMergeableObject(t[r])?s[r]=function(e,t){if(!t.customMerge)return a;var i=t.customMerge(e);return"function"==typeof i?i:a}(r,i)(e[r],t[r],i):s[r]=n(t[r],i))})),s}(e,i,c):n(i,c)}a.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce((function(e,i){return a(e,i,t)}),{})};var c=a;e.exports=c},221:function(e,t,i){function n(e){return Array.isArray?Array.isArray(e):"[object Array]"===l(e)}i.r(t),i.d(t,{default:function(){return B}});function s(e){return"string"==typeof e}function r(e){return"number"==typeof e}function o(e){return"object"==typeof e}function a(e){return null!=e}function c(e){return!e.trim().length}function l(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const h=e=>`Missing ${e} property in key`,u=e=>`Property 'weight' in key '${e}' must be a positive integer`,d=Object.prototype.hasOwnProperty;class p{constructor(e){this._keys=[],this._keyMap={};let t=0;e.forEach((e=>{let i=f(e);t+=i.weight,this._keys.push(i),this._keyMap[i.id]=i,t+=i.weight})),this._keys.forEach((e=>{e.weight/=t}))}get(e){return this._keyMap[e]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function f(e){let t=null,i=null,r=null,o=1,a=null;if(s(e)||n(e))r=e,t=m(e),i=g(e);else{if(!d.call(e,"name"))throw new Error(h("name"));const n=e.name;if(r=n,d.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(u(n));t=m(n),i=g(n),a=e.getFn}return{path:t,id:i,weight:o,src:r,getFn:a}}function m(e){return n(e)?e:e.split(".")}function g(e){return n(e)?e.join("."):e}var v={isCaseSensitive:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(e,t)=>e.score===t.score?e.idx{if(a(e))if(t[u]){const d=e[t[u]];if(!a(d))return;if(u===t.length-1&&(s(d)||r(d)||function(e){return!0===e||!1===e||function(e){return o(e)&&null!==e}(e)&&"[object Boolean]"==l(e)}(d)))i.push(function(e){return null==e?"":function(e){if("string"==typeof e)return e;let t=e+"";return"0"==t&&1/e==-1/0?"-0":t}(e)}(d));else if(n(d)){c=!0;for(let e=0,i=d.length;e{this._keysMap[e.id]=t}))}create(){!this.isCreated&&this.docs.length&&(this.isCreated=!0,s(this.docs[0])?this.docs.forEach(((e,t)=>{this._addString(e,t)})):this.docs.forEach(((e,t)=>{this._addObject(e,t)})),this.norm.clear())}add(e){const t=this.size();s(e)?this._addString(e,t):this._addObject(e,t)}removeAt(e){this.records.splice(e,1);for(let t=e,i=this.size();t{let o=t.getFn?t.getFn(e):this.getFn(e,t.path);if(a(o))if(n(o)){let e=[];const t=[{nestedArrIndex:-1,value:o}];for(;t.length;){const{nestedArrIndex:i,value:r}=t.pop();if(a(r))if(s(r)&&!c(r)){let t={v:r,i,n:this.norm.get(r)};e.push(t)}else n(r)&&r.forEach(((e,i)=>{t.push({nestedArrIndex:i,value:e})}))}i.$[r]=e}else if(s(o)&&!c(o)){let e={v:o,n:this.norm.get(o)};i.$[r]=e}})),this.records.push(i)}toJSON(){return{keys:this.keys,records:this.records}}}function E(e,t,{getFn:i=v.getFn,fieldNormWeight:n=v.fieldNormWeight}={}){const s=new y({getFn:i,fieldNormWeight:n});return s.setKeys(e.map(f)),s.setSources(t),s.create(),s}function b(e,{errors:t=0,currentLocation:i=0,expectedLocation:n=0,distance:s=v.distance,ignoreLocation:r=v.ignoreLocation}={}){const o=t/e.length;if(r)return o;const a=Math.abs(n-i);return s?o+a/s:a?1:o}const S=32;function I(e){let t={};for(let i=0,n=e.length;i{this.chunks.push({pattern:e,alphabet:I(e),startIndex:t})},h=this.pattern.length;if(h>S){let e=0;const t=h%S,i=h-t;for(;e{const{isMatch:f,score:m,indices:g}=function(e,t,i,{location:n=v.location,distance:s=v.distance,threshold:r=v.threshold,findAllMatches:o=v.findAllMatches,minMatchCharLength:a=v.minMatchCharLength,includeMatches:c=v.includeMatches,ignoreLocation:l=v.ignoreLocation}={}){if(t.length>S)throw new Error("Pattern length exceeds max of 32.");const h=t.length,u=e.length,d=Math.max(0,Math.min(n,u));let p=r,f=d;const m=a>1||c,g=m?Array(u):[];let _;for(;(_=e.indexOf(t,f))>-1;){let e=b(t,{currentLocation:_,expectedLocation:d,distance:s,ignoreLocation:l});if(p=Math.min(e,p),f=_+h,m){let e=0;for(;e=c;r-=1){let o=r-1,a=i[e.charAt(o)];if(m&&(g[o]=+!!a),_[r]=(_[r+1]<<1|1)&a,n&&(_[r]|=(y[r+1]|y[r])<<1|1|y[r+1]),_[r]&O&&(E=b(t,{errors:n,currentLocation:o,expectedLocation:d,distance:s,ignoreLocation:l}),E<=p)){if(p=E,f=o,f<=d)break;c=Math.max(1,2*d-f)}}if(b(t,{errors:n+1,currentLocation:d,expectedLocation:d,distance:s,ignoreLocation:l})>p)break;y=_}const C={isMatch:f>=0,score:Math.max(.001,E)};if(m){const e=function(e=[],t=v.minMatchCharLength){let i=[],n=-1,s=-1,r=0;for(let o=e.length;r=t&&i.push([n,s]),n=-1)}return e[r-1]&&r-n>=t&&i.push([n,r-1]),i}(g,a);e.length?c&&(C.indices=e):C.isMatch=!1}return C}(e,t,d,{location:n+p,distance:s,threshold:r,findAllMatches:o,minMatchCharLength:a,includeMatches:i,ignoreLocation:c});f&&(u=!0),h+=m,f&&g&&(l=[...l,...g])}));let d={isMatch:u,score:u?h/this.chunks.length:1};return u&&i&&(d.indices=l),d}}class C{constructor(e){this.pattern=e}static isMultiMatch(e){return T(e,this.multiRegex)}static isSingleMatch(e){return T(e,this.singleRegex)}search(){}}function T(e,t){const i=e.match(t);return i?i[1]:null}class w extends C{constructor(e,{location:t=v.location,threshold:i=v.threshold,distance:n=v.distance,includeMatches:s=v.includeMatches,findAllMatches:r=v.findAllMatches,minMatchCharLength:o=v.minMatchCharLength,isCaseSensitive:a=v.isCaseSensitive,ignoreLocation:c=v.ignoreLocation}={}){super(e),this._bitapSearch=new O(e,{location:t,threshold:i,distance:n,includeMatches:s,findAllMatches:r,minMatchCharLength:o,isCaseSensitive:a,ignoreLocation:c})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(e){return this._bitapSearch.searchIn(e)}}class L extends C{constructor(e){super(e)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(e){let t,i=0;const n=[],s=this.pattern.length;for(;(t=e.indexOf(this.pattern,i))>-1;)i=t+s,n.push([t,i-1]);const r=!!n.length;return{isMatch:r,score:r?0:1,indices:n}}}const A=[class extends C{constructor(e){super(e)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(e){const t=e===this.pattern;return{isMatch:t,score:t?0:1,indices:[0,this.pattern.length-1]}}},L,class extends C{constructor(e){super(e)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(e){const t=e.startsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,this.pattern.length-1]}}},class extends C{constructor(e){super(e)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(e){const t=!e.startsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}},class extends C{constructor(e){super(e)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(e){const t=!e.endsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}},class extends C{constructor(e){super(e)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(e){const t=e.endsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[e.length-this.pattern.length,e.length-1]}}},class extends C{constructor(e){super(e)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(e){const t=-1===e.indexOf(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}},w],M=A.length,P=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,x=new Set([w.type,L.type]);const N=[];function D(e,t){for(let i=0,n=N.length;i!(!e[j]&&!e.$or),K=e=>({[j]:Object.keys(e).map((t=>({[t]:e[t]})))});function R(e,t,{auto:i=!0}={}){const r=e=>{let a=Object.keys(e);const c=(e=>!!e[F])(e);if(!c&&a.length>1&&!k(e))return r(K(e));if((e=>!n(e)&&o(e)&&!k(e))(e)){const n=c?e[F]:a[0],r=c?e.$val:e[n];if(!s(r))throw new Error((e=>`Invalid value for key ${e}`)(n));const o={keyId:g(n),pattern:r};return i&&(o.searcher=D(r,t)),o}let l={children:[],operator:a[0]};return a.forEach((t=>{const i=e[t];n(i)&&i.forEach((e=>{l.children.push(r(e))}))})),l};return k(e)||(e=K(e)),r(e)}function H(e,t){const i=e.matches;t.matches=[],a(i)&&i.forEach((e=>{if(!a(e.indices)||!e.indices.length)return;const{indices:i,value:n}=e;let s={indices:i,value:n};e.key&&(s.key=e.key.src),e.idx>-1&&(s.refIndex=e.idx),t.matches.push(s)}))}function Y(e,t){t.score=e.score}class B{constructor(e,t={},i){this.options={...v,...t},this.options.useExtendedSearch,this._keyStore=new p(this.options.keys),this.setCollection(e,i)}setCollection(e,t){if(this._docs=e,t&&!(t instanceof y))throw new Error("Incorrect 'index' type");this._myIndex=t||E(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(e){a(e)&&(this._docs.push(e),this._myIndex.add(e))}remove(e=(()=>!1)){const t=[];for(let i=0,n=this._docs.length;i{let i=1;e.matches.forEach((({key:e,norm:n,score:s})=>{const r=e?e.weight:null;i*=Math.pow(0===s&&r?Number.EPSILON:s,(r||1)*(t?1:n))})),e.score=i}))}(l,{ignoreFieldNorm:c}),o&&l.sort(a),r(t)&&t>-1&&(l=l.slice(0,t)),function(e,t,{includeMatches:i=v.includeMatches,includeScore:n=v.includeScore}={}){const s=[];return i&&s.push(H),n&&s.push(Y),e.map((e=>{const{idx:i}=e,n={item:t[i],refIndex:i};return s.length&&s.forEach((t=>{t(e,n)})),n}))}(l,this._docs,{includeMatches:i,includeScore:n})}_searchStringList(e){const t=D(e,this.options),{records:i}=this._myIndex,n=[];return i.forEach((({v:e,i,n:s})=>{if(!a(e))return;const{isMatch:r,score:o,indices:c}=t.searchIn(e);r&&n.push({item:e,idx:i,matches:[{score:o,value:e,norm:s,indices:c}]})})),n}_searchLogical(e){const t=R(e,this.options),i=(e,t,n)=>{if(!e.children){const{keyId:i,searcher:s}=e,r=this._findMatches({key:this._keyStore.get(i),value:this._myIndex.getValueForItemAtKeyId(t,i),searcher:s});return r&&r.length?[{idx:n,item:t,matches:r}]:[]}const s=[];for(let r=0,o=e.children.length;r{if(a(e)){let o=i(t,e,n);o.length&&(s[n]||(s[n]={idx:n,item:e,matches:[]},r.push(s[n])),o.forEach((({matches:e})=>{s[n].matches.push(...e)})))}})),r}_searchObjectList(e){const t=D(e,this.options),{keys:i,records:n}=this._myIndex,s=[];return n.forEach((({$:e,i:n})=>{if(!a(e))return;let r=[];i.forEach(((i,n)=>{r.push(...this._findMatches({key:i,value:e[n],searcher:t}))})),r.length&&s.push({idx:n,item:e,matches:r})})),s}_findMatches({key:e,value:t,searcher:i}){if(!a(t))return[];let s=[];if(n(t))t.forEach((({v:t,i:n,n:r})=>{if(!a(t))return;const{isMatch:o,score:c,indices:l}=i.searchIn(t);o&&s.push({score:c,key:e,value:t,idx:n,norm:r,indices:l})}));else{const{v:n,n:r}=t,{isMatch:o,score:a,indices:c}=i.searchIn(n);o&&s.push({score:a,key:e,value:n,norm:r,indices:c})}return s}}B.version="6.6.2",B.createIndex=E,B.parseIndex=function(e,{getFn:t=v.getFn,fieldNormWeight:i=v.fieldNormWeight}={}){const{keys:n,records:s}=e,r=new y({getFn:t,fieldNormWeight:i});return r.setKeys(n),r.setIndexRecords(s),r},B.config=v,B.parseQuery=R,function(...e){N.push(...e)}(class{constructor(e,{isCaseSensitive:t=v.isCaseSensitive,includeMatches:i=v.includeMatches,minMatchCharLength:n=v.minMatchCharLength,ignoreLocation:s=v.ignoreLocation,findAllMatches:r=v.findAllMatches,location:o=v.location,threshold:a=v.threshold,distance:c=v.distance}={}){this.query=null,this.options={isCaseSensitive:t,includeMatches:i,minMatchCharLength:n,findAllMatches:r,ignoreLocation:s,location:o,threshold:a,distance:c},this.pattern=t?e:e.toLowerCase(),this.query=function(e,t={}){return e.split("|").map((e=>{let i=e.trim().split(P).filter((e=>e&&!!e.trim())),n=[];for(let e=0,s=i.length;e{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";var e=i(529),t=i.n(e);(()=>{const e=document.getElementById("classifai-previewer-nonce");if(!e)return;const i=e.value,n={categoriesStatus:document.getElementById("classifai-settings-category").checked,keywordsStatus:document.getElementById("classifai-settings-keyword").checked,entitiesStatus:document.getElementById("classifai-settings-entity").checked,conceptsStatus:document.getElementById("classifai-settings-concept").checked},s={category:"categories",keyword:"keywords",entity:"entities",concept:"concepts"};document.querySelectorAll("#classifai-settings-category, #classifai-settings-keyword, #classifai-settings-entity, #classifai-settings-concept").forEach((e=>{e.addEventListener("change",(e=>{"classifai-settings-category"===e.target.id&&(n.categoriesStatus=e.target.checked),"classifai-settings-keyword"===e.target.id&&(n.keywordsStatus=e.target.checked),"classifai-settings-entity"===e.target.id&&(n.entitiesStatus=e.target.checked),"classifai-settings-concept"===e.target.id&&(n.conceptsStatus=e.target.checked);const t=e.target.id.split("-").at(-1);e.target.checked?document.querySelector(`.tax-row--${s[t]}`).classList.remove("tax-row--hide"):document.querySelector(`.tax-row--${s[t]}`).classList.add("tax-row--hide")}))})),document.getElementById("get-classifier-preview-data-btn").addEventListener("click",(function(e){const t=Number(document.querySelector("#classifai-settings-category_threshold").value),s=Number(document.querySelector("#classifai-settings-keyword_threshold").value),r=Number(document.querySelector("#classifai-settings-entity_threshold").value),o=Number(document.querySelector("#classifai-settings-concept_threshold").value),a=document.getElementById("classifai-preview-post-selector").value,c=document.getElementById("classifai-post-preview-wrapper"),l={categories:t,keywords:s,entities:r,concepts:o};e.target.closest(".button").classList.add("get-classifier-preview-data-btn--loading");const h=new FormData;h.append("action","get_post_classifier_preview_data"),h.append("post_id",a),h.append("nonce",i),fetch(`${ajaxurl}`,{method:"POST",body:h}).then((e=>e.json())).then((t=>{if(!t.success)return c.style.display="block",c.innerHTML=t.data,void e.target.closest(".button").classList.remove("get-classifier-preview-data-btn--loading");const{data:{categories:i=[],concepts:s=[],entities:r=[],keywords:o=[]}}=t,a=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;return Object.keys(e).map((i=>({[i]:e[i].filter((e=>(e?.score&&100*e.score>t[i]||e?.relevance&&(e.relevance,t[i]),e)))})))}({categories:i,keywords:o,entities:r,concepts:s},l),h=function(){let e="";return(arguments.length>0&&void 0!==arguments[0]?arguments[0]:[]).forEach((t=>{Object.keys(t).forEach((i=>{e+=`
${i}
`,t[i].forEach((t=>{let i=0,n=0;t?.score?i=t.score:t?.relevance&&(i=t.relevance),t?.text?n=t.text:t?.label&&(n=t.label);const s=300+300*i;i=(100*i).toFixed(2),n=n.split("/").filter((e=>""!==e)).join(", "),e+=`
`,e+=`${i}% ${n}`,e+="
"})),e+="
"}))})),e}(a);c.style.display="block",c.innerHTML=h,e.target.closest(".button").classList.remove("get-classifier-preview-data-btn--loading")}))}));const r=document.getElementById("classifai-preview-post-selector"),o=new(t())(r,{noResultsText:""}),a=function(e,t,i){let n;return function(){const t=this,i=arguments;clearTimeout(n),n=setTimeout((function(){n=null,e.apply(t,i)}),300)}}((function(e){const t=[].slice.call(document.querySelectorAll('input[name*="classifai_watson_nlu[post_types"]:checked')).map((e=>e.id.split("-").at(-1))),n=[].slice.call(document.querySelectorAll('input[name*="classifai_watson_nlu[post_statuses"]:checked')).map((e=>e.id.split("-").at(-1))),s=new FormData;s.append("post_types",t),s.append("post_status",n),s.append("search",e.detail.value),s.append("action","classifai_get_post_search_results"),s.append("nonce",i),fetch(`${ajaxurl}`,{method:"POST",body:s}).then((e=>e.json())).then((e=>{const{data:t}=e;o.setChoices(t.map((e=>({value:e.ID,label:e.post_title}))),"value","label",!0)}))}));r.addEventListener("search",a)})(),document.addEventListener("DOMContentLoaded",(function(){const e=document.getElementById("_classifai_process_content");e&&(e.addEventListener("change",(function(){const e=document.querySelector(".classifai-clasify-post-wrapper");!0===this.checked?e.style.display="none":e.style.display="block"})),e.dispatchEvent(new Event("change")))}))})()})(); \ No newline at end of file +(()=>{var e={529:e=>{var t;window,t=function(){return function(){"use strict";var e={282:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.clearChoices=t.activateChoices=t.filterChoices=t.addChoice=void 0;var n=i(883);t.addChoice=function(e){var t=e.value,i=e.label,s=e.id,r=e.groupId,o=e.disabled,a=e.elementId,c=e.customProperties,l=e.placeholder,h=e.keyCode;return{type:n.ACTION_TYPES.ADD_CHOICE,value:t,label:i,id:s,groupId:r,disabled:o,elementId:a,customProperties:c,placeholder:l,keyCode:h}},t.filterChoices=function(e){return{type:n.ACTION_TYPES.FILTER_CHOICES,results:e}},t.activateChoices=function(e){return void 0===e&&(e=!0),{type:n.ACTION_TYPES.ACTIVATE_CHOICES,active:e}},t.clearChoices=function(){return{type:n.ACTION_TYPES.CLEAR_CHOICES}}},783:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.addGroup=void 0;var n=i(883);t.addGroup=function(e){var t=e.value,i=e.id,s=e.active,r=e.disabled;return{type:n.ACTION_TYPES.ADD_GROUP,value:t,id:i,active:s,disabled:r}}},464:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.highlightItem=t.removeItem=t.addItem=void 0;var n=i(883);t.addItem=function(e){var t=e.value,i=e.label,s=e.id,r=e.choiceId,o=e.groupId,a=e.customProperties,c=e.placeholder,l=e.keyCode;return{type:n.ACTION_TYPES.ADD_ITEM,value:t,label:i,id:s,choiceId:r,groupId:o,customProperties:a,placeholder:c,keyCode:l}},t.removeItem=function(e,t){return{type:n.ACTION_TYPES.REMOVE_ITEM,id:e,choiceId:t}},t.highlightItem=function(e,t){return{type:n.ACTION_TYPES.HIGHLIGHT_ITEM,id:e,highlighted:t}}},137:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.setIsLoading=t.resetTo=t.clearAll=void 0;var n=i(883);t.clearAll=function(){return{type:n.ACTION_TYPES.CLEAR_ALL}},t.resetTo=function(e){return{type:n.ACTION_TYPES.RESET_TO,state:e}},t.setIsLoading=function(e){return{type:n.ACTION_TYPES.SET_IS_LOADING,isLoading:e}}},373:function(e,t,i){var n=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,s=0,r=t.length;s=0?this._store.getGroupById(s):null;return this._store.dispatch((0,l.highlightItem)(i,!0)),t&&this.passedElement.triggerEvent(d.EVENTS.highlightItem,{id:i,value:o,label:c,groupValue:h&&h.value?h.value:null}),this},e.prototype.unhighlightItem=function(e){if(!e||!e.id)return this;var t=e.id,i=e.groupId,n=void 0===i?-1:i,s=e.value,r=void 0===s?"":s,o=e.label,a=void 0===o?"":o,c=n>=0?this._store.getGroupById(n):null;return this._store.dispatch((0,l.highlightItem)(t,!1)),this.passedElement.triggerEvent(d.EVENTS.highlightItem,{id:t,value:r,label:a,groupValue:c&&c.value?c.value:null}),this},e.prototype.highlightAll=function(){var e=this;return this._store.items.forEach((function(t){return e.highlightItem(t)})),this},e.prototype.unhighlightAll=function(){var e=this;return this._store.items.forEach((function(t){return e.unhighlightItem(t)})),this},e.prototype.removeActiveItemsByValue=function(e){var t=this;return this._store.activeItems.filter((function(t){return t.value===e})).forEach((function(e){return t._removeItem(e)})),this},e.prototype.removeActiveItems=function(e){var t=this;return this._store.activeItems.filter((function(t){return t.id!==e})).forEach((function(e){return t._removeItem(e)})),this},e.prototype.removeHighlightedItems=function(e){var t=this;return void 0===e&&(e=!1),this._store.highlightedActiveItems.forEach((function(i){t._removeItem(i),e&&t._triggerChange(i.value)})),this},e.prototype.showDropdown=function(e){var t=this;return this.dropdown.isActive||requestAnimationFrame((function(){t.dropdown.show(),t.containerOuter.open(t.dropdown.distanceFromTopWindow),!e&&t._canSearch&&t.input.focus(),t.passedElement.triggerEvent(d.EVENTS.showDropdown,{})})),this},e.prototype.hideDropdown=function(e){var t=this;return this.dropdown.isActive?(requestAnimationFrame((function(){t.dropdown.hide(),t.containerOuter.close(),!e&&t._canSearch&&(t.input.removeActiveDescendant(),t.input.blur()),t.passedElement.triggerEvent(d.EVENTS.hideDropdown,{})})),this):this},e.prototype.getValue=function(e){void 0===e&&(e=!1);var t=this._store.activeItems.reduce((function(t,i){var n=e?i.value:i;return t.push(n),t}),[]);return this._isSelectOneElement?t[0]:t},e.prototype.setValue=function(e){var t=this;return this.initialised?(e.forEach((function(e){return t._setChoiceOrItem(e)})),this):this},e.prototype.setChoiceByValue=function(e){var t=this;return!this.initialised||this._isTextElement||(Array.isArray(e)?e:[e]).forEach((function(e){return t._findAndSelectChoiceByValue(e)})),this},e.prototype.setChoices=function(e,t,i,n){var s=this;if(void 0===e&&(e=[]),void 0===t&&(t="value"),void 0===i&&(i="label"),void 0===n&&(n=!1),!this.initialised)throw new ReferenceError("setChoices was called on a non-initialized instance of Choices");if(!this._isSelectElement)throw new TypeError("setChoices can't be used with INPUT based Choices");if("string"!=typeof t||!t)throw new TypeError("value parameter must be a name of 'value' field in passed objects");if(n&&this.clearChoices(),"function"==typeof e){var r=e(this);if("function"==typeof Promise&&r instanceof Promise)return new Promise((function(e){return requestAnimationFrame(e)})).then((function(){return s._handleLoadingState(!0)})).then((function(){return r})).then((function(e){return s.setChoices(e,t,i,n)})).catch((function(e){s.config.silent||console.error(e)})).then((function(){return s._handleLoadingState(!1)})).then((function(){return s}));if(!Array.isArray(r))throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: ".concat(typeof r));return this.setChoices(r,t,i,!1)}if(!Array.isArray(e))throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices");return this.containerOuter.removeLoadingState(),this._startLoading(),e.forEach((function(e){if(e.choices)s._addGroup({id:e.id?parseInt("".concat(e.id),10):null,group:e,valueKey:t,labelKey:i});else{var n=e;s._addChoice({value:n[t],label:n[i],isSelected:!!n.selected,isDisabled:!!n.disabled,placeholder:!!n.placeholder,customProperties:n.customProperties})}})),this._stopLoading(),this},e.prototype.clearChoices=function(){return this._store.dispatch((0,a.clearChoices)()),this},e.prototype.clearStore=function(){return this._store.dispatch((0,h.clearAll)()),this},e.prototype.clearInput=function(){var e=!this._isSelectOneElement;return this.input.clear(e),!this._isTextElement&&this._canSearch&&(this._isSearching=!1,this._store.dispatch((0,a.activateChoices)(!0))),this},e.prototype._render=function(){if(!this._store.isLoading()){this._currentState=this._store.state;var e=this._currentState.choices!==this._prevState.choices||this._currentState.groups!==this._prevState.groups||this._currentState.items!==this._prevState.items,t=this._isSelectElement,i=this._currentState.items!==this._prevState.items;e&&(t&&this._renderChoices(),i&&this._renderItems(),this._prevState=this._currentState)}},e.prototype._renderChoices=function(){var e=this,t=this._store,i=t.activeGroups,n=t.activeChoices,s=document.createDocumentFragment();if(this.choiceList.clear(),this.config.resetScrollPosition&&requestAnimationFrame((function(){return e.choiceList.scrollToTop()})),i.length>=1&&!this._isSearching){var r=n.filter((function(e){return!0===e.placeholder&&-1===e.groupId}));r.length>=1&&(s=this._createChoicesFragment(r,s)),s=this._createGroupsFragment(i,n,s)}else n.length>=1&&(s=this._createChoicesFragment(n,s));if(s.childNodes&&s.childNodes.length>0){var o=this._store.activeItems,a=this._canAddItem(o,this.input.value);if(a.response)this.choiceList.append(s),this._highlightChoice();else{var c=this._getTemplate("notice",a.notice);this.choiceList.append(c)}}else{var l=void 0;c=void 0,this._isSearching?(c="function"==typeof this.config.noResultsText?this.config.noResultsText():this.config.noResultsText,l=this._getTemplate("notice",c,"no-results")):(c="function"==typeof this.config.noChoicesText?this.config.noChoicesText():this.config.noChoicesText,l=this._getTemplate("notice",c,"no-choices")),this.choiceList.append(l)}},e.prototype._renderItems=function(){var e=this._store.activeItems||[];this.itemList.clear();var t=this._createItemsFragment(e);t.childNodes&&this.itemList.append(t)},e.prototype._createGroupsFragment=function(e,t,i){var n=this;return void 0===i&&(i=document.createDocumentFragment()),this.config.shouldSort&&e.sort(this.config.sorter),e.forEach((function(e){var s=function(e){return t.filter((function(t){return n._isSelectOneElement?t.groupId===e.id:t.groupId===e.id&&("always"===n.config.renderSelectedChoices||!t.selected)}))}(e);if(s.length>=1){var r=n._getTemplate("choiceGroup",e);i.appendChild(r),n._createChoicesFragment(s,i,!0)}})),i},e.prototype._createChoicesFragment=function(e,t,i){var s=this;void 0===t&&(t=document.createDocumentFragment()),void 0===i&&(i=!1);var r=this.config,o=r.renderSelectedChoices,a=r.searchResultLimit,c=r.renderChoiceLimit,l=this._isSearching?f.sortByScore:this.config.sorter,h=function(e){if("auto"!==o||s._isSelectOneElement||!e.selected){var i=s._getTemplate("choice",e,s.config.itemSelectText);t.appendChild(i)}},u=e;"auto"!==o||this._isSelectOneElement||(u=e.filter((function(e){return!e.selected})));var d=u.reduce((function(e,t){return t.placeholder?e.placeholderChoices.push(t):e.normalChoices.push(t),e}),{placeholderChoices:[],normalChoices:[]}),p=d.placeholderChoices,m=d.normalChoices;(this.config.shouldSort||this._isSearching)&&m.sort(l);var g=u.length,v=this._isSelectOneElement?n(n([],p,!0),m,!0):m;this._isSearching?g=a:c&&c>0&&!i&&(g=c);for(var _=0;_=n){var o=s?this._searchChoices(e):0;this.passedElement.triggerEvent(d.EVENTS.search,{value:e,resultCount:o})}else r&&(this._isSearching=!1,this._store.dispatch((0,a.activateChoices)(!0)))}},e.prototype._canAddItem=function(e,t){var i=!0,n="function"==typeof this.config.addItemText?this.config.addItemText(t):this.config.addItemText;if(!this._isSelectOneElement){var s=(0,f.existsInArray)(e,t);this.config.maxItemCount>0&&this.config.maxItemCount<=e.length&&(i=!1,n="function"==typeof this.config.maxItemText?this.config.maxItemText(this.config.maxItemCount):this.config.maxItemText),!this.config.duplicateItemsAllowed&&s&&i&&(i=!1,n="function"==typeof this.config.uniqueItemText?this.config.uniqueItemText(t):this.config.uniqueItemText),this._isTextElement&&this.config.addItems&&i&&"function"==typeof this.config.addItemFilter&&!this.config.addItemFilter(t)&&(i=!1,n="function"==typeof this.config.customAddItemText?this.config.customAddItemText(t):this.config.customAddItemText)}return{response:i,notice:n}},e.prototype._searchChoices=function(e){var t="string"==typeof e?e.trim():e,i="string"==typeof this._currentValue?this._currentValue.trim():this._currentValue;if(t.length<1&&t==="".concat(i," "))return 0;var s=this._store.searchableChoices,r=t,c=Object.assign(this.config.fuseOptions,{keys:n([],this.config.searchFields,!0),includeMatches:!0}),l=new o.default(s,c).search(r);return this._currentValue=t,this._highlightPosition=0,this._isSearching=!0,this._store.dispatch((0,a.filterChoices)(l)),l.length},e.prototype._addEventListeners=function(){var e=document.documentElement;e.addEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.addEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.addEventListener("mousedown",this._onMouseDown,!0),e.addEventListener("click",this._onClick,{passive:!0}),e.addEventListener("touchmove",this._onTouchMove,{passive:!0}),this.dropdown.element.addEventListener("mouseover",this._onMouseOver,{passive:!0}),this._isSelectOneElement&&(this.containerOuter.element.addEventListener("focus",this._onFocus,{passive:!0}),this.containerOuter.element.addEventListener("blur",this._onBlur,{passive:!0})),this.input.element.addEventListener("keyup",this._onKeyUp,{passive:!0}),this.input.element.addEventListener("focus",this._onFocus,{passive:!0}),this.input.element.addEventListener("blur",this._onBlur,{passive:!0}),this.input.element.form&&this.input.element.form.addEventListener("reset",this._onFormReset,{passive:!0}),this.input.addEventListeners()},e.prototype._removeEventListeners=function(){var e=document.documentElement;e.removeEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.removeEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.removeEventListener("mousedown",this._onMouseDown,!0),e.removeEventListener("click",this._onClick),e.removeEventListener("touchmove",this._onTouchMove),this.dropdown.element.removeEventListener("mouseover",this._onMouseOver),this._isSelectOneElement&&(this.containerOuter.element.removeEventListener("focus",this._onFocus),this.containerOuter.element.removeEventListener("blur",this._onBlur)),this.input.element.removeEventListener("keyup",this._onKeyUp),this.input.element.removeEventListener("focus",this._onFocus),this.input.element.removeEventListener("blur",this._onBlur),this.input.element.form&&this.input.element.form.removeEventListener("reset",this._onFormReset),this.input.removeEventListeners()},e.prototype._onKeyDown=function(e){var t=e.keyCode,i=this._store.activeItems,n=this.input.isFocussed,s=this.dropdown.isActive,r=this.itemList.hasChildren(),o=String.fromCharCode(t),a=/[^\x00-\x1F]/.test(o),c=d.KEY_CODES.BACK_KEY,l=d.KEY_CODES.DELETE_KEY,h=d.KEY_CODES.ENTER_KEY,u=d.KEY_CODES.A_KEY,p=d.KEY_CODES.ESC_KEY,f=d.KEY_CODES.UP_KEY,m=d.KEY_CODES.DOWN_KEY,g=d.KEY_CODES.PAGE_UP_KEY,v=d.KEY_CODES.PAGE_DOWN_KEY;switch(this._isTextElement||s||!a||(this.showDropdown(),this.input.isFocussed||(this.input.value+=e.key.toLowerCase())),t){case u:return this._onSelectKey(e,r);case h:return this._onEnterKey(e,i,s);case p:return this._onEscapeKey(s);case f:case g:case m:case v:return this._onDirectionKey(e,s);case l:case c:return this._onDeleteKey(e,i,n)}},e.prototype._onKeyUp=function(e){var t=e.target,i=e.keyCode,n=this.input.value,s=this._store.activeItems,r=this._canAddItem(s,n),o=d.KEY_CODES.BACK_KEY,c=d.KEY_CODES.DELETE_KEY;if(this._isTextElement)if(r.notice&&n){var l=this._getTemplate("notice",r.notice);this.dropdown.element.innerHTML=l.outerHTML,this.showDropdown(!0)}else this.hideDropdown(!0);else{var h=(i===o||i===c)&&t&&!t.value,u=!this._isTextElement&&this._isSearching,p=this._canSearch&&r.response;h&&u?(this._isSearching=!1,this._store.dispatch((0,a.activateChoices)(!0))):p&&this._handleSearch(this.input.rawValue)}this._canSearch=this.config.searchEnabled},e.prototype._onSelectKey=function(e,t){var i=e.ctrlKey,n=e.metaKey;(i||n)&&t&&(this._canSearch=!1,this.config.removeItems&&!this.input.value&&this.input.element===document.activeElement&&this.highlightAll())},e.prototype._onEnterKey=function(e,t,i){var n=e.target,s=d.KEY_CODES.ENTER_KEY,r=n&&n.hasAttribute("data-button");if(this._isTextElement&&n&&n.value){var o=this.input.value;this._canAddItem(t,o).response&&(this.hideDropdown(!0),this._addItem({value:o}),this._triggerChange(o),this.clearInput())}if(r&&(this._handleButtonAction(t,n),e.preventDefault()),i){var a=this.dropdown.getChild(".".concat(this.config.classNames.highlightedState));a&&(t[0]&&(t[0].keyCode=s),this._handleChoiceAction(t,a)),e.preventDefault()}else this._isSelectOneElement&&(this.showDropdown(),e.preventDefault())},e.prototype._onEscapeKey=function(e){e&&(this.hideDropdown(!0),this.containerOuter.focus())},e.prototype._onDirectionKey=function(e,t){var i=e.keyCode,n=e.metaKey,s=d.KEY_CODES.DOWN_KEY,r=d.KEY_CODES.PAGE_UP_KEY,o=d.KEY_CODES.PAGE_DOWN_KEY;if(t||this._isSelectOneElement){this.showDropdown(),this._canSearch=!1;var a=i===s||i===o?1:-1,c="[data-choice-selectable]",l=void 0;if(n||i===o||i===r)l=a>0?this.dropdown.element.querySelector("".concat(c,":last-of-type")):this.dropdown.element.querySelector(c);else{var h=this.dropdown.element.querySelector(".".concat(this.config.classNames.highlightedState));l=h?(0,f.getAdjacentEl)(h,c,a):this.dropdown.element.querySelector(c)}l&&((0,f.isScrolledIntoView)(l,this.choiceList.element,a)||this.choiceList.scrollToChildElement(l,a),this._highlightChoice(l)),e.preventDefault()}},e.prototype._onDeleteKey=function(e,t,i){var n=e.target;this._isSelectOneElement||n.value||!i||(this._handleBackspace(t),e.preventDefault())},e.prototype._onTouchMove=function(){this._wasTap&&(this._wasTap=!1)},e.prototype._onTouchEnd=function(e){var t=(e||e.touches[0]).target;this._wasTap&&this.containerOuter.element.contains(t)&&((t===this.containerOuter.element||t===this.containerInner.element)&&(this._isTextElement?this.input.focus():this._isSelectMultipleElement&&this.showDropdown()),e.stopPropagation()),this._wasTap=!0},e.prototype._onMouseDown=function(e){var t=e.target;if(t instanceof HTMLElement){if(_&&this.choiceList.element.contains(t)){var i=this.choiceList.element.firstElementChild,n="ltr"===this._direction?e.offsetX>=i.offsetWidth:e.offsetX0&&this.unhighlightAll(),this.containerOuter.removeFocusState(),this.hideDropdown(!0))},e.prototype._onFocus=function(e){var t,i=this,n=e.target;n&&this.containerOuter.element.contains(n)&&((t={})[d.TEXT_TYPE]=function(){n===i.input.element&&i.containerOuter.addFocusState()},t[d.SELECT_ONE_TYPE]=function(){i.containerOuter.addFocusState(),n===i.input.element&&i.showDropdown(!0)},t[d.SELECT_MULTIPLE_TYPE]=function(){n===i.input.element&&(i.showDropdown(!0),i.containerOuter.addFocusState())},t)[this.passedElement.element.type]()},e.prototype._onBlur=function(e){var t,i=this,n=e.target;if(n&&this.containerOuter.element.contains(n)&&!this._isScrollingOnIe){var s=this._store.activeItems.some((function(e){return e.highlighted}));((t={})[d.TEXT_TYPE]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),s&&i.unhighlightAll(),i.hideDropdown(!0))},t[d.SELECT_ONE_TYPE]=function(){i.containerOuter.removeFocusState(),(n===i.input.element||n===i.containerOuter.element&&!i._canSearch)&&i.hideDropdown(!0)},t[d.SELECT_MULTIPLE_TYPE]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),i.hideDropdown(!0),s&&i.unhighlightAll())},t)[this.passedElement.element.type]()}else this._isScrollingOnIe=!1,this.input.element.focus()},e.prototype._onFormReset=function(){this._store.dispatch((0,h.resetTo)(this._initialState))},e.prototype._highlightChoice=function(e){var t=this;void 0===e&&(e=null);var i=Array.from(this.dropdown.element.querySelectorAll("[data-choice-selectable]"));if(i.length){var n=e;Array.from(this.dropdown.element.querySelectorAll(".".concat(this.config.classNames.highlightedState))).forEach((function(e){e.classList.remove(t.config.classNames.highlightedState),e.setAttribute("aria-selected","false")})),n?this._highlightPosition=i.indexOf(n):(n=i.length>this._highlightPosition?i[this._highlightPosition]:i[i.length-1])||(n=i[0]),n.classList.add(this.config.classNames.highlightedState),n.setAttribute("aria-selected","true"),this.passedElement.triggerEvent(d.EVENTS.highlightChoice,{el:n}),this.dropdown.isActive&&(this.input.setActiveDescendant(n.id),this.containerOuter.setActiveDescendant(n.id))}},e.prototype._addItem=function(e){var t=e.value,i=e.label,n=void 0===i?null:i,s=e.choiceId,r=void 0===s?-1:s,o=e.groupId,a=void 0===o?-1:o,c=e.customProperties,h=void 0===c?{}:c,u=e.placeholder,p=void 0!==u&&u,f=e.keyCode,m=void 0===f?-1:f,g="string"==typeof t?t.trim():t,v=this._store.items,_=n||g,y=r||-1,E=a>=0?this._store.getGroupById(a):null,b=v?v.length+1:1;this.config.prependValue&&(g=this.config.prependValue+g.toString()),this.config.appendValue&&(g+=this.config.appendValue.toString()),this._store.dispatch((0,l.addItem)({value:g,label:_,id:b,choiceId:y,groupId:a,customProperties:h,placeholder:p,keyCode:m})),this._isSelectOneElement&&this.removeActiveItems(b),this.passedElement.triggerEvent(d.EVENTS.addItem,{id:b,value:g,label:_,customProperties:h,groupValue:E&&E.value?E.value:null,keyCode:m})},e.prototype._removeItem=function(e){var t=e.id,i=e.value,n=e.label,s=e.customProperties,r=e.choiceId,o=e.groupId,a=o&&o>=0?this._store.getGroupById(o):null;t&&r&&(this._store.dispatch((0,l.removeItem)(t,r)),this.passedElement.triggerEvent(d.EVENTS.removeItem,{id:t,value:i,label:n,customProperties:s,groupValue:a&&a.value?a.value:null}))},e.prototype._addChoice=function(e){var t=e.value,i=e.label,n=void 0===i?null:i,s=e.isSelected,r=void 0!==s&&s,o=e.isDisabled,c=void 0!==o&&o,l=e.groupId,h=void 0===l?-1:l,u=e.customProperties,d=void 0===u?{}:u,p=e.placeholder,f=void 0!==p&&p,m=e.keyCode,g=void 0===m?-1:m;if(null!=t){var v=this._store.choices,_=n||t,y=v?v.length+1:1,E="".concat(this._baseId,"-").concat(this._idNames.itemChoice,"-").concat(y);this._store.dispatch((0,a.addChoice)({id:y,groupId:h,elementId:E,value:t,label:_,disabled:c,customProperties:d,placeholder:f,keyCode:g})),r&&this._addItem({value:t,label:_,choiceId:y,customProperties:d,placeholder:f,keyCode:g})}},e.prototype._addGroup=function(e){var t=this,i=e.group,n=e.id,s=e.valueKey,r=void 0===s?"value":s,o=e.labelKey,a=void 0===o?"label":o,l=(0,f.isType)("Object",i)?i.choices:Array.from(i.getElementsByTagName("OPTION")),h=n||Math.floor((new Date).valueOf()*Math.random()),u=!!i.disabled&&i.disabled;l?(this._store.dispatch((0,c.addGroup)({value:i.label,id:h,active:!0,disabled:u})),l.forEach((function(e){var i=e.disabled||e.parentNode&&e.parentNode.disabled;t._addChoice({value:e[r],label:(0,f.isType)("Object",e)?e[a]:e.innerHTML,isSelected:e.selected,isDisabled:i,groupId:h,customProperties:e.customProperties,placeholder:e.placeholder})}))):this._store.dispatch((0,c.addGroup)({value:i.label,id:i.id,active:!1,disabled:i.disabled}))},e.prototype._getTemplate=function(e){for(var t,i=[],s=1;s0?this.element.scrollTop+o-s:e.offsetTop;requestAnimationFrame((function(){i._animateScroll(a,t)}))}},e.prototype._scrollDown=function(e,t,i){var n=(i-e)/t,s=n>1?n:1;this.element.scrollTop=e+s},e.prototype._scrollUp=function(e,t,i){var n=(e-i)/t,s=n>1?n:1;this.element.scrollTop=e-s},e.prototype._animateScroll=function(e,t){var i=this,s=n.SCROLLING_SPEED,r=this.element.scrollTop,o=!1;t>0?(this._scrollDown(r,s,e),re&&(o=!0)),o&&requestAnimationFrame((function(){i._animateScroll(e,t)}))},e}();t.default=s},730:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0});var n=i(799),s=function(){function e(e){var t=e.element,i=e.classNames;if(this.element=t,this.classNames=i,!(t instanceof HTMLInputElement||t instanceof HTMLSelectElement))throw new TypeError("Invalid element passed");this.isDisabled=!1}return Object.defineProperty(e.prototype,"isActive",{get:function(){return"active"===this.element.dataset.choice},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dir",{get:function(){return this.element.dir},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.element.value},set:function(e){this.element.value=e},enumerable:!1,configurable:!0}),e.prototype.conceal=function(){this.element.classList.add(this.classNames.input),this.element.hidden=!0,this.element.tabIndex=-1;var e=this.element.getAttribute("style");e&&this.element.setAttribute("data-choice-orig-style",e),this.element.setAttribute("data-choice","active")},e.prototype.reveal=function(){this.element.classList.remove(this.classNames.input),this.element.hidden=!1,this.element.removeAttribute("tabindex");var e=this.element.getAttribute("data-choice-orig-style");e?(this.element.removeAttribute("data-choice-orig-style"),this.element.setAttribute("style",e)):this.element.removeAttribute("style"),this.element.removeAttribute("data-choice"),this.element.value=this.element.value},e.prototype.enable=function(){this.element.removeAttribute("disabled"),this.element.disabled=!1,this.isDisabled=!1},e.prototype.disable=function(){this.element.setAttribute("disabled",""),this.element.disabled=!0,this.isDisabled=!0},e.prototype.triggerEvent=function(e,t){(0,n.dispatchEvent)(this.element,e,t)},e}();t.default=s},541:function(e,t,i){var n,s=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function __(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(__.prototype=t.prototype,new __)}),r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var o=function(e){function t(t){var i=t.element,n=t.classNames,s=t.delimiter,r=e.call(this,{element:i,classNames:n})||this;return r.delimiter=s,r}return s(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.element.value},set:function(e){this.element.setAttribute("value",e),this.element.value=e},enumerable:!1,configurable:!0}),t}(r(i(730)).default);t.default=o},982:function(e,t,i){var n,s=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function __(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(__.prototype=t.prototype,new __)}),r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var o=function(e){function t(t){var i=t.element,n=t.classNames,s=t.template,r=e.call(this,{element:i,classNames:n})||this;return r.template=s,r}return s(t,e),Object.defineProperty(t.prototype,"placeholderOption",{get:function(){return this.element.querySelector('option[value=""]')||this.element.querySelector("option[placeholder]")},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"optionGroups",{get:function(){return Array.from(this.element.getElementsByTagName("OPTGROUP"))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"options",{get:function(){return Array.from(this.element.options)},set:function(e){var t=this,i=document.createDocumentFragment();e.forEach((function(e){return n=e,s=t.template(n),void i.appendChild(s);var n,s})),this.appendDocFragment(i)},enumerable:!1,configurable:!0}),t.prototype.appendDocFragment=function(e){this.element.innerHTML="",this.element.appendChild(e)},t}(r(i(730)).default);t.default=o},883:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.SCROLLING_SPEED=t.SELECT_MULTIPLE_TYPE=t.SELECT_ONE_TYPE=t.TEXT_TYPE=t.KEY_CODES=t.ACTION_TYPES=t.EVENTS=void 0,t.EVENTS={showDropdown:"showDropdown",hideDropdown:"hideDropdown",change:"change",choice:"choice",search:"search",addItem:"addItem",removeItem:"removeItem",highlightItem:"highlightItem",highlightChoice:"highlightChoice",unhighlightItem:"unhighlightItem"},t.ACTION_TYPES={ADD_CHOICE:"ADD_CHOICE",FILTER_CHOICES:"FILTER_CHOICES",ACTIVATE_CHOICES:"ACTIVATE_CHOICES",CLEAR_CHOICES:"CLEAR_CHOICES",ADD_GROUP:"ADD_GROUP",ADD_ITEM:"ADD_ITEM",REMOVE_ITEM:"REMOVE_ITEM",HIGHLIGHT_ITEM:"HIGHLIGHT_ITEM",CLEAR_ALL:"CLEAR_ALL",RESET_TO:"RESET_TO",SET_IS_LOADING:"SET_IS_LOADING"},t.KEY_CODES={BACK_KEY:46,DELETE_KEY:8,ENTER_KEY:13,A_KEY:65,ESC_KEY:27,UP_KEY:38,DOWN_KEY:40,PAGE_UP_KEY:33,PAGE_DOWN_KEY:34},t.TEXT_TYPE="text",t.SELECT_ONE_TYPE="select-one",t.SELECT_MULTIPLE_TYPE="select-multiple",t.SCROLLING_SPEED=4},789:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_CONFIG=t.DEFAULT_CLASSNAMES=void 0;var n=i(799);t.DEFAULT_CLASSNAMES={containerOuter:"choices",containerInner:"choices__inner",input:"choices__input",inputCloned:"choices__input--cloned",list:"choices__list",listItems:"choices__list--multiple",listSingle:"choices__list--single",listDropdown:"choices__list--dropdown",item:"choices__item",itemSelectable:"choices__item--selectable",itemDisabled:"choices__item--disabled",itemChoice:"choices__item--choice",placeholder:"choices__placeholder",group:"choices__group",groupHeading:"choices__heading",button:"choices__button",activeState:"is-active",focusState:"is-focused",openState:"is-open",disabledState:"is-disabled",highlightedState:"is-highlighted",selectedState:"is-selected",flippedState:"is-flipped",loadingState:"is-loading",noResults:"has-no-results",noChoices:"has-no-choices"},t.DEFAULT_CONFIG={items:[],choices:[],silent:!1,renderChoiceLimit:-1,maxItemCount:-1,addItems:!0,addItemFilter:null,removeItems:!0,removeItemButton:!1,editItems:!1,allowHTML:!0,duplicateItemsAllowed:!0,delimiter:",",paste:!0,searchEnabled:!0,searchChoices:!0,searchFloor:1,searchResultLimit:4,searchFields:["label","value"],position:"auto",resetScrollPosition:!0,shouldSort:!0,shouldSortItems:!1,sorter:n.sortByAlpha,placeholder:!0,placeholderValue:null,searchPlaceholderValue:null,prependValue:null,appendValue:null,renderSelectedChoices:"auto",loadingText:"Loading...",noResultsText:"No results found",noChoicesText:"No choices to choose from",itemSelectText:"Press to select",uniqueItemText:"Only unique values can be added",customAddItemText:"Only values matching specific conditions can be added",addItemText:function(e){return'Press Enter to add "'.concat((0,n.sanitise)(e),'"')},maxItemText:function(e){return"Only ".concat(e," values can be added")},valueComparer:function(e,t){return e===t},fuseOptions:{includeScore:!0},labelId:"",callbackOnInit:null,callbackOnCreateTemplates:null,classNames:t.DEFAULT_CLASSNAMES}},18:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},978:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},948:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},359:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},285:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},533:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},187:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,s)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),s=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0}),s(i(18),t),s(i(978),t),s(i(948),t),s(i(359),t),s(i(285),t),s(i(533),t),s(i(287),t),s(i(132),t),s(i(837),t),s(i(598),t),s(i(369),t),s(i(37),t),s(i(47),t),s(i(923),t),s(i(876),t)},287:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},132:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},837:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},598:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},37:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},369:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},47:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},923:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},876:function(e,t){Object.defineProperty(t,"__esModule",{value:!0})},799:function(e,t){var i;Object.defineProperty(t,"__esModule",{value:!0}),t.parseCustomProperties=t.diff=t.cloneObject=t.existsInArray=t.dispatchEvent=t.sortByScore=t.sortByAlpha=t.strToEl=t.sanitise=t.isScrolledIntoView=t.getAdjacentEl=t.wrap=t.isType=t.getType=t.generateId=t.generateChars=t.getRandomNumber=void 0,t.getRandomNumber=function(e,t){return Math.floor(Math.random()*(t-e)+e)},t.generateChars=function(e){return Array.from({length:e},(function(){return(0,t.getRandomNumber)(0,36).toString(36)})).join("")},t.generateId=function(e,i){var n=e.id||e.name&&"".concat(e.name,"-").concat((0,t.generateChars)(2))||(0,t.generateChars)(4);return n=n.replace(/(:|\.|\[|\]|,)/g,""),"".concat(i,"-").concat(n)},t.getType=function(e){return Object.prototype.toString.call(e).slice(8,-1)},t.isType=function(e,i){return null!=i&&(0,t.getType)(i)===e},t.wrap=function(e,t){return void 0===t&&(t=document.createElement("div")),e.parentNode&&(e.nextSibling?e.parentNode.insertBefore(t,e.nextSibling):e.parentNode.appendChild(t)),t.appendChild(e)},t.getAdjacentEl=function(e,t,i){void 0===i&&(i=1);for(var n="".concat(i>0?"next":"previous","ElementSibling"),s=e[n];s;){if(s.matches(t))return s;s=s[n]}return s},t.isScrolledIntoView=function(e,t,i){return void 0===i&&(i=1),!!e&&(i>0?t.scrollTop+t.offsetHeight>=e.offsetTop+e.offsetHeight:e.offsetTop>=t.scrollTop)},t.sanitise=function(e){return"string"!=typeof e?e:e.replace(/&/g,"&").replace(/>/g,">").replace(/-1?e.map((function(e){var t=e;return t.id===parseInt("".concat(o.choiceId),10)&&(t.selected=!0),t})):e;case"REMOVE_ITEM":var a=n;return a.choiceId&&a.choiceId>-1?e.map((function(e){var t=e;return t.id===parseInt("".concat(a.choiceId),10)&&(t.selected=!1),t})):e;case"FILTER_CHOICES":var c=n;return e.map((function(e){var t=e;return t.active=c.results.some((function(e){var i=e.item,n=e.score;return i.id===t.id&&(t.score=n,!0)})),t}));case"ACTIVATE_CHOICES":var l=n;return e.map((function(e){var t=e;return t.active=l.active,t}));case"CLEAR_CHOICES":return t.defaultState;default:return e}}},871:function(e,t){var i=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,s=0,r=t.length;s0?"treeitem":"option"),Object.assign(E.dataset,{choice:"",id:d,value:p,selectText:i}),v?(E.classList.add(h),E.dataset.choiceDisabled="",E.setAttribute("aria-disabled","true")):(E.classList.add(c),E.dataset.choiceSelectable=""),E},input:function(e,t){var i=e.classNames,n=i.input,s=i.inputCloned,r=Object.assign(document.createElement("input"),{type:"search",name:"search_terms",className:"".concat(n," ").concat(s),autocomplete:"off",autocapitalize:"off",spellcheck:!1});return r.setAttribute("role","textbox"),r.setAttribute("aria-autocomplete","list"),r.setAttribute("aria-label",t),r},dropdown:function(e){var t=e.classNames,i=t.list,n=t.listDropdown,s=document.createElement("div");return s.classList.add(i,n),s.setAttribute("aria-expanded","false"),s},notice:function(e,t,i){var n,s=e.allowHTML,r=e.classNames,o=r.item,a=r.itemChoice,c=r.noResults,l=r.noChoices;void 0===i&&(i="");var h=[o,a];return"no-choices"===i?h.push(l):"no-results"===i&&h.push(c),Object.assign(document.createElement("div"),((n={})[s?"innerHTML":"innerText"]=t,n.className=h.join(" "),n))},option:function(e){var t=e.label,i=e.value,n=e.customProperties,s=e.active,r=e.disabled,o=new Option(t,i,!1,s);return n&&(o.dataset.customProperties="".concat(n)),o.disabled=!!r,o}};t.default=i},996:function(e){var t=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||function(e){return e.$$typeof===i}(e)}(e)},i="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function n(e,t){return!1!==t.clone&&t.isMergeableObject(e)?a((i=e,Array.isArray(i)?[]:{}),e,t):e;var i}function s(e,t,i){return e.concat(t).map((function(e){return n(e,i)}))}function r(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter((function(t){return e.propertyIsEnumerable(t)})):[]}(e))}function o(e,t){try{return t in e}catch(e){return!1}}function a(e,i,c){(c=c||{}).arrayMerge=c.arrayMerge||s,c.isMergeableObject=c.isMergeableObject||t,c.cloneUnlessOtherwiseSpecified=n;var l=Array.isArray(i);return l===Array.isArray(e)?l?c.arrayMerge(e,i,c):function(e,t,i){var s={};return i.isMergeableObject(e)&&r(e).forEach((function(t){s[t]=n(e[t],i)})),r(t).forEach((function(r){(function(e,t){return o(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,r)||(o(e,r)&&i.isMergeableObject(t[r])?s[r]=function(e,t){if(!t.customMerge)return a;var i=t.customMerge(e);return"function"==typeof i?i:a}(r,i)(e[r],t[r],i):s[r]=n(t[r],i))})),s}(e,i,c):n(i,c)}a.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce((function(e,i){return a(e,i,t)}),{})};var c=a;e.exports=c},221:function(e,t,i){function n(e){return Array.isArray?Array.isArray(e):"[object Array]"===l(e)}i.r(t),i.d(t,{default:function(){return B}});function s(e){return"string"==typeof e}function r(e){return"number"==typeof e}function o(e){return"object"==typeof e}function a(e){return null!=e}function c(e){return!e.trim().length}function l(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const h=e=>`Missing ${e} property in key`,u=e=>`Property 'weight' in key '${e}' must be a positive integer`,d=Object.prototype.hasOwnProperty;class p{constructor(e){this._keys=[],this._keyMap={};let t=0;e.forEach((e=>{let i=f(e);t+=i.weight,this._keys.push(i),this._keyMap[i.id]=i,t+=i.weight})),this._keys.forEach((e=>{e.weight/=t}))}get(e){return this._keyMap[e]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function f(e){let t=null,i=null,r=null,o=1,a=null;if(s(e)||n(e))r=e,t=m(e),i=g(e);else{if(!d.call(e,"name"))throw new Error(h("name"));const n=e.name;if(r=n,d.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(u(n));t=m(n),i=g(n),a=e.getFn}return{path:t,id:i,weight:o,src:r,getFn:a}}function m(e){return n(e)?e:e.split(".")}function g(e){return n(e)?e.join("."):e}var v={isCaseSensitive:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(e,t)=>e.score===t.score?e.idx{if(a(e))if(t[u]){const d=e[t[u]];if(!a(d))return;if(u===t.length-1&&(s(d)||r(d)||function(e){return!0===e||!1===e||function(e){return o(e)&&null!==e}(e)&&"[object Boolean]"==l(e)}(d)))i.push(function(e){return null==e?"":function(e){if("string"==typeof e)return e;let t=e+"";return"0"==t&&1/e==-1/0?"-0":t}(e)}(d));else if(n(d)){c=!0;for(let e=0,i=d.length;e{this._keysMap[e.id]=t}))}create(){!this.isCreated&&this.docs.length&&(this.isCreated=!0,s(this.docs[0])?this.docs.forEach(((e,t)=>{this._addString(e,t)})):this.docs.forEach(((e,t)=>{this._addObject(e,t)})),this.norm.clear())}add(e){const t=this.size();s(e)?this._addString(e,t):this._addObject(e,t)}removeAt(e){this.records.splice(e,1);for(let t=e,i=this.size();t{let o=t.getFn?t.getFn(e):this.getFn(e,t.path);if(a(o))if(n(o)){let e=[];const t=[{nestedArrIndex:-1,value:o}];for(;t.length;){const{nestedArrIndex:i,value:r}=t.pop();if(a(r))if(s(r)&&!c(r)){let t={v:r,i,n:this.norm.get(r)};e.push(t)}else n(r)&&r.forEach(((e,i)=>{t.push({nestedArrIndex:i,value:e})}))}i.$[r]=e}else if(s(o)&&!c(o)){let e={v:o,n:this.norm.get(o)};i.$[r]=e}})),this.records.push(i)}toJSON(){return{keys:this.keys,records:this.records}}}function E(e,t,{getFn:i=v.getFn,fieldNormWeight:n=v.fieldNormWeight}={}){const s=new y({getFn:i,fieldNormWeight:n});return s.setKeys(e.map(f)),s.setSources(t),s.create(),s}function b(e,{errors:t=0,currentLocation:i=0,expectedLocation:n=0,distance:s=v.distance,ignoreLocation:r=v.ignoreLocation}={}){const o=t/e.length;if(r)return o;const a=Math.abs(n-i);return s?o+a/s:a?1:o}const S=32;function I(e){let t={};for(let i=0,n=e.length;i{this.chunks.push({pattern:e,alphabet:I(e),startIndex:t})},h=this.pattern.length;if(h>S){let e=0;const t=h%S,i=h-t;for(;e{const{isMatch:f,score:m,indices:g}=function(e,t,i,{location:n=v.location,distance:s=v.distance,threshold:r=v.threshold,findAllMatches:o=v.findAllMatches,minMatchCharLength:a=v.minMatchCharLength,includeMatches:c=v.includeMatches,ignoreLocation:l=v.ignoreLocation}={}){if(t.length>S)throw new Error("Pattern length exceeds max of 32.");const h=t.length,u=e.length,d=Math.max(0,Math.min(n,u));let p=r,f=d;const m=a>1||c,g=m?Array(u):[];let _;for(;(_=e.indexOf(t,f))>-1;){let e=b(t,{currentLocation:_,expectedLocation:d,distance:s,ignoreLocation:l});if(p=Math.min(e,p),f=_+h,m){let e=0;for(;e=c;r-=1){let o=r-1,a=i[e.charAt(o)];if(m&&(g[o]=+!!a),_[r]=(_[r+1]<<1|1)&a,n&&(_[r]|=(y[r+1]|y[r])<<1|1|y[r+1]),_[r]&O&&(E=b(t,{errors:n,currentLocation:o,expectedLocation:d,distance:s,ignoreLocation:l}),E<=p)){if(p=E,f=o,f<=d)break;c=Math.max(1,2*d-f)}}if(b(t,{errors:n+1,currentLocation:d,expectedLocation:d,distance:s,ignoreLocation:l})>p)break;y=_}const C={isMatch:f>=0,score:Math.max(.001,E)};if(m){const e=function(e=[],t=v.minMatchCharLength){let i=[],n=-1,s=-1,r=0;for(let o=e.length;r=t&&i.push([n,s]),n=-1)}return e[r-1]&&r-n>=t&&i.push([n,r-1]),i}(g,a);e.length?c&&(C.indices=e):C.isMatch=!1}return C}(e,t,d,{location:n+p,distance:s,threshold:r,findAllMatches:o,minMatchCharLength:a,includeMatches:i,ignoreLocation:c});f&&(u=!0),h+=m,f&&g&&(l=[...l,...g])}));let d={isMatch:u,score:u?h/this.chunks.length:1};return u&&i&&(d.indices=l),d}}class C{constructor(e){this.pattern=e}static isMultiMatch(e){return T(e,this.multiRegex)}static isSingleMatch(e){return T(e,this.singleRegex)}search(){}}function T(e,t){const i=e.match(t);return i?i[1]:null}class w extends C{constructor(e,{location:t=v.location,threshold:i=v.threshold,distance:n=v.distance,includeMatches:s=v.includeMatches,findAllMatches:r=v.findAllMatches,minMatchCharLength:o=v.minMatchCharLength,isCaseSensitive:a=v.isCaseSensitive,ignoreLocation:c=v.ignoreLocation}={}){super(e),this._bitapSearch=new O(e,{location:t,threshold:i,distance:n,includeMatches:s,findAllMatches:r,minMatchCharLength:o,isCaseSensitive:a,ignoreLocation:c})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(e){return this._bitapSearch.searchIn(e)}}class L extends C{constructor(e){super(e)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(e){let t,i=0;const n=[],s=this.pattern.length;for(;(t=e.indexOf(this.pattern,i))>-1;)i=t+s,n.push([t,i-1]);const r=!!n.length;return{isMatch:r,score:r?0:1,indices:n}}}const A=[class extends C{constructor(e){super(e)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(e){const t=e===this.pattern;return{isMatch:t,score:t?0:1,indices:[0,this.pattern.length-1]}}},L,class extends C{constructor(e){super(e)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(e){const t=e.startsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,this.pattern.length-1]}}},class extends C{constructor(e){super(e)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(e){const t=!e.startsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}},class extends C{constructor(e){super(e)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(e){const t=!e.endsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}},class extends C{constructor(e){super(e)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(e){const t=e.endsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[e.length-this.pattern.length,e.length-1]}}},class extends C{constructor(e){super(e)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(e){const t=-1===e.indexOf(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}},w],M=A.length,P=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,x=new Set([w.type,L.type]);const N=[];function D(e,t){for(let i=0,n=N.length;i!(!e[j]&&!e.$or),K=e=>({[j]:Object.keys(e).map((t=>({[t]:e[t]})))});function R(e,t,{auto:i=!0}={}){const r=e=>{let a=Object.keys(e);const c=(e=>!!e[F])(e);if(!c&&a.length>1&&!k(e))return r(K(e));if((e=>!n(e)&&o(e)&&!k(e))(e)){const n=c?e[F]:a[0],r=c?e.$val:e[n];if(!s(r))throw new Error((e=>`Invalid value for key ${e}`)(n));const o={keyId:g(n),pattern:r};return i&&(o.searcher=D(r,t)),o}let l={children:[],operator:a[0]};return a.forEach((t=>{const i=e[t];n(i)&&i.forEach((e=>{l.children.push(r(e))}))})),l};return k(e)||(e=K(e)),r(e)}function H(e,t){const i=e.matches;t.matches=[],a(i)&&i.forEach((e=>{if(!a(e.indices)||!e.indices.length)return;const{indices:i,value:n}=e;let s={indices:i,value:n};e.key&&(s.key=e.key.src),e.idx>-1&&(s.refIndex=e.idx),t.matches.push(s)}))}function Y(e,t){t.score=e.score}class B{constructor(e,t={},i){this.options={...v,...t},this.options.useExtendedSearch,this._keyStore=new p(this.options.keys),this.setCollection(e,i)}setCollection(e,t){if(this._docs=e,t&&!(t instanceof y))throw new Error("Incorrect 'index' type");this._myIndex=t||E(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(e){a(e)&&(this._docs.push(e),this._myIndex.add(e))}remove(e=(()=>!1)){const t=[];for(let i=0,n=this._docs.length;i{let i=1;e.matches.forEach((({key:e,norm:n,score:s})=>{const r=e?e.weight:null;i*=Math.pow(0===s&&r?Number.EPSILON:s,(r||1)*(t?1:n))})),e.score=i}))}(l,{ignoreFieldNorm:c}),o&&l.sort(a),r(t)&&t>-1&&(l=l.slice(0,t)),function(e,t,{includeMatches:i=v.includeMatches,includeScore:n=v.includeScore}={}){const s=[];return i&&s.push(H),n&&s.push(Y),e.map((e=>{const{idx:i}=e,n={item:t[i],refIndex:i};return s.length&&s.forEach((t=>{t(e,n)})),n}))}(l,this._docs,{includeMatches:i,includeScore:n})}_searchStringList(e){const t=D(e,this.options),{records:i}=this._myIndex,n=[];return i.forEach((({v:e,i,n:s})=>{if(!a(e))return;const{isMatch:r,score:o,indices:c}=t.searchIn(e);r&&n.push({item:e,idx:i,matches:[{score:o,value:e,norm:s,indices:c}]})})),n}_searchLogical(e){const t=R(e,this.options),i=(e,t,n)=>{if(!e.children){const{keyId:i,searcher:s}=e,r=this._findMatches({key:this._keyStore.get(i),value:this._myIndex.getValueForItemAtKeyId(t,i),searcher:s});return r&&r.length?[{idx:n,item:t,matches:r}]:[]}const s=[];for(let r=0,o=e.children.length;r{if(a(e)){let o=i(t,e,n);o.length&&(s[n]||(s[n]={idx:n,item:e,matches:[]},r.push(s[n])),o.forEach((({matches:e})=>{s[n].matches.push(...e)})))}})),r}_searchObjectList(e){const t=D(e,this.options),{keys:i,records:n}=this._myIndex,s=[];return n.forEach((({$:e,i:n})=>{if(!a(e))return;let r=[];i.forEach(((i,n)=>{r.push(...this._findMatches({key:i,value:e[n],searcher:t}))})),r.length&&s.push({idx:n,item:e,matches:r})})),s}_findMatches({key:e,value:t,searcher:i}){if(!a(t))return[];let s=[];if(n(t))t.forEach((({v:t,i:n,n:r})=>{if(!a(t))return;const{isMatch:o,score:c,indices:l}=i.searchIn(t);o&&s.push({score:c,key:e,value:t,idx:n,norm:r,indices:l})}));else{const{v:n,n:r}=t,{isMatch:o,score:a,indices:c}=i.searchIn(n);o&&s.push({score:a,key:e,value:n,norm:r,indices:c})}return s}}B.version="6.6.2",B.createIndex=E,B.parseIndex=function(e,{getFn:t=v.getFn,fieldNormWeight:i=v.fieldNormWeight}={}){const{keys:n,records:s}=e,r=new y({getFn:t,fieldNormWeight:i});return r.setKeys(n),r.setIndexRecords(s),r},B.config=v,B.parseQuery=R,function(...e){N.push(...e)}(class{constructor(e,{isCaseSensitive:t=v.isCaseSensitive,includeMatches:i=v.includeMatches,minMatchCharLength:n=v.minMatchCharLength,ignoreLocation:s=v.ignoreLocation,findAllMatches:r=v.findAllMatches,location:o=v.location,threshold:a=v.threshold,distance:c=v.distance}={}){this.query=null,this.options={isCaseSensitive:t,includeMatches:i,minMatchCharLength:n,findAllMatches:r,ignoreLocation:s,location:o,threshold:a,distance:c},this.pattern=t?e:e.toLowerCase(),this.query=function(e,t={}){return e.split("|").map((e=>{let i=e.trim().split(P).filter((e=>e&&!!e.trim())),n=[];for(let e=0,s=i.length;e{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";var e=i(529),t=i.n(e);(()=>{const e=document.getElementById("classifai-previewer-nonce");if(!e)return;const i=e.value,n={categoriesStatus:document.getElementById("classifai-settings-category").checked,keywordsStatus:document.getElementById("classifai-settings-keyword").checked,entitiesStatus:document.getElementById("classifai-settings-entity").checked,conceptsStatus:document.getElementById("classifai-settings-concept").checked},s={category:"categories",keyword:"keywords",entity:"entities",concept:"concepts"};document.querySelectorAll("#classifai-settings-category, #classifai-settings-keyword, #classifai-settings-entity, #classifai-settings-concept").forEach((e=>{e.addEventListener("change",(e=>{"classifai-settings-category"===e.target.id&&(n.categoriesStatus=e.target.checked),"classifai-settings-keyword"===e.target.id&&(n.keywordsStatus=e.target.checked),"classifai-settings-entity"===e.target.id&&(n.entitiesStatus=e.target.checked),"classifai-settings-concept"===e.target.id&&(n.conceptsStatus=e.target.checked);const t=e.target.id.split("-").at(-1);e.target.checked?document.querySelector(`.tax-row--${s[t]}`).classList.remove("tax-row--hide"):document.querySelector(`.tax-row--${s[t]}`).classList.add("tax-row--hide")}))})),document.getElementById("get-classifier-preview-data-btn").addEventListener("click",(function(e){const t=Number(document.querySelector("#classifai-settings-category_threshold").value),s=Number(document.querySelector("#classifai-settings-keyword_threshold").value),r=Number(document.querySelector("#classifai-settings-entity_threshold").value),o=Number(document.querySelector("#classifai-settings-concept_threshold").value),a=document.getElementById("classifai-preview-post-selector").value,c=document.getElementById("classifai-post-preview-wrapper"),l={categories:t,keywords:s,entities:r,concepts:o};e.target.closest(".button").classList.add("get-classifier-preview-data-btn--loading");const h=new FormData;h.append("action","get_post_classifier_preview_data"),h.append("post_id",a),h.append("nonce",i),fetch(`${ajaxurl}`,{method:"POST",body:h}).then((e=>e.json())).then((t=>{if(!t.success)return c.style.display="block",c.innerHTML=t.data,void e.target.closest(".button").classList.remove("get-classifier-preview-data-btn--loading");const{data:{categories:i=[],concepts:s=[],entities:r=[],keywords:o=[]}}=t,a=function(e={},t){return Object.keys(e).map((i=>({[i]:e[i].filter((e=>(e?.score&&100*e.score>t[i]||e?.relevance&&(e.relevance,t[i]),e)))})))}({categories:i,keywords:o,entities:r,concepts:s},l),h=function(e=[]){let t="";return e.forEach((e=>{Object.keys(e).forEach((i=>{t+=`
${i}
`,e[i].forEach((e=>{let i=0,n=0;e?.score?i=e.score:e?.relevance&&(i=e.relevance),e?.text?n=e.text:e?.label&&(n=e.label);const s=300+300*i;i=(100*i).toFixed(2),n=n.split("/").filter((e=>""!==e)).join(", "),t+=`
`,t+=`${i}% ${n}`,t+="
"})),t+="
"}))})),t}(a);c.style.display="block",c.innerHTML=h,e.target.closest(".button").classList.remove("get-classifier-preview-data-btn--loading")}))}));const r=document.getElementById("classifai-preview-post-selector"),o=new(t())(r,{noResultsText:""}),a=function(e,t,i){let n;return function(){const t=this,i=arguments;clearTimeout(n),n=setTimeout((function(){n=null,e.apply(t,i)}),300)}}((function(e){const t=[].slice.call(document.querySelectorAll('input[name*="classifai_watson_nlu[post_types"]:checked')).map((e=>e.id.split("-").at(-1))),n=[].slice.call(document.querySelectorAll('input[name*="classifai_watson_nlu[post_statuses"]:checked')).map((e=>e.id.split("-").at(-1))),s=new FormData;s.append("post_types",t),s.append("post_status",n),s.append("search",e.detail.value),s.append("action","classifai_get_post_search_results"),s.append("nonce",i),fetch(`${ajaxurl}`,{method:"POST",body:s}).then((e=>e.json())).then((e=>{const{data:t}=e;o.setChoices(t.map((e=>({value:e.ID,label:e.post_title}))),"value","label",!0)}))}));r.addEventListener("search",a)})(),document.addEventListener("DOMContentLoaded",(function(){const e=document.getElementById("_classifai_process_content");e&&(e.addEventListener("change",(function(){const e=document.querySelector(".classifai-clasify-post-wrapper");!0===this.checked?e.style.display="none":e.style.display="block"})),e.dispatchEvent(new Event("change")))}))})()})(); \ No newline at end of file diff --git a/dist/media-modal.asset.php b/dist/media-modal.asset.php index 05bc0d018..19ce6e5f8 100644 --- a/dist/media-modal.asset.php +++ b/dist/media-modal.asset.php @@ -1 +1 @@ - array(), 'version' => 'cfed6a8acb04d3a71390'); + array('wp-media-utils', 'wp-url'), 'version' => '4486a6d0da2d4050e63f'); diff --git a/dist/media-modal.css b/dist/media-modal.css index 8c777d21c..3c1d87f45 100644 --- a/dist/media-modal.css +++ b/dist/media-modal.css @@ -1 +1 @@ -.media-frame-content .generated-images,.media-frame-content .prompt-view{padding:0 16px}.media-frame-content .generated-images ul{display:flex;flex-wrap:wrap;gap:15px;list-style-type:none;margin:0;padding:0}.media-frame-content .generated-images li{margin-bottom:20px}.media-frame-content .generated-images .generated-image img{background-color:#f0f0f1;border:1px solid rgba(0,0,0,.1);box-shadow:inset 0 0 15px rgba(0,0,0,.1),inset 0 0 0 1px rgba(0,0,0,.05);display:block;height:auto;margin-bottom:10px;max-width:100%;-o-object-fit:cover;object-fit:cover;width:365px}.media-frame-content .generated-images .generated-image button{display:block;float:left;margin-right:10px}.media-frame-content .generated-images .generated-image .spinner{float:left;margin:6px}.media-frame-content .generated-images .spinner{float:none;visibility:hidden}.media-frame-content .generated-images .spinner.active{visibility:visible}.media-frame-content .generated-images .error{color:#cf2e2e;font-size:15px}.media-frame-content .prompt-view{margin-top:20px}.media-frame-content .prompt-view .prompt{margin-right:10px;padding:5px 8px;width:40%}.media-frame-content .prompt-view .error{color:#cf2e2e;display:block;font-size:15px;padding:10px 0} +.media-frame-content .generated-images,.media-frame-content .prompt-view{padding:0 16px}.media-frame-content .generated-images ul{display:flex;flex-wrap:wrap;gap:15px;list-style-type:none;margin:0;padding:0}.media-frame-content .generated-images li{margin-bottom:20px}.media-frame-content .generated-images .generated-image img{background-color:#f0f0f1;border:1px solid rgba(0,0,0,.1);box-shadow:inset 0 0 15px rgba(0,0,0,.1),inset 0 0 0 1px rgba(0,0,0,.05);display:block;height:auto;margin-bottom:10px;max-width:100%;-o-object-fit:cover;object-fit:cover;width:365px}.media-frame-content .generated-images .generated-image button{display:block;float:left;margin-right:10px}.media-frame-content .generated-images .generated-image button.is-tertiary{background:transparent;border:0;color:#007cba;cursor:pointer;outline:1px solid transparent;padding:6px;white-space:nowrap}.media-frame-content .generated-images .generated-image button.is-tertiary:hover:not(:disabled){box-shadow:inset 0 0 0 1px #006ba1;color:#006ba1}.media-frame-content .generated-images .generated-image button.is-tertiary:active:not(:disabled){background:#ddd;box-shadow:none;color:#006ba1}.media-frame-content .generated-images .generated-image .spinner{float:left;margin:6px}.media-frame-content .generated-images .spinner{float:none;visibility:hidden}.media-frame-content .generated-images .spinner.active{visibility:visible}.media-frame-content .generated-images .error{color:#cf2e2e;font-size:15px}.media-frame-content .prompt-view{margin-top:20px}.media-frame-content .prompt-view .prompt{margin-right:10px;padding:5px 8px;width:40%}.media-frame-content .prompt-view .error{color:#cf2e2e;display:block;font-size:15px;padding:10px 0} diff --git a/dist/media-modal.js b/dist/media-modal.js index 75ed8b035..f585b95b5 100644 --- a/dist/media-modal.js +++ b/dist/media-modal.js @@ -1 +1 @@ -(()=>{"use strict";const e=Backbone.Model.extend({defaults:{url:""}}),t=wp.media.View.extend({el:".error",initialize:function(e){this.$el.text(""),this.render(e.error)},render:function(e){return this.$el.text(e),this}}),i=Backbone.Collection.extend({model:e,url:wpApiSettings.root+classifaiDalleData.endpoint,makeRequest:function(e){this.fetch({type:"get",beforeSend:function(e){e.setRequestHeader("X-WP-Nonce",wpApiSettings.nonce)},data:{prompt:e,format:"b64_json"},reset:!0,error:function(e,i){new t({error:i.responseJSON.message})}})}}),{uploadMedia:n}=wp.mediaUtils,{cleanForSlug:a}=wp.url,r=wp.media.View.extend({tagName:"li",template:wp.template("dalle-image"),events:{"click .button-import":"import","click .button-import-insert":"importMediaLibrary","click .button-media-library":"loadMediaLibrary"},initialize:function(e){this.data=this.model.toJSON(),this.prompt=e.prompt,this.fileName=a(this.prompt)},render:function(){return this.$el.html(this.template(this.data)),this},import:async function(){var e;const t=this;this.enableLoadingState();const i=await this.convertImageToBlob(this.data.url);if(i)return await n({filesList:[new File([i],this.fileName+".png")],onFileChange:function(e){let[i]=e;i&&i.id&&(t.file=i,t.$(".button-import").removeClass("button-import").addClass("button-media-library").text(classifaiDalleData.buttonText),t.$(".button-import-insert").remove(),t.disableLoadingState())},onError:function(e){t.disableLoadingState(),t.$(".error").text(e)},additionalData:{post:null!==(e=wp.media.model.settings.post.id)&&void 0!==e?e:0,caption:classifaiDalleData.caption,alt_text:this.prompt}});this.$(".error").text(classifaiDalleData.errorText)},importMediaLibrary:async function(){await this.import(),await this.loadMediaLibrary()},loadMediaLibrary:async function(){this.enableLoadingState();const e=wp.media.model.Attachment;this.attachment=await e.get(this.file.id).fetch();const t={file:this.attachment,uploading:!0,date:new Date,filename:this.fileName+".png",menuOrder:0,loaded:0,percent:0,uploadedTo:wp.media.model.settings.post.id},i=wp.media.model.Attachment.create(t);wp.Uploader.queue.add(i),_.each(["file","loaded","size","percent"],(function(e){i.unset(e)})),i.set(_.extend(this.attachment,{uploading:!1})),wp.media.model.Attachment.get(this.file.id,i),wp.Uploader.queue.reset(),this.disableLoadingState(),jQuery("#menu-item-browse").click()},enableLoadingState:function(){const e=this.$el.parent("ul").find("button"),t=this.$(".spinner");e.prop("disabled",!0),t.addClass("active")},disableLoadingState:function(){const e=this.$el.parent("ul").find("button"),t=this.$(".spinner");e.prop("disabled",!1),t.removeClass("active")},convertImageToBlob:async function(e){const t=new Image;t.src=`data:image/png;base64,${e}`,t.crossOrigin="anonymous",await this.loadImage(t);const i=document.createElement("canvas");i.width=t.width,i.height=t.height;const n=i.getContext("2d");if(n)return n.drawImage(t,0,0),await new Promise((e=>{i.toBlob((t=>{t&&e(t)}),"image/jpeg")}))},loadImage:function(e){return new Promise((t=>e.onload=t))}}),o=wp.media.View.extend({el:".generated-images",initialize:function(e){this.collection=new i,this.prompt=e.prompt,this.listenTo(this.collection,"reset",this.renderAll),this.listenTo(this.collection,"error",this.error),this.collection.makeRequest(this.prompt),this.render()},render:function(){return this.$el.prev().find("button").prop("disabled",!0),this.$el.prev().find(".error").text(""),this.$("ul").empty(),this.$(".spinner").addClass("active"),this.$(".prompt-text").addClass("hidden"),this},renderImage:function(e){const t=new r({model:e,prompt:this.prompt});this.$("ul").append(t.render().el)},renderAll:function(){this.collection.length<1?(this.error(),this.$el.prev().find(".error").text(classifaiDalleData.errorText)):(this.$(".prompt-text").removeClass("hidden"),this.$(".prompt-text span").text(this.prompt),this.$(".spinner").removeClass("active"),this.collection.each(this.renderImage,this),this.$el.prev().find("button").prop("disabled",!1))},error:function(){this.$(".spinner").removeClass("active"),this.$el.prev().find("button").prop("disabled",!1)}}),s=wp.media.View.extend({template:wp.template("dalle-prompt"),events:{"click .button-generate":"promptRequest","keyup .prompt":"promptRequest"},render:function(){return this.$el.html(this.template()),this},promptRequest:function(e){let t="";13===e.which?t=e.target.value.trim():"BUTTON"===e.target.nodeName&&(t=e.target.parentElement.querySelector(".prompt").value.trim()),t&&new o({prompt:t})}}),l=wp.media.view.MediaFrame.Select;wp.media.view.MediaFrame.Select=l.extend({bindHandlers:function(){l.prototype.bindHandlers.apply(this,arguments),this.on("content:render:generate",this.generateContent,this)},browseRouter:function(e){l.prototype.browseRouter.apply(this,arguments),e.set({generate:{text:classifaiDalleData.tabText,priority:30}})},generateContent:function(){this.content.set((new s).render())}})})(); \ No newline at end of file +(()=>{"use strict";const e=Backbone.Model.extend({defaults:{url:""}}),t=wp.media.View.extend({el:".error",initialize:function(e){this.$el.text(""),this.render(e.error)},render:function(e){return this.$el.text(e),this}}),i=Backbone.Collection.extend({model:e,url:wpApiSettings.root+classifaiDalleData.endpoint,makeRequest:function(e){this.fetch({type:"get",beforeSend:function(e){e.setRequestHeader("X-WP-Nonce",wpApiSettings.nonce)},data:{prompt:e,format:"b64_json"},reset:!0,error:function(e,i){new t({error:i.responseJSON.message})}})}}),n=window.wp.mediaUtils,a=window.wp.url,r=wp.media.View.extend({tagName:"li",template:wp.template("dalle-image"),events:{"click .button-import":"import","click .button-import-insert":"importMediaLibrary","click .button-media-library":"loadMediaLibrary"},initialize:function(e){this.data=this.model.toJSON(),this.prompt=e.prompt,this.fileName=(0,a.cleanForSlug)(this.prompt)},render:function(){return this.$el.html(this.template(this.data)),this},import:async function(){var e;const t=this;this.enableLoadingState();const i=await this.convertImageToBlob(this.data.url);if(i)return await(0,n.uploadMedia)({filesList:[new File([i],this.fileName+".png")],onFileChange:function([e]){e&&e.id&&(t.file=e,t.$(".button-import").removeClass("button-import").addClass("button-media-library").text(classifaiDalleData.buttonText),t.$(".button-import-insert").remove(),t.disableLoadingState())},onError:function(e){t.disableLoadingState(),t.$(".error").text(e)},additionalData:{post:null!==(e=wp.media.model.settings.post.id)&&void 0!==e?e:0,caption:classifaiDalleData.caption,alt_text:this.prompt}});this.$(".error").text(classifaiDalleData.errorText)},importMediaLibrary:async function(){await this.import(),await this.loadMediaLibrary()},loadMediaLibrary:async function(){this.enableLoadingState();const e=wp.media.model.Attachment;this.attachment=await e.get(this.file.id).fetch();const t={file:this.attachment,uploading:!0,date:new Date,filename:this.fileName+".png",menuOrder:0,loaded:0,percent:0,uploadedTo:wp.media.model.settings.post.id},i=wp.media.model.Attachment.create(t);wp.Uploader.queue.add(i),_.each(["file","loaded","size","percent"],(function(e){i.unset(e)})),i.set(_.extend(this.attachment,{uploading:!1})),wp.media.model.Attachment.get(this.file.id,i),wp.Uploader.queue.reset(),this.disableLoadingState(),jQuery("#menu-item-browse").click()},enableLoadingState:function(){const e=this.$el.parent("ul").find("button"),t=this.$(".spinner");e.prop("disabled",!0),t.addClass("active")},disableLoadingState:function(){const e=this.$el.parent("ul").find("button"),t=this.$(".spinner");e.prop("disabled",!1),t.removeClass("active")},convertImageToBlob:async function(e){const t=new Image;t.src=`data:image/png;base64,${e}`,t.crossOrigin="anonymous",await this.loadImage(t);const i=document.createElement("canvas");i.width=t.width,i.height=t.height;const n=i.getContext("2d");if(n)return n.drawImage(t,0,0),await new Promise((e=>{i.toBlob((t=>{t&&e(t)}),"image/jpeg")}))},loadImage:function(e){return new Promise((t=>e.onload=t))}}),o=wp.media.View.extend({el:".generated-images",initialize:function(e){this.collection=new i,this.prompt=e.prompt,this.listenTo(this.collection,"reset",this.renderAll),this.listenTo(this.collection,"error",this.error),this.collection.makeRequest(this.prompt),this.render()},render:function(){return this.$el.prev().find("button").prop("disabled",!0),this.$el.prev().find(".error").text(""),this.$("ul").empty(),this.$(".spinner").addClass("active"),this.$(".prompt-text").addClass("hidden"),this},renderImage:function(e){const t=new r({model:e,prompt:this.prompt});this.$("ul").append(t.render().el)},renderAll:function(){this.collection.length<1?(this.error(),this.$el.prev().find(".error").text(classifaiDalleData.errorText)):(this.$(".prompt-text").removeClass("hidden"),this.$(".prompt-text span").text(this.prompt),this.$(".spinner").removeClass("active"),this.collection.each(this.renderImage,this),this.$el.prev().find("button").prop("disabled",!1))},error:function(){this.$(".spinner").removeClass("active"),this.$el.prev().find("button").prop("disabled",!1)}}),s=wp.media.View.extend({template:wp.template("dalle-prompt"),events:{"click .button-generate":"promptRequest","keyup .prompt":"promptRequest"},render:function(){return this.$el.html(this.template()),this},promptRequest:function(e){let t="";13===e.which?t=e.target.value.trim():"BUTTON"===e.target.nodeName&&(t=e.target.parentElement.querySelector(".prompt").value.trim()),t&&new o({prompt:t})}}),l=wp.media.view.MediaFrame.Select,d=wp.media.view.MediaFrame.Post;wp.media.view.MediaFrame.Select=l.extend({bindHandlers:function(){l.prototype.bindHandlers.apply(this,arguments),this.on("content:render:generate",this.generateContent,this)},browseRouter:function(e){l.prototype.browseRouter.apply(this,arguments),e.set({generate:{text:classifaiDalleData.tabText,priority:30}})},generateContent:function(){this.content.set((new s).render())}}),wp.media.view.MediaFrame.Post=d.extend({bindHandlers:function(){d.prototype.bindHandlers.apply(this,arguments),this.on("content:render:generate",this.generateContent,this)},browseRouter:function(e){d.prototype.browseRouter.apply(this,arguments),e.set({generate:{text:classifaiDalleData.tabText,priority:30}})},generateContent:function(){this.content.set((new s).render())}})})(); \ No newline at end of file diff --git a/dist/media.asset.php b/dist/media.asset.php index d2c7feae7..41e4a5e25 100644 --- a/dist/media.asset.php +++ b/dist/media.asset.php @@ -1 +1 @@ - array('wp-i18n'), 'version' => '9c0dc181eab8ae8565d0'); + array('wp-i18n'), 'version' => 'fa490b46d0f061e84110'); diff --git a/dist/media.js b/dist/media.js index b74c66631..7ca1c94e4 100644 --- a/dist/media.js +++ b/dist/media.js @@ -1 +1 @@ -(()=>{"use strict";const t=window.wp.i18n,{get:e}=lodash,a=a=>{let{button:n,endpoint:i,callback:s=!1,buttonText:c=(0,t.__)("Rescan","classifai")}=a;const d=n.getAttribute("data-id"),[l]=n.parentNode.getElementsByClassName("spinner"),[o]=n.parentNode.getElementsByClassName("error"),r=`${i}${d}`;n.setAttribute("disabled","disabled"),l.style.display="inline-block",l.classList.add("is-active"),o.style.display="none",wp.apiRequest({path:r}).then((t=>{n.removeAttribute("disabled"),l.style.display="none",l.classList.remove("is-active"),n.textContent=c,s&&s(t)}),(a=>{const i=e(a,"responseJSON",{code:"unknown_error",message:(0,t.__)("An unknown error occurred.","classifai")});l.style.display="none",l.classList.remove("is-active"),n.removeAttribute("disabled"),n.textContent=c,o.style.display="inline-block",o.textContent=`Error: ${i.message}`}))};!function(e){const n=()=>{const e=document.getElementById("classifai-rescan-alt-tags"),n=document.getElementById("classifai-rescan-image-tags"),i=document.getElementById("classifai-rescan-ocr"),s=document.getElementById("classifai-rescan-smart-crop"),c=document.getElementById("classifai-rescan-pdf"),d=document.getElementById("classifai-retranscribe");e&&e.addEventListener("click",(t=>a({button:t.target,endpoint:"/classifai/v1/alt-tags/",callback:t=>{const{enabledAltTextFields:e}=classifaiMediaVars;if(t){if(e.includes("alt")){var a;const e=null!==(a=document.getElementById("attachment-details-two-column-alt-text"))&&void 0!==a?a:document.getElementById("attachment-details-alt-text");e&&(e.value=t)}if(e.includes("caption")){var n;const e=null!==(n=document.getElementById("attachment-details-two-column-caption"))&&void 0!==n?n:document.getElementById("attachment-details-caption");e&&(e.value=t)}if(e.includes("description")){var i;const e=null!==(i=document.getElementById("attachment-details-two-column-description"))&&void 0!==i?i:document.getElementById("attachment-details-description");e&&(e.value=t)}}}}))),n&&n.addEventListener("click",(t=>a({button:t.target,endpoint:"/classifai/v1/image-tags/"}))),i&&i.addEventListener("click",(t=>a({button:t.target,endpoint:"/classifai/v1/ocr/",callback:t=>{if(t){var e;const a=null!==(e=document.getElementById("attachment-details-two-column-description"))&&void 0!==e?e:document.getElementById("attachment-details-description");a&&(a.value=t)}}}))),s&&s.addEventListener("click",(t=>a({button:t.target,endpoint:"/classifai/v1/smart-crop/"}))),c&&c.addEventListener("click",(e=>{const a=e.target.getAttribute("data-id");wp.apiRequest({path:`/classifai/v1/read-pdf/${a}`}),e.target.setAttribute("disabled","disabled"),e.target.textContent=(0,t.__)("Read API requested!","classifai")})),d&&d.addEventListener("click",(e=>a({button:e.target,endpoint:"/classifai/v1/openai/generate-transcript/",callback:t=>{if(t){var e;const a=null!==(e=document.getElementById("attachment-details-two-column-description"))&&void 0!==e?e:document.getElementById("attachment-details-description");a&&(a.value=t)}},buttonText:(0,t.__)("Re-transcribe","classifai")})))},i=()=>{const a=document.getElementById("classifai-rescan-pdf");if(!a)return;const n=a.getAttribute("data-id");e.ajax({url:ajaxurl,type:"POST",data:{action:"classifai_get_read_status",attachment_id:n,nonce:ClassifAI.ajax_nonce},success:e=>{e?.success&&(e?.data?.running?(a.setAttribute("disabled","disabled"),a.textContent=(0,t.__)("In progress!","classifai")):e?.data?.read&&(a.textContent=(0,t.__)("Rescan","classifai")))}})};e(document).ready((function(){wp.media&&wp.media.view.Modal.prototype.on("open",(function(){wp.media.frame.on("selection:toggle",n),wp.media.frame.on("selection:toggle",i)})),wp.media.frame&&(wp.media.frame.on("edit:attachment",n),wp.media.frame.on("edit:attachment",i)),wp.Uploader&&wp.Uploader.queue&&wp.Uploader.queue.on("reset",n)}))}(jQuery)})(); \ No newline at end of file +(()=>{"use strict";const t=window.wp.i18n,{get:e}=lodash,a=({button:a,endpoint:n,callback:i=!1,buttonText:s=(0,t.__)("Rescan","classifai")})=>{const c=a.getAttribute("data-id"),[d]=a.parentNode.getElementsByClassName("spinner"),[l]=a.parentNode.getElementsByClassName("error"),o=`${n}${c}`;a.setAttribute("disabled","disabled"),d.style.display="inline-block",d.classList.add("is-active"),l.style.display="none",wp.apiRequest({path:o}).then((t=>{a.removeAttribute("disabled"),d.style.display="none",d.classList.remove("is-active"),a.textContent=s,i&&i(t)}),(n=>{const i=e(n,"responseJSON",{code:"unknown_error",message:(0,t.__)("An unknown error occurred.","classifai")});d.style.display="none",d.classList.remove("is-active"),a.removeAttribute("disabled"),a.textContent=s,l.style.display="inline-block",l.textContent=`Error: ${i.message}`}))};!function(e){const n=()=>{const e=document.getElementById("classifai-rescan-alt-tags"),n=document.getElementById("classifai-rescan-image-tags"),i=document.getElementById("classifai-rescan-ocr"),s=document.getElementById("classifai-rescan-smart-crop"),c=document.getElementById("classifai-rescan-pdf"),d=document.getElementById("classifai-retranscribe");e&&e.addEventListener("click",(t=>a({button:t.target,endpoint:"/classifai/v1/alt-tags/",callback:t=>{const{enabledAltTextFields:e}=classifaiMediaVars;if(t){if(e.includes("alt")){var a;const e=null!==(a=document.getElementById("attachment-details-two-column-alt-text"))&&void 0!==a?a:document.getElementById("attachment-details-alt-text");e&&(e.value=t)}if(e.includes("caption")){var n;const e=null!==(n=document.getElementById("attachment-details-two-column-caption"))&&void 0!==n?n:document.getElementById("attachment-details-caption");e&&(e.value=t)}if(e.includes("description")){var i;const e=null!==(i=document.getElementById("attachment-details-two-column-description"))&&void 0!==i?i:document.getElementById("attachment-details-description");e&&(e.value=t)}}}}))),n&&n.addEventListener("click",(t=>a({button:t.target,endpoint:"/classifai/v1/image-tags/"}))),i&&i.addEventListener("click",(t=>a({button:t.target,endpoint:"/classifai/v1/ocr/",callback:t=>{if(t){var e;const a=null!==(e=document.getElementById("attachment-details-two-column-description"))&&void 0!==e?e:document.getElementById("attachment-details-description");a&&(a.value=t)}}}))),s&&s.addEventListener("click",(t=>a({button:t.target,endpoint:"/classifai/v1/smart-crop/"}))),c&&c.addEventListener("click",(e=>{const a=e.target.getAttribute("data-id");wp.apiRequest({path:`/classifai/v1/read-pdf/${a}`}),e.target.setAttribute("disabled","disabled"),e.target.textContent=(0,t.__)("Read API requested!","classifai")})),d&&d.addEventListener("click",(e=>a({button:e.target,endpoint:"/classifai/v1/openai/generate-transcript/",callback:t=>{if(t){var e;const a=null!==(e=document.getElementById("attachment-details-two-column-description"))&&void 0!==e?e:document.getElementById("attachment-details-description");a&&(a.value=t)}},buttonText:(0,t.__)("Re-transcribe","classifai")})))},i=()=>{const a=document.getElementById("classifai-rescan-pdf");if(!a)return;const n=a.getAttribute("data-id");e.ajax({url:ajaxurl,type:"POST",data:{action:"classifai_get_read_status",attachment_id:n,nonce:ClassifAI.ajax_nonce},success:e=>{e?.success&&(e?.data?.running?(a.setAttribute("disabled","disabled"),a.textContent=(0,t.__)("In progress!","classifai")):e?.data?.read&&(a.textContent=(0,t.__)("Rescan","classifai")))}})};e(document).ready((function(){wp.media&&wp.media.view.Modal.prototype.on("open",(function(){wp.media.frame.on("selection:toggle",n),wp.media.frame.on("selection:toggle",i)})),wp.media.frame&&(wp.media.frame.on("edit:attachment",n),wp.media.frame.on("edit:attachment",i)),wp.Uploader&&wp.Uploader.queue&&wp.Uploader.queue.on("reset",n)}))}(jQuery)})(); \ No newline at end of file diff --git a/dist/post-excerpt.asset.php b/dist/post-excerpt.asset.php index bba007ee0..d81ef3d97 100644 --- a/dist/post-excerpt.asset.php +++ b/dist/post-excerpt.asset.php @@ -1 +1 @@ - array('wp-components', 'wp-compose', 'wp-data', 'wp-edit-post', 'wp-editor', 'wp-element', 'wp-i18n', 'wp-plugins'), 'version' => 'cf8d93b1f0e1f6b91080'); + array('wp-components', 'wp-compose', 'wp-data', 'wp-edit-post', 'wp-editor', 'wp-element', 'wp-i18n', 'wp-plugins'), 'version' => '764b402ecd2a2c3902c6'); diff --git a/dist/post-excerpt.js b/dist/post-excerpt.js index 2f36ba040..927d8cf79 100644 --- a/dist/post-excerpt.js +++ b/dist/post-excerpt.js @@ -1 +1 @@ -(()=>{"use strict";const e=window.wp.element,t=window.wp.i18n,n=window.wp.data,s=window.wp.editPost,r=window.wp.editor,a=window.wp.plugins,i=window.wp.components,l=window.wp.compose,{get:o}=lodash,c=(0,l.compose)([(0,n.withSelect)((e=>({excerpt:e("core/editor").getEditedPostAttribute("excerpt")}))),(0,n.withDispatch)((e=>({onUpdateExcerpt(t){e("core/editor").editPost({excerpt:t})}})))])((function(n){let{excerpt:s,onUpdateExcerpt:r}=n;const{select:a}=wp.data,l=a("core/editor").getCurrentPostId(),c=""===s?(0,t.__)("Generate excerpt","classifai"):(0,t.__)("Re-generate excerpt","classifai"),p=a("core/edit-post").isPublishSidebarOpened();return(0,e.createElement)("div",{className:"editor-post-excerpt"},(0,e.createElement)(i.TextareaControl,{__nextHasNoMarginBottom:!0,label:p?null:(0,t.__)("Write an excerpt (optional)"),className:"editor-post-excerpt__textarea",onChange:e=>r(e),value:s}),!p&&(0,e.createElement)(i.ExternalLink,{href:(0,t.__)("https://wordpress.org/support/article/settings-sidebar/#excerpt")},(0,t.__)("Learn more about manual excerpts")),(0,e.createElement)(i.Button,{variant:"secondary","data-id":l,onClick:e=>(e=>{let{button:n,endpoint:s,callback:r=!1,buttonText:a=(0,t.__)("Rescan","classifai")}=e;const i=n.getAttribute("data-id"),[l]=n.parentNode.getElementsByClassName("spinner"),[c]=n.parentNode.getElementsByClassName("error"),p=`${s}${i}`;n.setAttribute("disabled","disabled"),l.style.display="inline-block",l.classList.add("is-active"),c.style.display="none",wp.apiRequest({path:p}).then((e=>{n.removeAttribute("disabled"),l.style.display="none",l.classList.remove("is-active"),n.textContent=a,r&&r(e)}),(e=>{const s=o(e,"responseJSON",{code:"unknown_error",message:(0,t.__)("An unknown error occurred.","classifai")});l.style.display="none",l.classList.remove("is-active"),n.removeAttribute("disabled"),n.textContent=a,c.style.display="inline-block",c.textContent=`Error: ${s.message}`}))})({button:e.target,endpoint:"/classifai/v1/openai/generate-excerpt/",callback:r,buttonText:c})},c),(0,e.createElement)("span",{className:"spinner",style:{display:"none",float:"none"}}),(0,e.createElement)("span",{className:"error",style:{display:"none",color:"#bc0b0b",paddingTop:"5px"}}))})),p=n=>{let{children:r}=n;const a=[(0,t.__)("Suggestion:"),(0,e.createElement)("span",{className:"editor-post-publish-panel__link",key:"label"},(0,t.__)("Generate excerpt","classifai"))];return(0,e.createElement)(s.PluginPrePublishPanel,{title:a,icon:"aside",initialOpen:!0},r)};class d extends e.Component{constructor(e){super(e),this.state={hadExcerptWhenOpeningThePanel:""!==e.excerpt}}componentDidUpdate(e){this.props.isPublishPanelOpen&&e.isPublishPanelOpen!==this.props.isPublishPanelOpen&&this.setState({hadExcerptWhenOpeningThePanel:""!==this.props.excerpt})}render(){return this.state.hadExcerptWhenOpeningThePanel?null:(0,e.createElement)(p,null,this.props.children)}}const u=(0,n.withSelect)((e=>({excerpt:e("core/editor").getEditedPostAttribute("excerpt"),isPublishPanelOpen:e("core/edit-post").isPublishSidebarOpened()})))(d);(0,n.dispatch)("core/edit-post").removeEditorPanel("post-excerpt"),(0,a.registerPlugin)("post-excerpt",{render:()=>(0,e.createElement)(r.PostExcerptCheck,null,(0,e.createElement)(s.PluginDocumentSettingPanel,{title:(0,t.__)("Excerpt")},(0,e.createElement)(c,null)),(0,e.createElement)(u,null,(0,e.createElement)(c,null)))})})(); \ No newline at end of file +(()=>{"use strict";const e=window.wp.element,t=window.wp.i18n,n=window.wp.data,s=window.wp.editPost,r=window.wp.editor,a=window.wp.plugins,i=window.wp.components,o=window.wp.compose,{get:l}=lodash,c=(0,o.compose)([(0,n.withSelect)((e=>({excerpt:e("core/editor").getEditedPostAttribute("excerpt")}))),(0,n.withDispatch)((e=>({onUpdateExcerpt(t){e("core/editor").editPost({excerpt:t})}})))])((function({excerpt:n,onUpdateExcerpt:s}){const{select:r}=wp.data,a=r("core/editor").getCurrentPostId(),o=""===n?(0,t.__)("Generate excerpt","classifai"):(0,t.__)("Re-generate excerpt","classifai"),c=r("core/edit-post").isPublishSidebarOpened();return(0,e.createElement)("div",{className:"editor-post-excerpt"},(0,e.createElement)(i.TextareaControl,{__nextHasNoMarginBottom:!0,label:c?null:(0,t.__)("Write an excerpt (optional)"),className:"editor-post-excerpt__textarea",onChange:e=>s(e),value:n}),!c&&(0,e.createElement)(i.ExternalLink,{href:(0,t.__)("https://wordpress.org/support/article/settings-sidebar/#excerpt")},(0,t.__)("Learn more about manual excerpts")),(0,e.createElement)(i.Button,{variant:"secondary","data-id":a,onClick:e=>(({button:e,endpoint:n,callback:s=!1,buttonText:r=(0,t.__)("Rescan","classifai")})=>{const a=e.getAttribute("data-id"),[i]=e.parentNode.getElementsByClassName("spinner"),[o]=e.parentNode.getElementsByClassName("error"),c=`${n}${a}`;e.setAttribute("disabled","disabled"),i.style.display="inline-block",i.classList.add("is-active"),o.style.display="none",wp.apiRequest({path:c}).then((t=>{e.removeAttribute("disabled"),i.style.display="none",i.classList.remove("is-active"),e.textContent=r,s&&s(t)}),(n=>{const s=l(n,"responseJSON",{code:"unknown_error",message:(0,t.__)("An unknown error occurred.","classifai")});i.style.display="none",i.classList.remove("is-active"),e.removeAttribute("disabled"),e.textContent=r,o.style.display="inline-block",o.textContent=`Error: ${s.message}`}))})({button:e.target,endpoint:"/classifai/v1/openai/generate-excerpt/",callback:s,buttonText:o})},o),(0,e.createElement)("span",{className:"spinner",style:{display:"none",float:"none"}}),(0,e.createElement)("span",{className:"error",style:{display:"none",color:"#bc0b0b",paddingTop:"5px"}}))})),p=({children:n})=>{const r=[(0,t.__)("Suggestion:"),(0,e.createElement)("span",{className:"editor-post-publish-panel__link",key:"label"},(0,t.__)("Generate excerpt","classifai"))];return(0,e.createElement)(s.PluginPrePublishPanel,{title:r,icon:"aside",initialOpen:!0},n)};class d extends e.Component{constructor(e){super(e),this.state={hadExcerptWhenOpeningThePanel:""!==e.excerpt}}componentDidUpdate(e){this.props.isPublishPanelOpen&&e.isPublishPanelOpen!==this.props.isPublishPanelOpen&&this.setState({hadExcerptWhenOpeningThePanel:""!==this.props.excerpt})}render(){return this.state.hadExcerptWhenOpeningThePanel?null:(0,e.createElement)(p,null,this.props.children)}}const u=(0,n.withSelect)((e=>({excerpt:e("core/editor").getEditedPostAttribute("excerpt"),isPublishPanelOpen:e("core/edit-post").isPublishSidebarOpened()})))(d);(0,n.dispatch)("core/edit-post").removeEditorPanel("post-excerpt"),(0,a.registerPlugin)("post-excerpt",{render:()=>(0,e.createElement)(r.PostExcerptCheck,null,(0,e.createElement)(s.PluginDocumentSettingPanel,{title:(0,t.__)("Excerpt")},(0,e.createElement)(c,null)),(0,e.createElement)(u,null,(0,e.createElement)(c,null)))})})(); \ No newline at end of file diff --git a/dist/post-status-info.asset.php b/dist/post-status-info.asset.php index de6f6756f..ac0bb5217 100644 --- a/dist/post-status-info.asset.php +++ b/dist/post-status-info.asset.php @@ -1 +1 @@ - array('wp-api-fetch', 'wp-components', 'wp-data', 'wp-edit-post', 'wp-editor', 'wp-element', 'wp-i18n', 'wp-plugins'), 'version' => '43513ba9ccf13060200f'); + array('wp-api-fetch', 'wp-components', 'wp-data', 'wp-edit-post', 'wp-editor', 'wp-element', 'wp-i18n', 'wp-plugins'), 'version' => 'cc7dfd2b6fbbd7084cf5'); diff --git a/dist/post-status-info.js b/dist/post-status-info.js index ddfffe7c8..ea02c1e98 100644 --- a/dist/post-status-info.js +++ b/dist/post-status-info.js @@ -1 +1 @@ -(()=>{"use strict";var e={n:t=>{var a=t&&t.__esModule?()=>t.default:()=>t;return e.d(a,{a}),a},d:(t,a)=>{for(var n in a)e.o(a,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:a[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};const t=window.wp.element,a=window.wp.data,n=window.wp.editPost,r=window.wp.editor,s=window.wp.components,l=window.wp.i18n,o=window.wp.plugins,i=window.wp.apiFetch;var c=e.n(i);const{classifaiChatGPTData:u}=window,d=e=>{let{error:a}=e;return a?(0,t.createElement)("div",{className:"error"},a):null};(0,o.registerPlugin)("classifai-status-info",{render:()=>{const[e,o]=(0,t.useState)(!1),[i,p]=(0,t.useState)(!1),[w,m]=(0,t.useState)(!1),[f,E]=(0,t.useState)([]);if(!u||!u.enabledFeatures)return null;if(u.noPermissions&&1===parseInt(u.noPermissions))return null;const P=(0,a.select)("core/editor").getCurrentPostId(),y=()=>p(!1)&&E([])&&m(!1);return(0,t.createElement)(n.PluginPostStatusInfo,{className:"classifai-post-status"},i&&(0,t.createElement)(s.Modal,{title:(0,l.__)("Select a title","classifai"),onRequestClose:y,isFullScreen:!1,className:"title-modal"},e&&(0,t.createElement)(s.Spinner,null),!e&&f&&(0,t.createElement)((e=>{let{data:n}=e;return n?(0,t.createElement)(t.Fragment,null,n.map(((e,n)=>(0,t.createElement)("div",{className:"classifai-title",key:n},(0,t.createElement)("textarea",{rows:"5"},e),(0,t.createElement)(s.Button,{variant:"secondary",onClick:()=>{(0,a.dispatch)("core/editor").editPost({title:e}),y()}},(0,l.__)("Select","classifai")))))):null}),{data:f}),!e&&w&&(0,t.createElement)(d,{error:w})),u.enabledFeatures.map((e=>{const a=e?.path+P;return(0,t.createElement)(r.PostTypeSupportCheck,{key:e?.feature,supportKeys:e?.feature},(0,t.createElement)(s.Button,{className:e?.feature,variant:"secondary",onClick:()=>(async e=>{o(!0),p(!0),c()({path:e}).then((e=>{E(e),m(!1),o(!1)}),(e=>{m(e?.message),E([]),o(!1)}))})(a)},e?.buttonText))})))}})})(); \ No newline at end of file +(()=>{"use strict";var e={n:t=>{var a=t&&t.__esModule?()=>t.default:()=>t;return e.d(a,{a}),a},d:(t,a)=>{for(var n in a)e.o(a,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:a[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};const t=window.wp.element,a=window.wp.data,n=window.wp.editPost,r=window.wp.editor,s=window.wp.components,l=window.wp.i18n,o=window.wp.plugins,i=window.wp.apiFetch;var c=e.n(i);const{classifaiChatGPTData:u}=window,d=({error:e})=>e?(0,t.createElement)("div",{className:"error"},e):null;(0,o.registerPlugin)("classifai-status-info",{render:()=>{const[e,o]=(0,t.useState)(!1),[i,p]=(0,t.useState)(!1),[w,m]=(0,t.useState)(!1),[f,E]=(0,t.useState)([]);if(!u||!u.enabledFeatures)return null;if(u.noPermissions&&1===parseInt(u.noPermissions))return null;const P=(0,a.select)("core/editor").getCurrentPostId(),y=()=>p(!1)&&E([])&&m(!1);return(0,t.createElement)(n.PluginPostStatusInfo,{className:"classifai-post-status"},i&&(0,t.createElement)(s.Modal,{title:(0,l.__)("Select a title","classifai"),onRequestClose:y,isFullScreen:!1,className:"title-modal"},e&&(0,t.createElement)(s.Spinner,null),!e&&f&&(0,t.createElement)((({data:e})=>e?(0,t.createElement)(t.Fragment,null,e.map(((e,n)=>(0,t.createElement)("div",{className:"classifai-title",key:n},(0,t.createElement)("textarea",{rows:"5"},e),(0,t.createElement)(s.Button,{variant:"secondary",onClick:()=>{(0,a.dispatch)("core/editor").editPost({title:e}),y()}},(0,l.__)("Select","classifai")))))):null),{data:f}),!e&&w&&(0,t.createElement)(d,{error:w})),u.enabledFeatures.map((e=>{const a=e?.path+P;return(0,t.createElement)(r.PostTypeSupportCheck,{key:e?.feature,supportKeys:e?.feature},(0,t.createElement)(s.Button,{className:e?.feature,variant:"secondary",onClick:()=>(async e=>{o(!0),p(!0),c()({path:e}).then((e=>{E(e),m(!1),o(!1)}),(e=>{m(e?.message),E([]),o(!1)}))})(a)},e?.buttonText))})))}})})(); \ No newline at end of file diff --git a/dist/recommended-content-block.asset.php b/dist/recommended-content-block.asset.php index 37d981eaf..2b06451fa 100644 --- a/dist/recommended-content-block.asset.php +++ b/dist/recommended-content-block.asset.php @@ -1 +1 @@ - array('react', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-core-data', 'wp-data', 'wp-element', 'wp-i18n', 'wp-primitives', 'wp-server-side-render'), 'version' => 'eba04d2b0607aab9c7ba'); + array('react', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-core-data', 'wp-data', 'wp-element', 'wp-i18n', 'wp-primitives', 'wp-server-side-render'), 'version' => '501cbbd0d2fb22ad2bfc'); diff --git a/dist/recommended-content-block.js b/dist/recommended-content-block.js index 7cc26819e..d67f06d7a 100644 --- a/dist/recommended-content-block.js +++ b/dist/recommended-content-block.js @@ -1 +1 @@ -(()=>{"use strict";var e={n:t=>{var n=t&&t.__esModule?()=>t.default:()=>t;return e.d(n,{a:n}),n},d:(t,n)=>{for(var a in n)e.o(n,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:n[a]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};const t=window.wp.i18n,n=window.wp.blocks,a=window.wp.element,l=window.wp.components,o=window.wp.blockEditor,s=window.wp.primitives,r=(0,a.createElement)(s.SVG,{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},(0,a.createElement)(s.Path,{d:"M4 4v1.5h16V4H4zm8 8.5h8V11h-8v1.5zM4 20h16v-1.5H4V20zm4-8c0-1.1-.9-2-2-2s-2 .9-2 2 .9 2 2 2 2-.9 2-2z"})),i=(0,a.createElement)(s.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(s.Path,{d:"m3 5c0-1.10457.89543-2 2-2h13.5c1.1046 0 2 .89543 2 2v13.5c0 1.1046-.8954 2-2 2h-13.5c-1.10457 0-2-.8954-2-2zm2-.5h6v6.5h-6.5v-6c0-.27614.22386-.5.5-.5zm-.5 8v6c0 .2761.22386.5.5.5h6v-6.5zm8 0v6.5h6c.2761 0 .5-.2239.5-.5v-6zm0-8v6.5h6.5v-6c0-.27614-.2239-.5-.5-.5z",fillRule:"evenodd",clipRule:"evenodd"})),c=window.wp.data,d=window.wp.serverSideRender;var m=e.n(d);const u=window.wp.coreData,p=e=>{const t=e?.reduce(((e,t)=>{const{mapById:n,mapByName:a,names:l}=e;return n[t.id]=t,a[t.name]=t,l.push(t.name),e}),{mapById:{},mapByName:{},names:[]});return{entities:e,...t}},g=e=>{let{onChange:t,query:n}=e;const o=(s=n.contentPostType,(0,c.useSelect)((e=>{const{getTaxonomies:t}=e(u.store);return t({type:s,per_page:-1,context:"view"})}),[s]));var s;const r=(0,c.useSelect)((e=>{const{getEntityRecords:t}=e(u.store),n={per_page:100},a=o?.map((e=>{let{slug:a,name:l}=e;const o=t("taxonomy",a,n);return{slug:a,name:l,terms:p(o)}}));return a}),[o]),i=e=>{const t=r.find((t=>{let{slug:n}=t;return n===e}));return t?(n.taxQuery?.[e]||[]).reduce(((e,n)=>{const a=t.terms.mapById[n];return a&&e.push({id:n,value:a.name}),e}),[]):[]};return(0,a.createElement)(a.Fragment,null,!!r?.length&&r.map((e=>{let{slug:o,name:s,terms:c}=e;return c?.names?.length?(0,a.createElement)(l.FormTokenField,{key:o,label:s,value:i(o),suggestions:c.names,onChange:(d=o,e=>{const a=r.find((e=>{let{slug:t}=e;return t===d}));if(!a)return;const l=Array.from(e.reduce(((e,t)=>{const n=((e,t)=>{const n=t?.id||e[t]?.id;if(n)return n;const a=t.toLocaleLowerCase();for(const t in e)if(t.toLocaleLowerCase()===a)return e[t].id})(a.terms.mapByName,t);return n&&e.add(n),e}),new Set)),o={...n.taxQuery,[d]:l};t({taxQuery:o})})}):null;var d})))},y=JSON.parse('{"u2":"classifai/recommended-content-block"}'),h=window.React;var w;function v(){return v=Object.assign?Object.assign.bind():function(e){for(var t=1;t{const{attributes:n,setAttributes:s}=e,{columns:d=3,displayLayout:p="grid",numberOfItems:y=3,contentPostType:h,taxQuery:w,displayAuthor:v,displayFeaturedImage:f,displayPostDate:_,displayPostExcerpt:b,addLinkToFeaturedImage:C}=n,E=(0,c.useSelect)((e=>e("core/editor").getCurrentPostId())),P=(0,o.useBlockProps)(),{postTypesTaxonomiesMap:x,postTypesSelectOptions:k}=(()=>{const e=(0,c.useSelect)((e=>{const{getPostTypes:t}=e(u.store),n=["attachment"],a=t({per_page:-1})?.filter((e=>{let{viewable:t,slug:a}=e;return t&&!n.includes(a)}));return a}),[]);return{postTypesTaxonomiesMap:(0,a.useMemo)((()=>{if(e?.length)return e.reduce(((e,t)=>(e[t.slug]=t.taxonomies,e)),{})}),[e]),postTypesSelectOptions:(0,a.useMemo)((()=>(e||[]).map((e=>{let{labels:t,slug:n}=e;return{label:t.singular_name,value:n}}))),[e])}})(),T=[{icon:r,title:(0,t.__)("List view","classifai"),onClick:()=>s({displayLayout:"list"}),isActive:"list"===p},{icon:i,title:(0,t.__)("Grid view"),onClick:()=>s({displayLayout:"grid"}),isActive:"grid"===p}];return(0,a.createElement)("div",P,(0,a.createElement)(o.BlockControls,null,(0,a.createElement)(l.ToolbarGroup,{controls:T})),(0,a.createElement)(o.InspectorControls,null,(0,a.createElement)(l.PanelBody,{title:(0,t.__)("Recommended Content Filters","classifai")},k&&(0,a.createElement)(l.SelectControl,{label:(0,t.__)("Post type","classifai"),value:h,options:k,onChange:e=>{const t={contentPostType:e},n=x[e],a=Object.entries(w||{}).reduce(((e,t)=>{let[a,l]=t;return n.includes(a)&&(e[a]=l),e}),{});t.taxQuery=Object.keys(a).length?a:void 0,s(t)}}),k&&(0,a.createElement)(g,{onChange:s,query:n})),(0,a.createElement)(l.PanelBody,{title:(0,t.__)("Settings","classifai")},(0,a.createElement)(l.RangeControl,{label:(0,t.__)("Number of items","classifai"),value:y,onChange:e=>s({numberOfItems:e}),min:1,max:50,required:!0}),"grid"===p&&(0,a.createElement)(l.RangeControl,{label:(0,t.__)("Columns","classifai"),value:d,onChange:e=>s({columns:e}),min:2,max:6,required:!0})),(0,a.createElement)(l.PanelBody,{title:(0,t.__)("Post content settings","classifai")},(0,a.createElement)(l.ToggleControl,{label:(0,t.__)("Post excerpt","classifai"),checked:b,onChange:e=>s({displayPostExcerpt:e})})),(0,a.createElement)(l.PanelBody,{title:(0,t.__)("Post meta settings","classifai")},(0,a.createElement)(l.ToggleControl,{label:(0,t.__)("Display author name","classifai"),checked:v,onChange:e=>s({displayAuthor:e})}),(0,a.createElement)(l.ToggleControl,{label:(0,t.__)("Display post date","classifai"),checked:_,onChange:e=>s({displayPostDate:e})})),(0,a.createElement)(l.PanelBody,{title:(0,t.__)("Featured image settings","classifai")},(0,a.createElement)(l.ToggleControl,{label:(0,t.__)("Display featured image","classifai"),checked:f,onChange:e=>s({displayFeaturedImage:e})}),f&&(0,a.createElement)(l.ToggleControl,{label:(0,t.__)("Add link to featured image","classifai"),checked:C,onChange:e=>s({addLinkToFeaturedImage:e})}))),!h&&(0,a.createElement)(l.Placeholder,{label:(0,t.__)("ClassifAI Recommended Content","classifai")},(0,a.createElement)("p",null,(0,t.__)("Please select Post type for this Recommended Content block on the sidebar settings.","classifai"))),h&&(0,a.createElement)(m(),{block:"classifai/recommended-content-block",attributes:{addLinkToFeaturedImage:C,columns:d,contentPostType:h,displayAuthor:v,displayFeaturedImage:f,displayLayout:p,displayPostDate:_,displayPostExcerpt:b,numberOfItems:y,taxQuery:w,excludeId:E||0}}))},save:()=>null,icon:function(e){return h.createElement("svg",v({width:20,height:15,viewBox:"0 0 61 46",fill:"none",xmlns:"http://www.w3.org/2000/svg"},e),w||(w=h.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M3.52 0C1.575 0 0 1.584 0 3.538v38.924C0 44.416 1.576 46 3.52 46h53.96c1.944 0 3.52-1.584 3.52-3.538V3.538C61 1.584 59.424 0 57.48 0H3.52Zm13.189 8.138h4.739L33.58 39.554h-6.056l-3.492-9.04H13.97l-3.453 9.04h-5.96L16.709 8.138Zm2.38 8.563c-.104.34-.211.672-.319.997l-.012.036-2.76 7.406h6.148l-2.745-7.455-.312-.984Zm21.227-8.563h12.59v4.015l-3.413.819V34.63l3.413.779v4.024h-12.59V35.41l3.413-.78V12.972l-3.413-.818V8.138Z",fill:"#1e1e1e"})))}})})(); \ No newline at end of file +(()=>{"use strict";var e={n:t=>{var n=t&&t.__esModule?()=>t.default:()=>t;return e.d(n,{a:n}),n},d:(t,n)=>{for(var a in n)e.o(n,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:n[a]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};const t=window.wp.i18n,n=window.wp.blocks,a=window.wp.element,l=window.wp.components,o=window.wp.blockEditor,s=window.wp.primitives,r=(0,a.createElement)(s.SVG,{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},(0,a.createElement)(s.Path,{d:"M4 4v1.5h16V4H4zm8 8.5h8V11h-8v1.5zM4 20h16v-1.5H4V20zm4-8c0-1.1-.9-2-2-2s-2 .9-2 2 .9 2 2 2 2-.9 2-2z"})),i=(0,a.createElement)(s.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(s.Path,{d:"m3 5c0-1.10457.89543-2 2-2h13.5c1.1046 0 2 .89543 2 2v13.5c0 1.1046-.8954 2-2 2h-13.5c-1.10457 0-2-.8954-2-2zm2-.5h6v6.5h-6.5v-6c0-.27614.22386-.5.5-.5zm-.5 8v6c0 .2761.22386.5.5.5h6v-6.5zm8 0v6.5h6c.2761 0 .5-.2239.5-.5v-6zm0-8v6.5h6.5v-6c0-.27614-.2239-.5-.5-.5z",fillRule:"evenodd",clipRule:"evenodd"})),c=window.wp.data,d=window.wp.serverSideRender;var m=e.n(d);const u=window.wp.coreData,p=e=>{const t=e?.reduce(((e,t)=>{const{mapById:n,mapByName:a,names:l}=e;return n[t.id]=t,a[t.name]=t,l.push(t.name),e}),{mapById:{},mapByName:{},names:[]});return{entities:e,...t}},g=({onChange:e,query:t})=>{const n=(o=t.contentPostType,(0,c.useSelect)((e=>{const{getTaxonomies:t}=e(u.store);return t({type:o,per_page:-1,context:"view"})}),[o]));var o;const s=(0,c.useSelect)((e=>{const{getEntityRecords:t}=e(u.store),a={per_page:100},l=n?.map((({slug:e,name:n})=>{const l=t("taxonomy",e,a);return{slug:e,name:n,terms:p(l)}}));return l}),[n]),r=e=>{const n=s.find((({slug:t})=>t===e));return n?(t.taxQuery?.[e]||[]).reduce(((e,t)=>{const a=n.terms.mapById[t];return a&&e.push({id:t,value:a.name}),e}),[]):[]};return(0,a.createElement)(a.Fragment,null,!!s?.length&&s.map((({slug:n,name:o,terms:i})=>{return i?.names?.length?(0,a.createElement)(l.FormTokenField,{key:n,label:o,value:r(n),suggestions:i.names,onChange:(c=n,n=>{const a=s.find((({slug:e})=>e===c));if(!a)return;const l=Array.from(n.reduce(((e,t)=>{const n=((e,t)=>{const n=t?.id||e[t]?.id;if(n)return n;const a=t.toLocaleLowerCase();for(const t in e)if(t.toLocaleLowerCase()===a)return e[t].id})(a.terms.mapByName,t);return n&&e.add(n),e}),new Set)),o={...t.taxQuery,[c]:l};e({taxQuery:o})})}):null;var c})))},y=JSON.parse('{"u2":"classifai/recommended-content-block"}'),h=window.React;var w;function v(){return v=Object.assign?Object.assign.bind():function(e){for(var t=1;t{const{attributes:n,setAttributes:s}=e,{columns:d=3,displayLayout:p="grid",numberOfItems:y=3,contentPostType:h,taxQuery:w,displayAuthor:v,displayFeaturedImage:f,displayPostDate:_,displayPostExcerpt:b,addLinkToFeaturedImage:C}=n,E=(0,c.useSelect)((e=>e("core/editor").getCurrentPostId())),P=(0,o.useBlockProps)(),{postTypesTaxonomiesMap:x,postTypesSelectOptions:k}=(()=>{const e=(0,c.useSelect)((e=>{const{getPostTypes:t}=e(u.store),n=["attachment"],a=t({per_page:-1})?.filter((({viewable:e,slug:t})=>e&&!n.includes(t)));return a}),[]);return{postTypesTaxonomiesMap:(0,a.useMemo)((()=>{if(e?.length)return e.reduce(((e,t)=>(e[t.slug]=t.taxonomies,e)),{})}),[e]),postTypesSelectOptions:(0,a.useMemo)((()=>(e||[]).map((({labels:e,slug:t})=>({label:e.singular_name,value:t})))),[e])}})(),T=[{icon:r,title:(0,t.__)("List view","classifai"),onClick:()=>s({displayLayout:"list"}),isActive:"list"===p},{icon:i,title:(0,t.__)("Grid view"),onClick:()=>s({displayLayout:"grid"}),isActive:"grid"===p}];return(0,a.createElement)("div",P,(0,a.createElement)(o.BlockControls,null,(0,a.createElement)(l.ToolbarGroup,{controls:T})),(0,a.createElement)(o.InspectorControls,null,(0,a.createElement)(l.PanelBody,{title:(0,t.__)("Recommended Content Filters","classifai")},k&&(0,a.createElement)(l.SelectControl,{label:(0,t.__)("Post type","classifai"),value:h,options:k,onChange:e=>{const t={contentPostType:e},n=x[e],a=Object.entries(w||{}).reduce(((e,[t,a])=>(n.includes(t)&&(e[t]=a),e)),{});t.taxQuery=Object.keys(a).length?a:void 0,s(t)}}),k&&(0,a.createElement)(g,{onChange:s,query:n})),(0,a.createElement)(l.PanelBody,{title:(0,t.__)("Settings","classifai")},(0,a.createElement)(l.RangeControl,{label:(0,t.__)("Number of items","classifai"),value:y,onChange:e=>s({numberOfItems:e}),min:1,max:50,required:!0}),"grid"===p&&(0,a.createElement)(l.RangeControl,{label:(0,t.__)("Columns","classifai"),value:d,onChange:e=>s({columns:e}),min:2,max:6,required:!0})),(0,a.createElement)(l.PanelBody,{title:(0,t.__)("Post content settings","classifai")},(0,a.createElement)(l.ToggleControl,{label:(0,t.__)("Post excerpt","classifai"),checked:b,onChange:e=>s({displayPostExcerpt:e})})),(0,a.createElement)(l.PanelBody,{title:(0,t.__)("Post meta settings","classifai")},(0,a.createElement)(l.ToggleControl,{label:(0,t.__)("Display author name","classifai"),checked:v,onChange:e=>s({displayAuthor:e})}),(0,a.createElement)(l.ToggleControl,{label:(0,t.__)("Display post date","classifai"),checked:_,onChange:e=>s({displayPostDate:e})})),(0,a.createElement)(l.PanelBody,{title:(0,t.__)("Featured image settings","classifai")},(0,a.createElement)(l.ToggleControl,{label:(0,t.__)("Display featured image","classifai"),checked:f,onChange:e=>s({displayFeaturedImage:e})}),f&&(0,a.createElement)(l.ToggleControl,{label:(0,t.__)("Add link to featured image","classifai"),checked:C,onChange:e=>s({addLinkToFeaturedImage:e})}))),!h&&(0,a.createElement)(l.Placeholder,{label:(0,t.__)("ClassifAI Recommended Content","classifai")},(0,a.createElement)("p",null,(0,t.__)("Please select Post type for this Recommended Content block on the sidebar settings.","classifai"))),h&&(0,a.createElement)(m(),{block:"classifai/recommended-content-block",attributes:{addLinkToFeaturedImage:C,columns:d,contentPostType:h,displayAuthor:v,displayFeaturedImage:f,displayLayout:p,displayPostDate:_,displayPostExcerpt:b,numberOfItems:y,taxQuery:w,excludeId:E||0}}))},save:()=>null,icon:function(e){return h.createElement("svg",v({width:20,height:15,viewBox:"0 0 61 46",fill:"none",xmlns:"http://www.w3.org/2000/svg"},e),w||(w=h.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M3.52 0C1.575 0 0 1.584 0 3.538v38.924C0 44.416 1.576 46 3.52 46h53.96c1.944 0 3.52-1.584 3.52-3.538V3.538C61 1.584 59.424 0 57.48 0H3.52Zm13.189 8.138h4.739L33.58 39.554h-6.056l-3.492-9.04H13.97l-3.453 9.04h-5.96L16.709 8.138Zm2.38 8.563c-.104.34-.211.672-.319.997l-.012.036-2.76 7.406h6.148l-2.745-7.455-.312-.984Zm21.227-8.563h12.59v4.015l-3.413.819V34.63l3.413.779v4.024h-12.59V35.41l3.413-.78V12.972l-3.413-.818V8.138Z",fill:"#1e1e1e"})))}})})(); \ No newline at end of file diff --git a/includes/Classifai/Admin/BulkActions.php b/includes/Classifai/Admin/BulkActions.php index 51c577caf..28b95f554 100644 --- a/includes/Classifai/Admin/BulkActions.php +++ b/includes/Classifai/Admin/BulkActions.php @@ -2,6 +2,7 @@ namespace Classifai\Admin; use Classifai\Providers\Azure\ComputerVision; +use Classifai\Providers\Azure\TextToSpeech; use Classifai\Providers\OpenAI\Embeddings; use Classifai\Providers\OpenAI\Whisper; use Classifai\Providers\OpenAI\Whisper\Transcribe; @@ -41,6 +42,11 @@ public function can_register() { */ private $whisper; + /** + * @var \Classifai\Providers\Azure\TextToSpeech + */ + private $text_to_speech; + /** * Register the actions needed. */ @@ -55,25 +61,32 @@ public function register() { * Register bulk actions for language processing. */ public function register_language_processing_hooks() { - $this->embeddings = new Embeddings( false ); - $settings = $this->embeddings->get_settings(); - $embeddings_post_types = []; - $nlu_post_types = get_supported_post_types(); - - // Set up the save post handler if we have any post types for NLU. - if ( ! empty( $nlu_post_types ) ) { + $this->embeddings = new Embeddings( false ); + $embedding_settings = $this->embeddings->get_settings(); + $embeddings_post_types = []; + $nlu_post_types = get_supported_post_types(); + $this->text_to_speech = new TextToSpeech( false ); + $text_to_speech_post_types = $this->text_to_speech->get_supported_post_types(); + + // Set up the save post handler if we have any post types. + if ( ! empty( $nlu_post_types ) || ! empty( $text_to_speech_post_types ) ) { $this->save_post_handler = new SavePostHandler(); } // Set up the embeddings post types if the feature is enabled. Otherwise clear our embeddings handler. - if ( isset( $settings['enable_classification'] ) && 1 === (int) $settings['enable_classification'] ) { + if ( isset( $embedding_settings['enable_classification'] ) && 1 === (int) $embedding_settings['enable_classification'] ) { $embeddings_post_types = $this->embeddings->supported_post_types(); } else { $this->embeddings = null; } + // Clear our TextToSpeech handler if no post types are set up. + if ( empty( $text_to_speech_post_types ) ) { + $this->text_to_speech = null; + } + // Merge our post types together and make them unique. - $post_types = array_unique( array_merge( $embeddings_post_types, $nlu_post_types ) ); + $post_types = array_unique( array_merge( $embeddings_post_types, $nlu_post_types, $text_to_speech_post_types ) ); if ( empty( $post_types ) ) { return; @@ -104,14 +117,29 @@ public function register_image_processing_hooks() { } /** - * Register Classifai bulk action. + * Register language processing bulk actions. * * @param array $bulk_actions Current bulk actions. * * @return array */ public function register_bulk_actions( $bulk_actions ) { - $bulk_actions['classify'] = __( 'Classify', 'classifai' ); + $nlu_post_types = get_supported_post_types(); + + if ( + ! empty( $nlu_post_types ) || + ( is_a( $this->embeddings, '\Classifai\Providers\OpenAI\Embeddings' ) && ! empty( $this->embeddings->supported_post_types() ) ) + ) { + $bulk_actions['classify'] = __( 'Classify', 'classifai' ); + } + + if ( + is_a( $this->text_to_speech, '\Classifai\Providers\Azure\TextToSpeech' ) && + in_array( get_current_screen()->post_type, $this->text_to_speech->get_supported_post_types(), true ) + ) { + $bulk_actions['text_to_speech'] = __( 'Text to speech', 'classifai' ); + } + return $bulk_actions; } @@ -145,7 +173,7 @@ public function register_media_bulk_actions( $bulk_actions ) { } /** - * Handle bulk actions. + * Handle language processing bulk actions. * * @param string $redirect_to Redirect URL after bulk actions. * @param string $doaction Action ID. @@ -154,24 +182,44 @@ public function register_media_bulk_actions( $bulk_actions ) { * @return string */ public function bulk_action_handler( $redirect_to, $doaction, $post_ids ) { - if ( 'classify' !== $doaction ) { + if ( + empty( $post_ids ) || + ! in_array( $doaction, [ 'classify', 'text_to_speech' ], true ) + ) { return $redirect_to; } + $action = ''; + foreach ( $post_ids as $post_id ) { - // Handle NLU classification. - if ( is_a( $this->save_post_handler, '\Classifai\Admin\SavePostHandler' ) ) { - $this->save_post_handler->classify( $post_id ); + if ( 'classify' === $doaction ) { + // Handle NLU classification. + if ( is_a( $this->save_post_handler, '\Classifai\Admin\SavePostHandler' ) ) { + $action = 'classified'; + $this->save_post_handler->classify( $post_id ); + } + + // Handle OpenAI Embeddings classification. + if ( is_a( $this->embeddings, '\Classifai\Providers\OpenAI\Embeddings' ) ) { + $action = 'classified'; + $this->embeddings->generate_embeddings_for_post( $post_id ); + } } - // Handle OpenAI Embeddings classification. - if ( is_a( $this->embeddings, '\Classifai\Providers\OpenAI\Embeddings' ) ) { - $this->embeddings->generate_embeddings_for_post( $post_id ); + if ( 'text_to_speech' === $doaction ) { + // Handle Azure Text to Speech generation. + if ( + is_a( $this->text_to_speech, '\Classifai\Providers\Azure\TextToSpeech' ) && + is_a( $this->save_post_handler, '\Classifai\Admin\SavePostHandler' ) + ) { + $action = 'text_to_speech'; + $this->save_post_handler->synthesize_speech( $post_id ); + } } } - $redirect_to = remove_query_arg( [ 'bulk_classified', 'bulk_scanned', 'bulk_cropped', 'bulk_transcribed' ], $redirect_to ); - $redirect_to = add_query_arg( 'bulk_classified', count( $post_ids ), $redirect_to ); + $redirect_to = remove_query_arg( [ 'bulk_classified', 'bulk_text_to_speech', 'bulk_scanned', 'bulk_cropped', 'bulk_transcribed' ], $redirect_to ); + $redirect_to = add_query_arg( rawurlencode( "bulk_{$action}" ), count( $post_ids ), $redirect_to ); return esc_url_raw( $redirect_to ); } @@ -213,7 +261,7 @@ public function media_bulk_action_handler( $redirect_to, $doaction, $attachment_ } } - $redirect_to = remove_query_arg( [ 'bulk_classified', 'bulk_scanned', 'bulk_cropped', 'bulk_transcribed' ], $redirect_to ); + $redirect_to = remove_query_arg( [ 'bulk_classified', 'bulk_text_to_speech', 'bulk_scanned', 'bulk_cropped', 'bulk_transcribed' ], $redirect_to ); $redirect_to = add_query_arg( rawurlencode( "bulk_{$action}" ), count( $attachment_ids ), $redirect_to ); return esc_url_raw( $redirect_to ); @@ -224,19 +272,25 @@ public function media_bulk_action_handler( $redirect_to, $doaction, $attachment_ */ public function bulk_action_admin_notice() { - $classified = ! empty( $_GET['bulk_classified'] ) ? intval( wp_unslash( $_GET['bulk_classified'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended - $scanned = ! empty( $_GET['bulk_scanned'] ) ? intval( wp_unslash( $_GET['bulk_scanned'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended - $cropped = ! empty( $_GET['bulk_cropped'] ) ? intval( wp_unslash( $_GET['bulk_cropped'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended - $transcribed = ! empty( $_GET['bulk_transcribed'] ) ? intval( wp_unslash( $_GET['bulk_transcribed'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended + $classified = ! empty( $_GET['bulk_classified'] ) ? intval( wp_unslash( $_GET['bulk_classified'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended + $text_to_speech = ! empty( $_GET['bulk_text_to_speech'] ) ? intval( wp_unslash( $_GET['bulk_text_to_speech'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended + $post_type = ! empty( $_GET['post_type'] ) ? sanitize_text_field( wp_unslash( $_GET['post_type'] ) ) : 'post'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended + $scanned = ! empty( $_GET['bulk_scanned'] ) ? intval( wp_unslash( $_GET['bulk_scanned'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended + $cropped = ! empty( $_GET['bulk_cropped'] ) ? intval( wp_unslash( $_GET['bulk_cropped'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended + $transcribed = ! empty( $_GET['bulk_transcribed'] ) ? intval( wp_unslash( $_GET['bulk_transcribed'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended - if ( ! $classified && ! $scanned && ! $cropped && ! $transcribed ) { + if ( ! $classified && ! $text_to_speech && ! $scanned && ! $cropped && ! $transcribed ) { return; } if ( $classified ) { $classified_posts_count = $classified; - $post_type = 'post'; + $post_type = $post_type; $action = __( 'Classified', 'classifai' ); + } elseif ( $text_to_speech ) { + $classified_posts_count = $text_to_speech; + $post_type = $post_type; + $action = __( 'Text to speech conversion done for', 'classifai' ); } elseif ( $scanned ) { $classified_posts_count = $scanned; $post_type = 'image'; @@ -297,15 +351,23 @@ public function register_row_action( $actions, $post ) { $post_types = array_merge( $post_types, $this->embeddings->supported_post_types() ); } - if ( ! in_array( $post->post_type, $post_types, true ) ) { - return $actions; + if ( in_array( $post->post_type, $post_types, true ) ) { + $actions['classify'] = sprintf( + '%s', + esc_url( wp_nonce_url( admin_url( sprintf( 'edit.php?action=classify&ids=%d&post_type=%s', $post->ID, $post->post_type ) ), 'bulk-posts' ) ), + esc_html__( 'Classify', 'classifai' ) + ); } - $actions['classify'] = sprintf( - '%s', - esc_url( wp_nonce_url( admin_url( sprintf( 'edit.php?action=classify&ids=%d&post_type=%s', $post->ID, $post->post_type ) ), 'bulk-posts' ) ), - esc_html__( 'Classify', 'classifai' ) - ); + if ( is_a( $this->text_to_speech, '\Classifai\Providers\Azure\TextToSpeech' ) ) { + if ( in_array( $post->post_type, $this->text_to_speech->get_supported_post_types(), true ) ) { + $actions['text_to_speech'] = sprintf( + '%s', + esc_url( wp_nonce_url( admin_url( sprintf( 'edit.php?action=text_to_speech&ids=%d&post_type=%s', $post->ID, $post->post_type ) ), 'bulk-posts' ) ), + esc_html__( 'Text to speech', 'classifai' ) + ); + } + } return $actions; } diff --git a/includes/Classifai/Admin/SavePostHandler.php b/includes/Classifai/Admin/SavePostHandler.php index 47f31ccbb..b0f7484e3 100644 --- a/includes/Classifai/Admin/SavePostHandler.php +++ b/includes/Classifai/Admin/SavePostHandler.php @@ -184,7 +184,8 @@ public function synthesize_speech( $post_id ) { ); } - if ( ! current_user_can( 'edit_post', $post_id ) ) { + // We skip the user cap check if running under WP-CLI. + if ( ! current_user_can( 'edit_post', $post_id ) && ( ! defined( 'WP_CLI' ) || ! WP_CLI ) ) { return new \WP_Error( 'azure_text_to_speech_user_not_authorized', esc_html__( 'Unauthorized user.', 'classifai' ) diff --git a/includes/Classifai/Blocks.php b/includes/Classifai/Blocks.php index 36bbf0dbe..fd6eaf5d0 100644 --- a/includes/Classifai/Blocks.php +++ b/includes/Classifai/Blocks.php @@ -46,7 +46,7 @@ function register_blocks() { function blocks_styles() { wp_enqueue_style( 'recommended-content-block-style', - CLASSIFAI_PLUGIN_URL . '/dist/recommended-content-block-frontend.css', + CLASSIFAI_PLUGIN_URL . 'dist/recommended-content-block-frontend.css', [], CLASSIFAI_PLUGIN_VERSION ); diff --git a/includes/Classifai/Command/ClassifaiCommand.php b/includes/Classifai/Command/ClassifaiCommand.php index 87af3b07d..da006643a 100644 --- a/includes/Classifai/Command/ClassifaiCommand.php +++ b/includes/Classifai/Command/ClassifaiCommand.php @@ -2,12 +2,14 @@ namespace Classifai\Command; +use Classifai\Admin\SavePostHandler; use Classifai\Watson\APIRequest; use Classifai\Watson\Classifier; use Classifai\Watson\Normalizer; use Classifai\PostClassifier; use Classifai\Providers\Azure\ComputerVision; use Classifai\Providers\Azure\SmartCropping; +use Classifai\Providers\Azure\TextToSpeech; /** * ClassifaiCommand is the command line interface of the ClassifAI plugin. @@ -18,7 +20,6 @@ // phpcs:ignore WordPressVIPMinimum.Classes.RestrictedExtendClasses.wp_cli class ClassifaiCommand extends \WP_CLI_Command { - /** * Batch classifies post(s) using the current ClassifAI configuration. * @@ -207,6 +208,162 @@ public function text( $args = [], $opts = [] ) { } } + /** + * Batch trigger generation of text-to-speech depending on passed-in settings. + * + * ## Options + * + * [] + * : Comma-delimited list of post IDs to generate text-to-speech for + * + * [--post_type=] + * : Batch process items belonging to this post type. If not used, relies on post_ids in args + * + * [--post_status=] + * : Batch process items that have this post status. Default publish + + * [--per_page=] + * : How many items should be processed at a time. Default 100 + * + * [--dry-run=] + * : Whether to run as a dry-run. Default true + * + * @param array $args Arguments. + * @param array $opts Options. + */ + public function text_to_speech( $args = [], $opts = [] ) { + $defaults = [ + 'post_type' => false, + 'post_status' => 'publish', + 'per_page' => 100, + ]; + + $opts = wp_parse_args( $opts, $defaults ); + $opts['per_page'] = (int) $opts['per_page'] > 0 ? $opts['per_page'] : 100; + $allowed_post_types = TextToSpeech::get_supported_post_types(); + + $count = 0; + $errors = 0; + + $save_post_handler = new SavePostHandler(); + + // Determine if this is a dry run or not. + if ( isset( $opts['dry-run'] ) ) { + if ( 'false' === $opts['dry-run'] ) { + $dry_run = false; + } else { + $dry_run = (bool) $opts['dry-run']; + } + } else { + $dry_run = true; + } + + if ( $dry_run ) { + \WP_CLI::line( '--- Running command in dry-run mode ---' ); + } + + // If we have a post type specified, process all items in that type. + if ( ! empty( $opts['post_type'] ) ) { + // Only allow processing post types that are enabled in settings. + if ( $opts['post_type'] && ! in_array( $opts['post_type'], $allowed_post_types, true ) ) { + \WP_CLI::error( sprintf( 'The "%s" post type is not enabled for Text to Speech processing', $opts['post_type'] ) ); + } + + // Only allow processing post statuses that are valid for a particular post type. + if ( ! in_array( $opts['post_status'], get_available_post_statuses( $opts['post_type'] ), true ) ) { + \WP_CLI::error( sprintf( 'The "%s" post status is not valid for the "%s" post type', $opts['post_status'], $opts['post_type'] ) ); + } + + \WP_CLI::log( sprintf( 'Starting processing of "%s" post type items that have the "%s" status in batches of %d', $opts['post_type'], $opts['post_status'], $opts['per_page'] ) ); + + $paged = 1; + + do { + $posts = get_posts( + array( + 'post_type' => $opts['post_type'], + 'posts_per_page' => $opts['per_page'], + 'paged' => $paged, + 'post_status' => $opts['post_status'], + 'suppress_filters' => 'false', + 'fields' => 'ids', + ) + ); + $total = count( $posts ); + + foreach ( $posts as $post_id ) { + if ( ! $dry_run ) { + $result = $save_post_handler->synthesize_speech( $post_id ); + + if ( is_wp_error( $result ) ) { + \WP_CLI::log( sprintf( 'Error while processing item ID %s: %s', $post_id, $result->get_error_message() ) ); + $errors ++; + } + } + + $count ++; + } + + $this->inmemory_cleanup(); + + if ( $total ) { + \WP_CLI::log( sprintf( 'Batch %d is done, proceeding to next batch', $paged ) ); + } + + $paged ++; + } while ( $total ); + } else { + // If no post type is specified, we have to have a list of post IDs. + if ( ! isset( $args[0] ) ) { + \WP_CLI::error( 'Please specify a comma-delimited list of post IDs to process' ); + } + + $post_ids = array_map( 'absint', explode( ',', $args[0] ) ); + + \WP_CLI::log( sprintf( 'Starting processing of %s items', count( $post_ids ) ) ); + + $progress_bar = \WP_CLI\Utils\make_progress_bar( 'Processing ...', count( $post_ids ) ); + + foreach ( $post_ids as $post_id ) { + // Ensure we have a valid post ID. + if ( ! get_post( $post_id ) ) { + \WP_CLI::log( sprintf( 'Item ID %d does not exist', $post_id ) ); + $errors ++; + continue; + } + + // Ensure we have a valid post type. + $post_type = get_post_type( $post_id ); + if ( ! $post_type || ! in_array( $post_type, $allowed_post_types, true ) ) { + \WP_CLI::log( sprintf( 'The "%s" post type is not enabled for Text to Speech processing', $post_type ) ); + $errors ++; + continue; + } + + if ( ! $dry_run ) { + $result = $save_post_handler->synthesize_speech( $post_id ); + + if ( is_wp_error( $result ) ) { + \WP_CLI::log( sprintf( 'Error while processing item ID %s: %s', $post_id, $result->get_error_message() ) ); + $errors ++; + } + } + + $progress_bar->tick(); + $count ++; + } + + $progress_bar->finish(); + } + + if ( ! $dry_run ) { + \WP_CLI::success( sprintf( '%d items have been processed', $count ) ); + } else { + \WP_CLI::success( sprintf( '%d items would have been processed', $count ) ); + } + + \WP_CLI::log( sprintf( '%d items had errors', $errors ) ); + } /** * Batch classifies attachments(s) using the current ClassifAI configuration. @@ -430,6 +587,28 @@ public function reset( $args = [], $opts = [] ) { /* helpers */ + /** + * Clear in-memory local object cache and reset in-memory database query log. + * + * Copied from WordPress.com VIP's implementation: + * https://github.com/Automattic/vip-go-mu-plugins/blob/develop/vip-helpers/vip-wp-cli.php + */ + private function inmemory_cleanup() { + global $wp_object_cache, $wpdb; + + if ( is_object( $wp_object_cache ) ) { + $wp_object_cache->group_ops = []; + $wp_object_cache->memcache_debug = []; + $wp_object_cache->cache = []; + + if ( method_exists( $wp_object_cache, '__remoteset' ) ) { + $wp_object_cache->__remoteset(); + } + } + + $wpdb->queries = []; + } + /** * Returns the list of post ids to classify with Watson * diff --git a/includes/Classifai/Providers/Azure/ComputerVision.php b/includes/Classifai/Providers/Azure/ComputerVision.php index fb7b9d2c6..00ee86901 100644 --- a/includes/Classifai/Providers/Azure/ComputerVision.php +++ b/includes/Classifai/Providers/Azure/ComputerVision.php @@ -659,11 +659,11 @@ public function ocr_processing( array $metadata = [], int $attachment_id = 0, bo * @since 1.6.0 * @hook classifai_should_ocr_scan_image * - * @param bool $should_ocr_scan Whether to run OCR scanning. The default value is set in ComputerVision settings. - * @param array $metadata Image metadata. - * @param int $attachment_id The attachment ID. + * @param {bool} $should_ocr_scan Whether to run OCR scanning. The default value is set in ComputerVision settings. + * @param {array} $metadata Image metadata. + * @param {int} $attachment_id The attachment ID. * - * @return bool Whether to run OCR scanning. + * @return {bool} Whether to run OCR scanning. */ if ( ! $force && ! apply_filters( 'classifai_should_ocr_scan_image', $should_ocr_scan, $metadata, $attachment_id ) ) { return $metadata; @@ -815,8 +815,8 @@ protected function generate_alt_tags( $captions, $attachment_id ) { * @since 1.5.0 * @hook classifai_computer_vision_caption_failed * - * @param array $tags The caption data. - * @param int $threshold The caption_threshold setting. + * @param {array} $tags The caption data. + * @param {int} $threshold The caption_threshold setting. */ do_action( 'classifai_computer_vision_caption_failed', $captions, $threshold ); } @@ -928,8 +928,8 @@ protected function generate_image_tags( $tags, $attachment_id ) { * @since 1.5.0 * @hook classifai_computer_vision_image_tag_failed * - * @param array $tags The image tag data. - * @param int $threshold The tag_threshold setting. + * @param {array} $tags The image tag data. + * @param {int} $threshold The tag_threshold setting. */ do_action( 'classifai_computer_vision_image_tag_failed', $tags, $threshold ); } diff --git a/includes/Classifai/Providers/Azure/OCR.php b/includes/Classifai/Providers/Azure/OCR.php index 85b511794..2cccfc89a 100644 --- a/includes/Classifai/Providers/Azure/OCR.php +++ b/includes/Classifai/Providers/Azure/OCR.php @@ -122,10 +122,10 @@ public function should_process( int $attachment_id ) { * @since 1.6.0 * @hook classifai_ocr_approved_media_types * - * @param array $media_types The media types to process. - * @param int $attachment_id The attachment ID. + * @param {array} $media_types The media types to process. + * @param {int} $attachment_id The attachment ID. * - * @return array Filtered media types. + * @return {array} Filtered media types. */ $approved_media_types = apply_filters( 'classifai_ocr_approved_media_types', $this->media_to_process, $attachment_id ); @@ -145,11 +145,11 @@ public function should_process( int $attachment_id ) { * @since 1.6.0 * @hook classifai_ocr_tags * - * @param array $tags Tags to look for. Default handwriting and text. - * @param int $attachment_id The attachment ID. - * @param bool|object $scan Previosly run scan. + * @param {array} $tags Tags to look for. Default handwriting and text. + * @param {int} $attachment_id The attachment ID. + * @param {bool|object} $scan Previously run scan. * - * @return array Filtered tags. + * @return {array} Filtered tags. */ $tags = apply_filters( 'classifai_ocr_tags', [ 'handwriting', 'text' ], $attachment_id, $this->scan ); @@ -159,11 +159,11 @@ public function should_process( int $attachment_id ) { * @since 1.6.0 * @hook classifai_ocr_tag_confidence * - * @param int $confidence The mininum confidence level. Default 90. - * @param int $attachment_id The attachment ID. - * @param bool|object $scan Previosly run scan. + * @param {int} $confidence The minimum confidence level. Default 90. + * @param {int} $attachment_id The attachment ID. + * @param {bool|object} $scan Previously run scan. * - * @return int Confidence level. + * @return {int} Confidence level. */ $tag_confidence = apply_filters( 'classifai_ocr_tag_confidence', 90, $attachment_id, $this->scan ); @@ -181,11 +181,11 @@ public function should_process( int $attachment_id ) { * @since 1.6.0 * @hook classifai_ocr_should_process * - * @param bool $process Whether to run OCR processing or not. - * @param int $attachment_id The attachment ID. - * @param bool|object $scan Previosly run scan. + * @param {bool} $process Whether to run OCR processing or not. + * @param {int} $attachment_id The attachment ID. + * @param {bool|object} $scan Previously run scan. * - * @return bool Whether this attachment should have OCR processing. + * @return {bool} Whether this attachment should have OCR processing. */ return apply_filters( 'classifai_ocr_should_process', $process, $attachment_id, $this->scan ); } @@ -246,10 +246,10 @@ public function generate_ocr_data( array $metadata, int $attachment_id ) { * @since 1.6.0 * @hook classifai_ocr_text * - * @param string $text The returned text data. - * @param object $scan The full scan results from the API. + * @param {string} $text The returned text data. + * @param {object} $scan The full scan results from the API. * - * @return string The filtered text data. + * @return {string} The filtered text data. */ $text = apply_filters( 'classifai_ocr_text', implode( ' ', $text ), $scan ); @@ -267,13 +267,13 @@ public function generate_ocr_data( array $metadata, int $attachment_id ) { * @since 1.6.0 * @hook classifai_ocr_text_post_args * - * @param string $post_args Array of post data for the attachment post update. Defaults to `ID` and `post_content`. - * @param int $attachment_id ID of the attachment post. - * @param object $scan The full scan results from the API. - * @param string $text The text data to be saved. - * @param object $scan The full scan results from the API. + * @param {string} $post_args Array of post data for the attachment post update. Defaults to `ID` and `post_content`. + * @param {int} $attachment_id ID of the attachment post. + * @param {object} $scan The full scan results from the API. + * @param {string} $text The text data to be saved. + * @param {object} $scan The full scan results from the API. * - * @return string The filtered text data. + * @return {string} The filtered text data. */ $post_args = apply_filters( 'classifai_ocr_text_post_args', $post_args, $attachment_id, $text, $scan ); @@ -326,8 +326,8 @@ public function process( string $url ) { * @since 1.6.0 * @hook classifai_ocr_after_request * - * @param array|WP_Error Response data or a WP_Error if the request failed. - * @param string The attachment URL. + * @param {array|WP_Error} Response data or a WP_Error if the request failed. + * @param {string} The attachment URL. */ do_action( 'classifai_ocr_after_request', $response, $url ); @@ -349,8 +349,8 @@ public function process( string $url ) { * @since 1.6.0 * @hook classifai_ocr_unsuccessful_response * - * @param array|WP_Error Response data or a WP_Error if the request failed. - * @param string The attachment URL. + * @param {array|WP_Error} Response data or a WP_Error if the request failed. + * @param {string} The attachment URL. */ do_action( 'classifai_ocr_unsuccessful_response', $response, $url ); diff --git a/includes/Classifai/Providers/Azure/Read.php b/includes/Classifai/Providers/Azure/Read.php index e656a3b77..b7b9ed49e 100644 --- a/includes/Classifai/Providers/Azure/Read.php +++ b/includes/Classifai/Providers/Azure/Read.php @@ -98,12 +98,13 @@ public function should_process() { /** * Filters whether to run Read processing on this attachment item * + * @since 1.7.0 * @hook classifai_azure_read_should_process * - * @param bool $process Whether to run OCR processing or not. - * @param int $attachment_id The attachment ID. + * @param {bool} $process Whether to run OCR processing or not. + * @param {int} $attachment_id The attachment ID. * - * @return bool Whether this attachment should have OCR processing. + * @return {bool} Whether this attachment should have OCR processing. */ return apply_filters( 'classifai_azure_read_should_process', $process, $this->attachment_id ); } @@ -145,12 +146,13 @@ public function read_document() { /** * Filters the request arguments sent to Read endpoint. * + * @since 1.7.0 * @hook classifai_azure_read_should_process * - * @param array $args Whether to run OCR processing or not. - * @param int $attachment_id The attachment ID. + * @param {array} $args Whether to run OCR processing or not. + * @param {int} $attachment_id The attachment ID. * - * @return array Filtered request arguments. + * @return {array} Filtered request arguments. */ $request_args = apply_filters( 'classifai_azure_read_request_args', [], $this->attachment_id ); @@ -186,10 +188,10 @@ public function read_document() { * @since 1.5.0 * @hook classifai_azure_read_after_request * - * @param array|WP_Error Response data or a WP_Error if the request failed. - * @param string The request URL with query args added. - * @param int The document ID. - * @param string The document URL. + * @param {array|WP_Error} Response data or a WP_Error if the request failed. + * @param {string} The request URL with query args added. + * @param {int} The document ID. + * @param {string} The document URL. */ do_action( 'classifai_azure_read_after_request', $response, $url, $this->attachment_id, $document_url ); @@ -251,6 +253,16 @@ public function check_read_result( $operation_url ) { case 'notStarted': case 'running': $this->update_status( $body ); + /** + * Filters the Read retry interval. + * + * @since 1.7.0 + * @hook classifai_azure_read_retry_interval + * + * @param {int} $seconds How many seconds should the interval be? Default 60. + * + * @return {int} Filtered interval. + */ $retry_interval = apply_filters( 'classifai_azure_read_retry_interval', MINUTE_IN_SECONDS ); wp_schedule_single_event( time() + $retry_interval, 'classifai_retry_get_read_result', [ $operation_url, $this->attachment_id ] ); break; @@ -280,13 +292,14 @@ public function update_document_description( $data ) { } /** - * Filter the text max pages can be processed. + * Filter the max pages that can be processed. * + * @since 1.7.0 * @hook classifai_azure_read_result_max_page * - * @param int $max_page The attachment ID. + * @param {int} $max_page The maximum pages that are read. * - * @return int + * @return {int} Filtered max pages. */ $max_page = min( apply_filters( 'classifai_azure_read_result_max_page', 2 ), count( $data['analyzeResult']['readResults'] ) ); @@ -301,13 +314,14 @@ public function update_document_description( $data ) { /** * Filter the text result returned from Read API. * + * @since 1.7.0 * @hook classifai_azure_read_text_result * - * @param array $lines_of_text Array of text extracted from the response. - * @param int $attachment_id The attachment ID. - * @param array $data Read result. + * @param {array} $lines_of_text Array of text extracted from the response. + * @param {int} $attachment_id The attachment ID. + * @param {array} $data Read result. * - * @return array + * @return {array} Filtered array of text. */ $lines_of_text = apply_filters( 'classifai_azure_read_text_result', $lines_of_text, $this->attachment_id, $data ); diff --git a/includes/Classifai/Providers/Azure/SmartCropping.php b/includes/Classifai/Providers/Azure/SmartCropping.php index a8c75bfb4..c46f86419 100644 --- a/includes/Classifai/Providers/Azure/SmartCropping.php +++ b/includes/Classifai/Providers/Azure/SmartCropping.php @@ -103,7 +103,7 @@ public function get_max_pixel_dimension() { * @since 1.5.0 * @hook classifai_smart_crop_max_pixel_dimension * - * @param {int} max The max width/height in pixels. + * @param {int} $max The max width/height in pixels. Default 1024. * * @return {int} Filtered max dimension in pixels. */ @@ -264,10 +264,13 @@ public function get_cropped_thumbnail( $attachment_id, $size_data ) { * the original file in the file system. * * @since 1.5.0 + * @hook classifai_smart_cropping_thumb_file_name * - * @param string Default file name. - * @param int The ID of the attachment being processed. - * @param array Width and height data for the image. + * @param {string} Default file name. + * @param {int} The ID of the attachment being processed. + * @param {array} Width and height data for the image. + * + * @return {string} Filtered file name. */ $new_thumb_file_name = apply_filters( 'classifai_smart_cropping_thumb_file_name', @@ -334,9 +337,9 @@ public function request_cropped_thumbnail( $data ) { * @since 1.5.0 * @hook classifai_smart_cropping_after_request * - * @param array|WP_Error Response data or a WP_Error if the request failed. - * @param string The request URL with query args added. - * @param array Array containing the image height and width. + * @param {array|WP_Error} Response data or a WP_Error if the request failed. + * @param {string} The request URL with query args added. + * @param {array} Array containing the image height and width. */ do_action( 'classifai_smart_cropping_after_request', $response, $url, $data ); @@ -358,9 +361,9 @@ public function request_cropped_thumbnail( $data ) { * @since 1.5.0 * @hook classifai_smart_cropping_unsuccessful_response * - * @param array|WP_Error Response data or a WP_Error if the request failed. - * @param string The request URL with query args added. - * @param array Array containing the image height and width. + * @param {array|WP_Error} Response data or a WP_Error if the request failed. + * @param {string} The request URL with query args added. + * @param {array} Array containing the image height and width. */ do_action( 'classifai_smart_cropping_unsuccessful_response', $response, $url, $data ); diff --git a/includes/Classifai/Providers/Azure/TextToSpeech.php b/includes/Classifai/Providers/Azure/TextToSpeech.php index 633b68396..e119341ce 100644 --- a/includes/Classifai/Providers/Azure/TextToSpeech.php +++ b/includes/Classifai/Providers/Azure/TextToSpeech.php @@ -502,10 +502,15 @@ public function render_post_audio_controls( $content ) { } /** - * Filter to disable Text to Speech synthesis for a post by post ID. + * Filter to disable the rendering of the Text to Speech block. * - * @param boolean 'is_disabled' Boolean to toggle the service. By default - false. - * @param boolean 'post_id' Post ID. + * @since 2.2.0 + * @hook classifai_disable_post_to_audio_block + * + * @param {bool} $is_disabled Whether to disable the display or not. By default - false. + * @param {bool} $post_id Post ID. + * + * @return {bool} Whether the audio block should be shown. */ if ( apply_filters( 'classifai_disable_post_to_audio_block', false, $post->ID ) ) { return $content; @@ -519,7 +524,7 @@ public function render_post_audio_controls( $content ) { wp_enqueue_script( 'classifai-post-audio-player-js', - CLASSIFAI_PLUGIN_URL . '/dist/post-audio-controls.js', + CLASSIFAI_PLUGIN_URL . 'dist/post-audio-controls.js', get_asset_info( 'post-audio-controls', 'dependencies' ), get_asset_info( 'post-audio-controls', 'version' ), true @@ -527,7 +532,7 @@ public function render_post_audio_controls( $content ) { wp_enqueue_style( 'classifai-post-audio-player-css', - CLASSIFAI_PLUGIN_URL . '/dist/post-audio-controls.css', + CLASSIFAI_PLUGIN_URL . 'dist/post-audio-controls.css', array(), get_asset_info( 'post-audio-controls', 'version' ), 'all' @@ -555,10 +560,13 @@ public function render_post_audio_controls( $content ) { /** * Hook to filter the text next to the audio controls on the frontend. * - * @param string The text to filter. - * @param integer The Post ID. + * @since 2.2.0 + * @hook classifai_listen_to_this_post_text + * + * @param {string} The text to filter. + * @param {int} Post ID. * - * @return string + * @return {string} Filtered text. */ apply_filters( 'classifai_listen_to_this_post_text', '%s %s', $post->ID ), esc_html__( 'Listen to this', 'classifai' ), diff --git a/includes/Classifai/Providers/OpenAI/ChatGPT.php b/includes/Classifai/Providers/OpenAI/ChatGPT.php index fe5199fc7..835ab4f4d 100644 --- a/includes/Classifai/Providers/OpenAI/ChatGPT.php +++ b/includes/Classifai/Providers/OpenAI/ChatGPT.php @@ -374,7 +374,7 @@ public function get_provider_debug_information( $settings = null, $configured = __( 'Generate titles', 'classifai' ) => $enable_titles ? __( 'yes', 'classifai' ) : __( 'no', 'classifai' ), __( 'Allowed roles (titles)', 'classifai' ) => implode( ', ', $settings['title_roles'] ?? [] ), __( 'Number of titles', 'classifai' ) => absint( $settings['number_titles'] ?? 1 ), - __( 'Latest response', 'classifai' ) => $this->get_formatted_latest_response( 'classifai_openai_chatgpt_latest_response' ), + __( 'Latest response', 'classifai' ) => $this->get_formatted_latest_response( get_transient( 'classifai_openai_chatgpt_latest_response' ) ), ]; } @@ -443,7 +443,7 @@ public function generate_excerpt( int $post_id = 0 ) { * * @return {string} Prompt. */ - $prompt = apply_filters( 'classifai_chatgpt_excerpt_prompt', 'Provide a kicker for the following text in ' . $excerpt_length . ' words', $post_id, $excerpt_length ); + $prompt = apply_filters( 'classifai_chatgpt_excerpt_prompt', 'Provide a teaser for the following text using a maximum of ' . $excerpt_length . ' words', $post_id, $excerpt_length ); /** * Filter the request body before sending to ChatGPT. @@ -485,7 +485,8 @@ public function generate_excerpt( int $post_id = 0 ) { if ( ! is_wp_error( $response ) && ! empty( $response['choices'] ) ) { foreach ( $response['choices'] as $choice ) { if ( isset( $choice['message'], $choice['message']['content'] ) ) { - $response = sanitize_text_field( $choice['message']['content'] ); + // ChatGPT often adds quotes to strings, so remove those as well as extra spaces. + $response = sanitize_text_field( trim( $choice['message']['content'], ' "\'' ) ); } } } diff --git a/includes/Classifai/Providers/OpenAI/DallE.php b/includes/Classifai/Providers/OpenAI/DallE.php index 1a24b9ef0..97aad17b1 100644 --- a/includes/Classifai/Providers/OpenAI/DallE.php +++ b/includes/Classifai/Providers/OpenAI/DallE.php @@ -21,6 +21,13 @@ class DallE extends Provider { */ protected $dalle_url = 'https://api.openai.com/v1/images/generations'; + /** + * Maximum number of characters a prompt can have + * + * @var int + */ + public $max_prompt_chars = 1000; + /** * OpenAI DALL·E constructor. * @@ -87,7 +94,7 @@ public function enqueue_admin_scripts( $hook_suffix = '' ) { wp_enqueue_script( 'classifai-generate-images', CLASSIFAI_PLUGIN_URL . 'dist/media-modal.js', - [ 'jquery', 'wp-api' ], + [ 'jquery', 'wp-api', 'wp-media-utils', 'wp-url' ], get_asset_info( 'media-modal', 'version' ), true ); @@ -139,7 +146,7 @@ public function print_media_templates() {

- + @@ -333,7 +340,7 @@ public function get_provider_debug_information( $settings = null, $configured = __( 'Allowed roles', 'classifai' ) => implode( ', ', $settings['roles'] ?? [] ), __( 'Number of images', 'classifai' ) => absint( $settings['number'] ?? 1 ), __( 'Image size', 'classifai' ) => sanitize_text_field( $settings['size'] ?? '1024x1024' ), - __( 'Latest response', 'classifai' ) => $this->get_formatted_latest_response( 'classifai_openai_dalle_latest_response' ), + __( 'Latest response', 'classifai' ) => $this->get_formatted_latest_response( get_transient( 'classifai_openai_dalle_latest_response' ) ), ]; } @@ -383,6 +390,11 @@ public function generate_image_callback( string $prompt = '', array $args = [] ) */ $prompt = apply_filters( 'classifai_dalle_prompt', $prompt ); + // If our prompt exceeds the max length, throw an error. + if ( mb_strlen( $prompt ) > $this->max_prompt_chars ) { + return new WP_Error( 'invalid_param', esc_html__( 'Your image prompt is too long. Please ensure it doesn\'t exceed 1000 characters.', 'classifai' ) ); + } + $request = new APIRequest( $settings['api_key'] ?? '' ); /** diff --git a/includes/Classifai/Providers/OpenAI/Embeddings.php b/includes/Classifai/Providers/OpenAI/Embeddings.php index d8f7aaa28..7c515edc8 100644 --- a/includes/Classifai/Providers/OpenAI/Embeddings.php +++ b/includes/Classifai/Providers/OpenAI/Embeddings.php @@ -314,7 +314,7 @@ public function get_provider_debug_information( $settings = null, $configured = __( 'Post statuses', 'classifai' ) => implode( ', ', $settings['post_statuses'] ?? [] ), __( 'Taxonomies', 'classifai' ) => implode( ', ', $settings['taxonomies'] ?? [] ), __( 'Number of terms', 'classifai' ) => $settings['number'] ?? 1, - __( 'Latest response', 'classifai' ) => $this->get_formatted_latest_response( 'classifai_openai_embeddings_latest_response' ), + __( 'Latest response', 'classifai' ) => $this->get_formatted_latest_response( get_transient( 'classifai_openai_embeddings_latest_response' ) ), ]; } diff --git a/includes/Classifai/Providers/OpenAI/Whisper.php b/includes/Classifai/Providers/OpenAI/Whisper.php index 32b01a1fe..2beb0640f 100644 --- a/includes/Classifai/Providers/OpenAI/Whisper.php +++ b/includes/Classifai/Providers/OpenAI/Whisper.php @@ -328,7 +328,7 @@ public function get_provider_debug_information( $settings = null, $configured = __( 'Authenticated', 'classifai' ) => $authenticated ? __( 'yes', 'classifai' ) : __( 'no', 'classifai' ), __( 'Generate transcripts', 'classifai' ) => $enable_transcript ? __( 'yes', 'classifai' ) : __( 'no', 'classifai' ), __( 'Allowed roles', 'classifai' ) => implode( ', ', $settings['roles'] ?? [] ), - __( 'Latest response', 'classifai' ) => $this->get_formatted_latest_response( 'classifai_openai_whisper_latest_response' ), + __( 'Latest response', 'classifai' ) => $this->get_formatted_latest_response( get_transient( 'classifai_openai_whisper_latest_response' ) ), ]; } diff --git a/includes/Classifai/Providers/Provider.php b/includes/Classifai/Providers/Provider.php index ff80518fe..488886b08 100644 --- a/includes/Classifai/Providers/Provider.php +++ b/includes/Classifai/Providers/Provider.php @@ -397,11 +397,11 @@ public function rest_endpoint_callback( $post_id, $route_to_call, $args = [] ) { /** * Format the result of most recent request. * - * @param string $data Response data to format. + * @param array|WP_Error $data Response data to format. * * @return string */ - protected function get_formatted_latest_response( string $data = '' ) { + protected function get_formatted_latest_response( $data ) { if ( ! $data ) { return __( 'N/A', 'classifai' ); } diff --git a/includes/Classifai/Providers/Watson/NLU.php b/includes/Classifai/Providers/Watson/NLU.php index 3d75722bd..f7c207269 100644 --- a/includes/Classifai/Providers/Watson/NLU.php +++ b/includes/Classifai/Providers/Watson/NLU.php @@ -758,20 +758,18 @@ function( $post_type ) use ( $settings_post_types ) { __( 'API username', 'classifai' ) => $credentials['watson_username'] ?? '', __( 'Post types', 'classifai' ) => implode( ', ', $post_types ), __( 'Features', 'classifai' ) => preg_replace( '/,"/', ', "', wp_json_encode( $settings['features'] ?? '' ) ), - __( 'Latest response', 'classifai' ) => $this->get_formatted_latest_response(), + __( 'Latest response', 'classifai' ) => $this->get_formatted_latest_response( get_transient( 'classifai_watson_nlu_latest_response' ) ), ]; } /** * Format the result of most recent request. * - * @param string $data Response data to format. + * @param array|WP_Error $data Response data to format. * * @return string */ - protected function get_formatted_latest_response( string $data = '' ) { - $data = get_transient( 'classifai_watson_nlu_latest_response' ); - + protected function get_formatted_latest_response( $data ) { if ( ! $data ) { return __( 'N/A', 'classifai' ); } diff --git a/includes/Classifai/Watson/Linker.php b/includes/Classifai/Watson/Linker.php index 96bea57cf..c1b6dc5a7 100644 --- a/includes/Classifai/Watson/Linker.php +++ b/includes/Classifai/Watson/Linker.php @@ -33,25 +33,39 @@ class Linker { * @param int $post_id The post to link to. * @param array $output The classification results from Watson NLU. * @param array $options Unused. - - * @return void + * + * @return array The terms that were linked. */ public function link( $post_id, $output, $options = [] ) { + $all_terms = []; + if ( ! empty( $output['categories'] ) ) { - $this->link_categories( $post_id, $output['categories'] ); + $terms = $this->link_categories( $post_id, $output['categories'], false ); + $all_terms = $terms; } if ( ! empty( $output['keywords'] ) ) { - $this->link_keywords( $post_id, $output['keywords'] ); + $terms = $this->link_keywords( $post_id, $output['keywords'], false ); + $all_terms = array_merge_recursive( $all_terms, $terms ); } if ( ! empty( $output['concepts'] ) ) { - $this->link_concepts( $post_id, $output['concepts'] ); + $terms = $this->link_concepts( $post_id, $output['concepts'], false ); + $all_terms = array_merge_recursive( $all_terms, $terms ); } if ( ! empty( $output['entities'] ) ) { - $this->link_entities( $post_id, $output['entities'] ); + $terms = $this->link_entities( $post_id, $output['entities'], false ); + $all_terms = array_merge_recursive( $all_terms, $terms ); + } + + if ( ! empty( $all_terms ) ) { + foreach ( $all_terms as $taxonomy => $terms ) { + wp_set_object_terms( $post_id, $terms, $taxonomy, false ); + } } + + return $all_terms; } /* helpers */ @@ -71,11 +85,13 @@ public function link( $post_id, $output, $options = [] ) { * * Eg:- /animals/pets/cats * - * @param int $post_id The id of the post to link + * @param int $post_id The id of the post to link. * @param array $categories The list of categories to link - * @return void + * @param bool $link_categories Whether link categories to post or return array of term ids. + * + * @return array|\WP_Error List of the terms to link. WP_Error class object on error. */ - public function link_categories( $post_id, $categories ) { + public function link_categories( int $post_id, array $categories, bool $link_categories = true ) { $terms_to_link = []; $taxonomy = \Classifai\get_feature_taxonomy( 'category' ); @@ -91,30 +107,35 @@ public function link_categories( $post_id, $categories ) { $term = get_term_by( 'name', $part, $taxonomy ); if ( false === $term ) { - $term = wp_insert_term( - $part, - $taxonomy, - [ - 'parent' => $parent, - ] - ); + $term = wp_insert_term( $part, $taxonomy, [ 'parent' => $parent ] ); if ( ! is_wp_error( $term ) ) { - $parent = intval( $term['term_id'] ); - $terms_to_link[] = intval( $term['term_id'] ); + $parent = (int) $term['term_id']; + $terms_to_link[] = (int) $term['term_id']; } } else { - $parent = intval( $term->term_id ); - $terms_to_link[] = intval( $term->term_id ); + $parent = $term->term_id; + $terms_to_link[] = $term->term_id; } } } } } - if ( ! empty( $terms_to_link ) ) { - wp_set_object_terms( $post_id, $terms_to_link, $taxonomy, false ); + // Exit if there are not any term to link. + if ( empty( $terms_to_link ) ) { + return []; + } + + if ( $link_categories ) { + $result = wp_set_object_terms( $post_id, $terms_to_link, $taxonomy, false ); + + if ( is_wp_error( $result ) ) { + return $result; + } } + + return [ $taxonomy => $terms_to_link ]; } /** @@ -127,11 +148,13 @@ public function link_categories( $post_id, $categories ) { * ... * ] * - * @param int $post_id The post to link to + * @param int $post_id The id of the post to link. * @param array $keywords NLU returned keywords - * @return void + * @param bool $link_keywords Whether link keywords to post or return array of term ids. + * + * @return array|\WP_Error List of the terms to link. WP_Error class object on error. */ - public function link_keywords( $post_id, $keywords ) { + public function link_keywords( int $post_id, array $keywords, bool $link_keywords = true ) { $terms_to_link = []; $taxonomy = \Classifai\get_feature_taxonomy( 'keyword' ); @@ -145,17 +168,28 @@ public function link_keywords( $post_id, $keywords ) { $term = wp_insert_term( $name, $taxonomy, [] ); if ( ! is_wp_error( $term ) ) { - $terms_to_link[] = intval( $term['term_id'] ); + $terms_to_link[] = (int) $term['term_id']; } } else { - $terms_to_link[] = intval( $term->term_id ); + $terms_to_link[] = $term->term_id; } } } - if ( ! empty( $terms_to_link ) ) { - wp_set_object_terms( $post_id, $terms_to_link, $taxonomy, false ); + // Exit if there are not any term to link. + if ( empty( $terms_to_link ) ) { + return []; + } + + if ( $link_keywords ) { + $result = wp_set_object_terms( $post_id, $terms_to_link, $taxonomy, false ); + + if ( is_wp_error( $result ) ) { + return $result; + } } + + return [ $taxonomy => $terms_to_link ]; } /** @@ -168,11 +202,13 @@ public function link_keywords( $post_id, $keywords ) { * ... * ] * - * @param int $post_id The post to link to. + * @param int $post_id The id of the post to link. * @param array $concepts The NLU returned concepts. - * @return void + * @param bool $link_concepts Whether link concepts to post or return array of term ids. + * + * @return array|\WP_Error List of the terms to link. WP_Error class object on error. */ - public function link_concepts( $post_id, $concepts ) { + public function link_concepts( int $post_id, array $concepts, bool $link_concepts = true ) { $terms_to_link = []; $taxonomy = \Classifai\get_feature_taxonomy( 'concept' ); @@ -185,25 +221,36 @@ public function link_concepts( $post_id, $concepts ) { $term = wp_insert_term( $name, $taxonomy, [] ); if ( ! is_wp_error( $term ) ) { - $terms_to_link[] = intval( $term['term_id'] ); + $terms_to_link[] = (int) $term['term_id']; if ( ! empty( $concept['dbpedia_resource'] ) ) { update_term_meta( - intval( $term['term_id'] ), + (int) $term['term_id'], 'dbpedia_resource', $concept['dbpedia_resource'] ); } } } else { - $terms_to_link[] = intval( $term->term_id ); + $terms_to_link[] = $term->term_id; } } } - if ( ! empty( $terms_to_link ) ) { - wp_set_object_terms( $post_id, $terms_to_link, $taxonomy, false ); + // Exit if there are not any term to link. + if ( empty( $terms_to_link ) ) { + return []; + } + + if ( $link_concepts ) { + $result = wp_set_object_terms( $post_id, $terms_to_link, $taxonomy, false ); + + if ( is_wp_error( $result ) ) { + return $result; + } } + + return [ $taxonomy => $terms_to_link ]; } /** @@ -216,11 +263,13 @@ public function link_concepts( $post_id, $concepts ) { * ... * ] * - * @param int $post_id The post to link to + * @param int $post_id The id of the post to link. * @param array $entities The entities returned by the NLU api - * @return void + * @param bool $link_entities Whether link entities to post or return array of term ids. + * + * @return array|\WP_Error List of the terms to link. WP_Error class object on error. */ - public function link_entities( $post_id, $entities ) { + public function link_entities( int $post_id, array $entities, bool $link_entities = true ) { $terms_to_link = []; $taxonomy = \Classifai\get_feature_taxonomy( 'entity' ); @@ -238,31 +287,42 @@ public function link_entities( $post_id, $entities ) { $term = wp_insert_term( $name, $taxonomy, [] ); if ( ! is_wp_error( $term ) ) { - $terms_to_link[] = intval( $term['term_id'] ); + $terms_to_link[] = (int) $term['term_id']; if ( ! empty( $entity['disambiguation']['dbpedia_resource'] ) ) { update_term_meta( - intval( $term['term_id'] ), + (int) $term['term_id'], 'dbpedia_resource', $entity['disambiguation']['dbpedia_resource'] ); update_term_meta( - intval( $term['term_id'] ), + (int) $term['term_id'], 'type', $entity['type'] ); } } } else { - $terms_to_link[] = intval( $term->term_id ); + $terms_to_link[] = $term->term_id; } } } - if ( ! empty( $terms_to_link ) ) { - wp_set_object_terms( $post_id, $terms_to_link, $taxonomy, false ); + // Exit if there are not any term to link. + if ( empty( $terms_to_link ) ) { + return []; + } + + if ( $link_entities ) { + $result = wp_set_object_terms( $post_id, $terms_to_link, $taxonomy, false ); + + if ( is_wp_error( $result ) ) { + return $result; + } } + + return [ $taxonomy => $terms_to_link ]; } /** diff --git a/languages/classifai.pot b/languages/classifai.pot index 97498de91..0020e3f70 100644 --- a/languages/classifai.pot +++ b/languages/classifai.pot @@ -2,9 +2,9 @@ # This file is distributed under the GPLv2. msgid "" msgstr "" -"Project-Id-Version: ClassifAI 2.2.0\n" +"Project-Id-Version: ClassifAI 2.2.1\n" "Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/classifai\n" -"POT-Creation-Date: 2023-05-22 17:28:17+00:00\n" +"POT-Creation-Date: 2023-06-08 18:43:16+00:00\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" @@ -53,48 +53,57 @@ msgid "" "install the stable version of ClassifAI instead." msgstr "" -#: includes/Classifai/Admin/BulkActions.php:114 -#: includes/Classifai/Admin/BulkActions.php:307 +#: includes/Classifai/Admin/BulkActions.php:133 +#: includes/Classifai/Admin/BulkActions.php:358 msgid "Classify" msgstr "" -#: includes/Classifai/Admin/BulkActions.php:133 +#: includes/Classifai/Admin/BulkActions.php:140 +#: includes/Classifai/Admin/BulkActions.php:367 +msgid "Text to speech" +msgstr "" + +#: includes/Classifai/Admin/BulkActions.php:161 msgid "Scan image" msgstr "" -#: includes/Classifai/Admin/BulkActions.php:137 +#: includes/Classifai/Admin/BulkActions.php:165 msgid "Smart crop" msgstr "" -#: includes/Classifai/Admin/BulkActions.php:141 +#: includes/Classifai/Admin/BulkActions.php:169 #: includes/Classifai/Providers/OpenAI/Whisper.php:131 msgid "Transcribe audio" msgstr "" -#: includes/Classifai/Admin/BulkActions.php:239 +#: includes/Classifai/Admin/BulkActions.php:289 msgid "Classified" msgstr "" -#: includes/Classifai/Admin/BulkActions.php:243 +#: includes/Classifai/Admin/BulkActions.php:293 +msgid "Text to speech conversion done for" +msgstr "" + +#: includes/Classifai/Admin/BulkActions.php:297 msgid "Scanned" msgstr "" -#: includes/Classifai/Admin/BulkActions.php:247 +#: includes/Classifai/Admin/BulkActions.php:301 msgid "Cropped" msgstr "" -#: includes/Classifai/Admin/BulkActions.php:251 +#: includes/Classifai/Admin/BulkActions.php:305 msgid "Transcribed" msgstr "" -#: includes/Classifai/Admin/BulkActions.php:257 +#: includes/Classifai/Admin/BulkActions.php:311 #. translators: %1$s: action, %2$s: number of posts, %3$s: post type msgid "%1$s %2$s %3$s." msgid_plural "%1$s %2$s %3$ss." msgstr[0] "" msgstr[1] "" -#: includes/Classifai/Admin/BulkActions.php:334 +#: includes/Classifai/Admin/BulkActions.php:396 #: includes/Classifai/Providers/OpenAI/Whisper.php:128 #: includes/Classifai/Providers/OpenAI/Whisper.php:178 msgid "Transcribe" @@ -146,7 +155,7 @@ msgid "Please enable at least one feature to set up ClassifAI." msgstr "" #: includes/Classifai/Admin/Onboarding.php:563 -#: includes/Classifai/Admin/SavePostHandler.php:432 +#: includes/Classifai/Admin/SavePostHandler.php:433 msgid "You don't have permission to perform this operation." msgstr "" @@ -163,28 +172,28 @@ msgstr "" msgid "Post ID missing." msgstr "" -#: includes/Classifai/Admin/SavePostHandler.php:190 +#: includes/Classifai/Admin/SavePostHandler.php:191 msgid "Unauthorized user." msgstr "" -#: includes/Classifai/Admin/SavePostHandler.php:212 +#: includes/Classifai/Admin/SavePostHandler.php:213 msgid "Voice data not set." msgstr "" -#: includes/Classifai/Admin/SavePostHandler.php:253 +#: includes/Classifai/Admin/SavePostHandler.php:254 msgid "HTTP request unsuccessful." msgstr "" -#: includes/Classifai/Admin/SavePostHandler.php:300 +#: includes/Classifai/Admin/SavePostHandler.php:301 msgid "Audio creation failed." msgstr "" -#: includes/Classifai/Admin/SavePostHandler.php:365 -#: includes/Classifai/Providers/Watson/NLU.php:836 +#: includes/Classifai/Admin/SavePostHandler.php:366 +#: includes/Classifai/Providers/Watson/NLU.php:834 msgid "Post" msgstr "" -#: includes/Classifai/Admin/SavePostHandler.php:374 +#: includes/Classifai/Admin/SavePostHandler.php:375 #. translators: %s is post type label. msgid "%s classified successfully." msgstr "" @@ -428,7 +437,7 @@ msgstr "" #: includes/Classifai/Providers/Azure/ComputerVision.php:695 #: includes/Classifai/Providers/Azure/OCR.php:305 -#: includes/Classifai/Providers/Azure/Read.php:119 +#: includes/Classifai/Providers/Azure/Read.php:120 #: includes/Classifai/Services/ImageProcessing.php:293 #: includes/Classifai/Services/Personalizer.php:176 msgid "Please set up valid authentication with Azure." @@ -524,7 +533,7 @@ msgstr "" #: includes/Classifai/Providers/Azure/Personalizer.php:718 #: includes/Classifai/Providers/Azure/TextToSpeech.php:410 #: includes/Classifai/Providers/OpenAI/ChatGPT.php:370 -#: includes/Classifai/Providers/OpenAI/DallE.php:331 +#: includes/Classifai/Providers/OpenAI/DallE.php:338 #: includes/Classifai/Providers/OpenAI/Embeddings.php:311 #: includes/Classifai/Providers/OpenAI/Whisper.php:328 msgid "Authenticated" @@ -534,8 +543,8 @@ msgstr "" #: includes/Classifai/Providers/OpenAI/ChatGPT.php:370 #: includes/Classifai/Providers/OpenAI/ChatGPT.php:371 #: includes/Classifai/Providers/OpenAI/ChatGPT.php:374 -#: includes/Classifai/Providers/OpenAI/DallE.php:331 -#: includes/Classifai/Providers/OpenAI/DallE.php:332 +#: includes/Classifai/Providers/OpenAI/DallE.php:338 +#: includes/Classifai/Providers/OpenAI/DallE.php:339 #: includes/Classifai/Providers/OpenAI/Embeddings.php:311 #: includes/Classifai/Providers/OpenAI/Embeddings.php:312 #: includes/Classifai/Providers/OpenAI/Whisper.php:328 @@ -549,8 +558,8 @@ msgstr "" #: includes/Classifai/Providers/OpenAI/ChatGPT.php:370 #: includes/Classifai/Providers/OpenAI/ChatGPT.php:371 #: includes/Classifai/Providers/OpenAI/ChatGPT.php:374 -#: includes/Classifai/Providers/OpenAI/DallE.php:331 -#: includes/Classifai/Providers/OpenAI/DallE.php:332 +#: includes/Classifai/Providers/OpenAI/DallE.php:338 +#: includes/Classifai/Providers/OpenAI/DallE.php:339 #: includes/Classifai/Providers/OpenAI/Embeddings.php:311 #: includes/Classifai/Providers/OpenAI/Embeddings.php:312 #: includes/Classifai/Providers/OpenAI/Whisper.php:328 @@ -665,11 +674,11 @@ msgstr "" msgid "Service Status" msgstr "" -#: includes/Classifai/Providers/Azure/Read.php:123 +#: includes/Classifai/Providers/Azure/Read.php:124 msgid "Document does not meet processing requirements." msgstr "" -#: includes/Classifai/Providers/Azure/Read.php:134 +#: includes/Classifai/Providers/Azure/Read.php:135 #. translators: %1$s is the document file size in bytes, %2$s is the current #. default max filesize in bytes, %3$s is the integer '4 * MB_IN_BYTES' msgid "" @@ -678,35 +687,35 @@ msgid "" "bytes)." msgstr "" -#: includes/Classifai/Providers/Azure/Read.php:135 +#: includes/Classifai/Providers/Azure/Read.php:136 msgid "size not found" msgstr "" -#: includes/Classifai/Providers/Azure/Read.php:165 +#: includes/Classifai/Providers/Azure/Read.php:167 msgid "Document does not exist." msgstr "" -#: includes/Classifai/Providers/Azure/Read.php:203 +#: includes/Classifai/Providers/Azure/Read.php:205 msgid "Operation URL is invalid." msgstr "" -#: includes/Classifai/Providers/Azure/Read.php:211 +#: includes/Classifai/Providers/Azure/Read.php:213 msgid "Unknown Read error." msgstr "" -#: includes/Classifai/Providers/Azure/Read.php:247 +#: includes/Classifai/Providers/Azure/Read.php:249 msgid "Invalid Read result." msgstr "" -#: includes/Classifai/Providers/Azure/Read.php:258 +#: includes/Classifai/Providers/Azure/Read.php:270 msgid "The Read operation has failed." msgstr "" -#: includes/Classifai/Providers/Azure/Read.php:264 +#: includes/Classifai/Providers/Azure/Read.php:276 msgid "Invalid Read result status." msgstr "" -#: includes/Classifai/Providers/Azure/Read.php:279 +#: includes/Classifai/Providers/Azure/Read.php:291 msgid "The Read result is invalid." msgstr "" @@ -744,15 +753,15 @@ msgstr "" msgid "Latest response - Voices" msgstr "" -#: includes/Classifai/Providers/Azure/TextToSpeech.php:548 +#: includes/Classifai/Providers/Azure/TextToSpeech.php:553 msgid "Play audio" msgstr "" -#: includes/Classifai/Providers/Azure/TextToSpeech.php:548 +#: includes/Classifai/Providers/Azure/TextToSpeech.php:553 msgid "Pause audio" msgstr "" -#: includes/Classifai/Providers/Azure/TextToSpeech.php:564 +#: includes/Classifai/Providers/Azure/TextToSpeech.php:572 msgid "Listen to this" msgstr "" @@ -799,8 +808,8 @@ msgstr "" #: includes/Classifai/Providers/OpenAI/ChatGPT.php:194 #: includes/Classifai/Providers/OpenAI/ChatGPT.php:246 -#: includes/Classifai/Providers/OpenAI/DallE.php:207 -#: includes/Classifai/Providers/OpenAI/DallE.php:333 +#: includes/Classifai/Providers/OpenAI/DallE.php:214 +#: includes/Classifai/Providers/OpenAI/DallE.php:340 #: includes/Classifai/Providers/OpenAI/Whisper.php:249 #: includes/Classifai/Providers/OpenAI/Whisper.php:330 msgid "Allowed roles" @@ -854,7 +863,7 @@ msgid "Allowed roles (titles)" msgstr "" #: includes/Classifai/Providers/OpenAI/ChatGPT.php:377 -#: includes/Classifai/Providers/OpenAI/DallE.php:336 +#: includes/Classifai/Providers/OpenAI/DallE.php:343 #: includes/Classifai/Providers/OpenAI/Embeddings.php:317 #: includes/Classifai/Providers/OpenAI/Whisper.php:331 #: includes/Classifai/Providers/Watson/NLU.php:761 @@ -875,123 +884,129 @@ msgid "" "check your settings." msgstr "" -#: includes/Classifai/Providers/OpenAI/ChatGPT.php:505 +#: includes/Classifai/Providers/OpenAI/ChatGPT.php:506 msgid "Post ID is required to generate titles." msgstr "" -#: includes/Classifai/Providers/OpenAI/ChatGPT.php:519 +#: includes/Classifai/Providers/OpenAI/ChatGPT.php:520 msgid "" "Title generation is disabled or OpenAI authentication failed. Please check " "your settings." msgstr "" -#: includes/Classifai/Providers/OpenAI/ChatGPT.php:580 +#: includes/Classifai/Providers/OpenAI/ChatGPT.php:581 msgid "No choices were returned from OpenAI." msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:39 +#: includes/Classifai/Providers/OpenAI/DallE.php:46 msgid "OpenAI DALL·E" msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:42 +#: includes/Classifai/Providers/OpenAI/DallE.php:49 msgid "Image generation" msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:109 +#: includes/Classifai/Providers/OpenAI/DallE.php:116 #. translators: %1$s is replaced with the OpenAI DALL·E URL msgid "Image generated by OpenAI's DALL·E" msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:119 -#: includes/Classifai/Providers/OpenAI/DallE.php:143 -#: includes/Classifai/Providers/OpenAI/DallE.php:332 +#: includes/Classifai/Providers/OpenAI/DallE.php:126 +#: includes/Classifai/Providers/OpenAI/DallE.php:150 +#: includes/Classifai/Providers/OpenAI/DallE.php:339 msgid "Generate images" msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:120 +#: includes/Classifai/Providers/OpenAI/DallE.php:127 msgid "Something went wrong. No results found" msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:121 +#: includes/Classifai/Providers/OpenAI/DallE.php:128 msgid "Select image" msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:137 +#: includes/Classifai/Providers/OpenAI/DallE.php:144 msgid "Enter a prompt below to generate images." msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:140 +#: includes/Classifai/Providers/OpenAI/DallE.php:147 msgid "" "Once images are generated, choose one or more of those to import into your " "Media Library and then choose one image to insert." msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:142 +#: includes/Classifai/Providers/OpenAI/DallE.php:149 msgid "Enter prompt" msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:147 +#: includes/Classifai/Providers/OpenAI/DallE.php:154 msgid "Images generated from prompt: " msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:160 +#: includes/Classifai/Providers/OpenAI/DallE.php:167 msgid "Import into Media Library" msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:161 +#: includes/Classifai/Providers/OpenAI/DallE.php:168 msgid "Import and Insert" msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:183 +#: includes/Classifai/Providers/OpenAI/DallE.php:190 msgid "Enable image generation" msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:191 +#: includes/Classifai/Providers/OpenAI/DallE.php:198 msgid "" "When enabled, a new Generate images tab will be shown in the media upload " "flow, allowing you to generate and import images." msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:215 +#: includes/Classifai/Providers/OpenAI/DallE.php:222 msgid "" "Choose which roles are allowed to generate images. Note that the roles " "above only include those that have permissions to upload media." msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:221 -#: includes/Classifai/Providers/OpenAI/DallE.php:334 +#: includes/Classifai/Providers/OpenAI/DallE.php:228 +#: includes/Classifai/Providers/OpenAI/DallE.php:341 msgid "Number of images" msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:229 +#: includes/Classifai/Providers/OpenAI/DallE.php:236 msgid "" "Number of images that will be generated in one request. Note that each " "image will incur separate costs." msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:235 -#: includes/Classifai/Providers/OpenAI/DallE.php:335 +#: includes/Classifai/Providers/OpenAI/DallE.php:242 +#: includes/Classifai/Providers/OpenAI/DallE.php:342 msgid "Image size" msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:247 +#: includes/Classifai/Providers/OpenAI/DallE.php:254 msgid "Size of generated images." msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:349 +#: includes/Classifai/Providers/OpenAI/DallE.php:356 msgid "A prompt is required to generate an image." msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:367 +#: includes/Classifai/Providers/OpenAI/DallE.php:374 msgid "Sorry, you are not allowed to do that." msgstr "" -#: includes/Classifai/Providers/OpenAI/DallE.php:371 +#: includes/Classifai/Providers/OpenAI/DallE.php:378 msgid "" "Image generation is disabled or OpenAI authentication failed. Please check " "your settings." msgstr "" +#: includes/Classifai/Providers/OpenAI/DallE.php:395 +msgid "" +"Your image prompt is too long. Please ensure it doesn't exceed 1000 " +"characters." +msgstr "" + #: includes/Classifai/Providers/OpenAI/Embeddings.php:58 msgid "OpenAI Embeddings" msgstr "" @@ -1163,7 +1178,7 @@ msgid "Image description" msgstr "" #: includes/Classifai/Providers/Provider.php:406 -#: includes/Classifai/Providers/Watson/NLU.php:776 +#: includes/Classifai/Providers/Watson/NLU.php:774 msgid "N/A" msgstr "" @@ -1286,15 +1301,15 @@ msgstr "" msgid "Features" msgstr "" -#: includes/Classifai/Providers/Watson/NLU.php:813 +#: includes/Classifai/Providers/Watson/NLU.php:811 msgid "ClassifAI Language Processing" msgstr "" -#: includes/Classifai/Providers/Watson/NLU.php:844 +#: includes/Classifai/Providers/Watson/NLU.php:842 msgid "Process content on update" msgstr "" -#: includes/Classifai/Providers/Watson/NLU.php:851 +#: includes/Classifai/Providers/Watson/NLU.php:849 #. translators: %s Post type label msgid "Classify %s" msgstr "" diff --git a/readme.txt b/readme.txt index 9b686015c..46c49d387 100644 --- a/readme.txt +++ b/readme.txt @@ -4,7 +4,7 @@ Tags: AI, Artifical Intelligence, ML, Machine Learning, Microsoft A Requires at least: 5.7 Tested up to: 6.2 Requires PHP: 7.4 -Stable tag: 2.2.0 +Stable tag: 2.2.1 License: GPLv2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html @@ -14,6 +14,8 @@ Supercharge WordPress Content Workflows and Engagement with Artificial Intellige Tap into leading cloud-based services like [OpenAI](https://openai.com/), [Microsoft Azure AI](https://azure.microsoft.com/en-us/overview/ai-platform/), and [IBM Watson](https://www.ibm.com/watson) to augment your WordPress-powered websites. Publish content faster while improving SEO performance and increasing audience engagement. ClassifAI integrates Artificial Intelligence and Machine Learning technologies to lighten your workload and eliminate tedious tasks, giving you more time to create original content that matters. +*You can learn more about ClassifAI's features at [ClassifAIPlugin.com](https://classifaiplugin.com/) and documentation at the [ClassifAI documentation site](https://10up.github.io/classifai/).* + **Features** * Generate a summary of post content and store it as an excerpt using [OpenAI's ChatGPT API](https://platform.openai.com/docs/guides/chat) diff --git a/vendor/autoload.php b/vendor/autoload.php index f586675a0..e5257fbe6 100644 --- a/vendor/autoload.php +++ b/vendor/autoload.php @@ -22,4 +22,4 @@ require_once __DIR__ . '/composer/autoload_real.php'; -return ComposerAutoloaderInit34f74af76e37894d26924a3481f854c9::getLoader(); +return ComposerAutoloaderInit78ebc9d8bf725b931b62796c1ed5a4cf::getLoader(); diff --git a/vendor/bin/uaparser b/vendor/bin/uaparser index 15456552e..f64f0bb06 100755 --- a/vendor/bin/uaparser +++ b/vendor/bin/uaparser @@ -112,9 +112,8 @@ if (PHP_VERSION_ID < 80000) { (function_exists('stream_get_wrappers') && in_array('phpvfscomposer', stream_get_wrappers(), true)) || (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper')) ) { - include("phpvfscomposer://" . __DIR__ . '/..'.'/ua-parser/uap-php/bin/uaparser'); - exit(0); + return include("phpvfscomposer://" . __DIR__ . '/..'.'/ua-parser/uap-php/bin/uaparser'); } } -include __DIR__ . '/..'.'/ua-parser/uap-php/bin/uaparser'; +return include __DIR__ . '/..'.'/ua-parser/uap-php/bin/uaparser'; diff --git a/vendor/composer/autoload_real.php b/vendor/composer/autoload_real.php index 8596930aa..3ebcf4157 100644 --- a/vendor/composer/autoload_real.php +++ b/vendor/composer/autoload_real.php @@ -2,7 +2,7 @@ // autoload_real.php @generated by Composer -class ComposerAutoloaderInit34f74af76e37894d26924a3481f854c9 +class ComposerAutoloaderInit78ebc9d8bf725b931b62796c1ed5a4cf { private static $loader; @@ -24,16 +24,16 @@ public static function getLoader() require __DIR__ . '/platform_check.php'; - spl_autoload_register(array('ComposerAutoloaderInit34f74af76e37894d26924a3481f854c9', 'loadClassLoader'), true, true); + spl_autoload_register(array('ComposerAutoloaderInit78ebc9d8bf725b931b62796c1ed5a4cf', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__)); - spl_autoload_unregister(array('ComposerAutoloaderInit34f74af76e37894d26924a3481f854c9', 'loadClassLoader')); + spl_autoload_unregister(array('ComposerAutoloaderInit78ebc9d8bf725b931b62796c1ed5a4cf', 'loadClassLoader')); require __DIR__ . '/autoload_static.php'; - call_user_func(\Composer\Autoload\ComposerStaticInit34f74af76e37894d26924a3481f854c9::getInitializer($loader)); + call_user_func(\Composer\Autoload\ComposerStaticInit78ebc9d8bf725b931b62796c1ed5a4cf::getInitializer($loader)); $loader->register(true); - $filesToLoad = \Composer\Autoload\ComposerStaticInit34f74af76e37894d26924a3481f854c9::$files; + $filesToLoad = \Composer\Autoload\ComposerStaticInit78ebc9d8bf725b931b62796c1ed5a4cf::$files; $requireFile = \Closure::bind(static function ($fileIdentifier, $file) { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php index 3df80dd13..85cc99836 100644 --- a/vendor/composer/autoload_static.php +++ b/vendor/composer/autoload_static.php @@ -4,7 +4,7 @@ namespace Composer\Autoload; -class ComposerStaticInit34f74af76e37894d26924a3481f854c9 +class ComposerStaticInit78ebc9d8bf725b931b62796c1ed5a4cf { public static $files = array ( '7166494aeff09009178f278afd86c83f' => __DIR__ . '/..' . '/yahnis-elsts/plugin-update-checker/load-v4p13.php', @@ -46,9 +46,9 @@ class ComposerStaticInit34f74af76e37894d26924a3481f854c9 public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { - $loader->prefixLengthsPsr4 = ComposerStaticInit34f74af76e37894d26924a3481f854c9::$prefixLengthsPsr4; - $loader->prefixDirsPsr4 = ComposerStaticInit34f74af76e37894d26924a3481f854c9::$prefixDirsPsr4; - $loader->classMap = ComposerStaticInit34f74af76e37894d26924a3481f854c9::$classMap; + $loader->prefixLengthsPsr4 = ComposerStaticInit78ebc9d8bf725b931b62796c1ed5a4cf::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInit78ebc9d8bf725b931b62796c1ed5a4cf::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInit78ebc9d8bf725b931b62796c1ed5a4cf::$classMap; }, null, ClassLoader::class); } diff --git a/vendor/composer/installed.php b/vendor/composer/installed.php index df700a08d..36cefb97a 100644 --- a/vendor/composer/installed.php +++ b/vendor/composer/installed.php @@ -3,7 +3,7 @@ 'name' => '10up/classifai', 'pretty_version' => 'dev-trunk', 'version' => 'dev-trunk', - 'reference' => 'c2ddfb4434f0a52913b86bd6cb2874c2a7966a45', + 'reference' => '851b912be815521d54dcbaed691828cdbabcf6cc', 'type' => 'wordpress-plugin', 'install_path' => __DIR__ . '/../../', 'aliases' => array(), @@ -13,7 +13,7 @@ '10up/classifai' => array( 'pretty_version' => 'dev-trunk', 'version' => 'dev-trunk', - 'reference' => 'c2ddfb4434f0a52913b86bd6cb2874c2a7966a45', + 'reference' => '851b912be815521d54dcbaed691828cdbabcf6cc', 'type' => 'wordpress-plugin', 'install_path' => __DIR__ . '/../../', 'aliases' => array(),