From 9996091afbd69c29ee80c9c293dce134a803e59e Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 14 Feb 2025 13:13:51 -0500 Subject: [PATCH 01/35] Add support for conditional hooks that match method return values. For details see: https://processwire.com/docs/modules/hooks/#conditional-hooks-matching-return-value-or-type --- wire/core/WireHooks.php | 190 ++++++++++++++++++++++++++++++---------- 1 file changed, 145 insertions(+), 45 deletions(-) diff --git a/wire/core/WireHooks.php b/wire/core/WireHooks.php index dfa5a6543..1c773d49e 100644 --- a/wire/core/WireHooks.php +++ b/wire/core/WireHooks.php @@ -47,6 +47,7 @@ class WireHooks { * - fromClass: the name of the class containing the hooked method, if not the object where addHook was executed. Set automatically, but you may still use in some instances. * - argMatch: array of Selectors objects where the indexed argument (n) to the hooked method must match, order to execute hook. * - objMatch: Selectors object that the current object must match in order to execute hook + * - retMatch: Selectors object that must match the return value, or a match string to match return value * - public: auto-assigned to true or false by addHook() as to whether the method is public or private/protected. * */ @@ -58,7 +59,10 @@ class WireHooks { 'allInstances' => false, 'fromClass' => '', 'argMatch' => null, + 'argMatchType' => [], 'objMatch' => null, + 'retMatch' => null, + 'retMatchType' => '', ); /** @@ -631,8 +635,21 @@ public function addHook(Wire $object, $method, $toObject, $toMethod = null, $opt $options['fromClass'] = $fromClass; } + $retMatch = ''; $argOpen = strpos($method, '('); - if($argOpen) { + + if($argOpen) { + if(strpos($method, ':(')) { + list($method, $retMatch) = explode(':(', $method, 2); + $retMatch = rtrim($retMatch, ') '); + } else if(strpos($method, ':<') && substr(trim($method), -1) === '>') { + list($method, $retMatch) = explode(':<', $method, 2); + $retMatch = "<$retMatch"; + } + $argOpen = strpos($method, '('); + } + + if($argOpen) { // arguments to match may be specified in method name $argClose = strpos($method, ')'); if($argClose === $argOpen+1) { @@ -659,18 +676,31 @@ public function addHook(Wire $object, $method, $toObject, $toMethod = null, $opt // just single argument specified, so argument 0 is assumed } if(is_string($argMatch)) $argMatch = array(0 => $argMatch); + $argMatchType = []; foreach($argMatch as $argKey => $argVal) { - if(Selectors::stringHasSelector($argVal)) { - /** @var Selectors $selectors */ - $selectors = $this->wire->wire(new Selectors()); - $selectors->init($argVal); - $argMatch[$argKey] = $selectors; - } + list($argVal, $argValType) = $this->prepareArgMatch($argVal); + $argMatch[$argKey] = $argVal; + $argMatchType[$argKey] = $argValType; + } + if(count($argMatch)) { + $options['argMatch'] = $argMatch; + $options['argMatchType'] = $argMatchType; } - if(count($argMatch)) $options['argMatch'] = $argMatch; } + } else if(strpos($method, ':')) { + list($method, $retMatch) = explode(':', $method, 2); } + if($retMatch) { + // match return value + if($options['before'] && !$options['after']) { + throw new WireException('You cannot match return values with “before” hooks'); + } + list($retMatch, $retMatchType) = $this->prepareArgMatch($retMatch); + $options['retMatch'] = $retMatch; + $options['retMatchType'] = $retMatchType; + } + $localHooks = $object->getLocalHooks(); if($options['allInstances'] || $options['fromClass']) { @@ -996,50 +1026,25 @@ public function runHooks(Wire $object, $method, $arguments, $type = 'method') { if($type == 'method' && !empty($hook['options']['argMatch'])) { // argument comparison to determine at runtime whether to execute the hook $argMatches = $hook['options']['argMatch']; + $argMatchTypes = $hook['options']['argMatchType']; $matches = true; foreach($argMatches as $argKey => $argMatch) { /** @var Selectors $argMatch */ + $argMatchType = isset($argMatchTypes[$argKey]) ? $argMatchTypes[$argKey] : ''; $argVal = isset($arguments[$argKey]) ? $arguments[$argKey] : null; - if(is_object($argMatch)) { - // Selectors object - if(is_object($argVal)) { - $matches = $argMatch->matches($argVal); - } else { - // we don't work with non-object here - $matches = false; - } - } else if(is_string($argMatch) && strpos($argMatch, '<') === 0 && substr($argMatch, -1) === '>') { - // i.e. , , , , , etc. - $argMatch = trim($argMatch, '<>'); - if(strpos($argMatch, '|')) { - // i.e. or etc. - $argMatches = explode('|', str_replace(array('<', '>'), '', $argMatch)); - } else { - $argMatches = array($argMatch); - } - foreach($argMatches as $argMatchType) { - if(isset($this->argMatchTypes[$argMatchType])) { - $argMatchFunc = $this->argMatchTypes[$argMatchType]; - $matches = $argMatchFunc($argVal); - } else { - $matches = wireInstanceOf($argVal, $argMatchType); - } - if($matches) break; - } - } else { - if(is_array($argVal)) { - // match any array element - $matches = in_array($argMatch, $argVal); - } else { - // exact string match - $matches = $argMatch == $argVal; - } - } + $matches = $this->conditionalArgMatch($argMatch, $argVal, $argMatchType); if(!$matches) break; } if(!$matches) continue; // don't run hook } + if($type === 'method' && $when === 'after' && !empty($hook['options']['retMatch'])) { + if(!$this->conditionalArgMatch( + $hook['options']['retMatch'], + $result['return'], + $hook['options']['retMatchType'])) continue; + } + if($this->allowPathHooks && isset($this->pathHooks[$hook['id']])) { $allowRunPathHook = $this->allowRunPathHook($hook['id'], $arguments); $this->removeHook($object, $hook['id']); // once only @@ -1135,9 +1140,104 @@ public function runHooks(Wire $object, $method, $arguments, $type = 'method') { } /** - * Allow given path hook to run? + * Prepare argument match + * + * @param string $argMatch + * @return array + * @since 3.0.247 + * + */ + protected function prepareArgMatch($argMatch) { + $argMatch = trim($argMatch, '()'); + $argMatchType = ''; + + list($c1, $c2, $c3) = [ substr($argMatch, 0, 1), substr($argMatch, -1), substr($argMatch, 0, 2) ]; + + if($c1 === '<' && $c2 === '>') { + // i.e. or + $argMatchType = 'instanceof'; + $argMatch = trim($argMatch, '<>'); + + } else if($c1 === '=' || $c1 === '<' || $c1 === '>' || Selectors::isOperator($c3)) { + // selector that starts with operator and translates to "argVal matches argMatch" + $argMatch = "___val$argMatch"; // i.e. ___val=something + $argMatchType = 'selector'; + } + + if($argMatchType === 'instanceof') { + // ok + $argMatch = strpos($argMatch, '|') ? explode('|', $argMatch) : [ $argMatch ]; + } else if(Selectors::stringHasSelector($argMatch)) { + /** @var Selectors $selectors */ + $selectors = $this->wire->wire(new Selectors()); + $selectors->init($argMatch); + $argMatch = $selectors; + $argMatchType = 'selector'; + } else { + $argMatchType = 'equals'; + } + + return [ $argMatch, $argMatchType ]; + } + + /** + * Does given value match given match condition? + * + * @param Selectors|string $argMatch + * @param mixed $argVal + * @return bool + * @since 3.0.247 * - * This checks if the hook’s path matches the request path, allowing for both + */ + protected function conditionalArgMatch($argMatch, $argVal, $argMatchType) { + + $matches = false; + + if($argMatch instanceof Selectors) { + // Selectors object + /** @var Selector $s */ + $s = $argMatch->first(); + if($s instanceof Selector && $s->field() === '___val') { + $o = WireData(); + $o->set('value', $argVal); + $s->field = 'value'; + $argVal = $o; + } else if(is_array($argVal)) { + $argVal = count($argVal) && is_string(key($argVal)) ? WireData($argVal) : WireArray($argVal); + } + if(is_object($argVal)) { + $matches = $argMatch->matches($argVal); + } + + } else if($argMatchType === 'instanceof') { + if(!is_array($argMatch)) $argMatch = [ $argMatch ]; + foreach($argMatch as $type) { + if(isset($this->argMatchTypes[$type])) { + $argMatchFunc = $this->argMatchTypes[$type]; + $matches = $argMatchFunc($argVal); + } else { + $matches = wireInstanceOf($argVal, $type); + } + if($matches) break; + } + + } else if(is_array($argVal)) { + // match any array element + $matches = in_array($argMatch, $argVal); + + } else { + // exact match + $matches = $argMatch == $argVal; + } + + return $matches; + + } + + /** + * Allow given path hook to run? + * + * This checks if the hook’s path matches the request path, allowing for both * regular and regex matches and populating parenthesized portions to arguments * that will appear in the HookEvent. * From 668081fb23139b99695efe250841efb30b2fe178 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 14 Feb 2025 14:43:37 -0500 Subject: [PATCH 02/35] Fix issue processwire/processwire-issues#2041 --- wire/core/WireHooks.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/wire/core/WireHooks.php b/wire/core/WireHooks.php index 1c773d49e..1e22c9fcd 100644 --- a/wire/core/WireHooks.php +++ b/wire/core/WireHooks.php @@ -1275,6 +1275,15 @@ protected function allowRunPathHook($id, array &$arguments) { $regexDelim = $matchPath[0]; } else { // needs to be in regex format + if(strpos($matchPath, '.') !== false) { + // preserve some regex sequences containing periods + $r = [ '.+' => '•+', '.*' => '•*', '\\.' => '\\•' ]; + $matchPath = str_replace(array_keys($r), array_values($r), $matchPath); + // force any remaining periods to be taken literally + $matchPath = str_replace('.', '\\.', $matchPath); + // restore regex sequences containing periods + $matchPath = str_replace(array_values($r), array_keys($r), $matchPath); + } if(strpos($matchPath, '/') === 0) $matchPath = "^$matchPath"; $matchPath = "#$matchPath$#"; } From 8ee238ea70873135253abe0bbe812730de65981f Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 14 Feb 2025 14:58:18 -0500 Subject: [PATCH 03/35] Fix issue processwire/processwire-issues#2045 --- wire/modules/Inputfield/InputfieldTinyMCE/plugins/pwimage.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/wire/modules/Inputfield/InputfieldTinyMCE/plugins/pwimage.js b/wire/modules/Inputfield/InputfieldTinyMCE/plugins/pwimage.js index 06914a418..6696383a1 100644 --- a/wire/modules/Inputfield/InputfieldTinyMCE/plugins/pwimage.js +++ b/wire/modules/Inputfield/InputfieldTinyMCE/plugins/pwimage.js @@ -228,7 +228,8 @@ function pwTinyMCE_image(editor) { }); $iframe.setButtons(buttons); - $iframe.setTitle($i.find('title').html()); + var title = $i.find('title').html(); + if(title.length) $iframe.setTitle(title); } /** From a8ea9544626c0b47c169e22a11852d253a1bf148 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 14 Feb 2025 15:00:04 -0500 Subject: [PATCH 04/35] Bump version to 3.0.247 --- wire/core/ProcessWire.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wire/core/ProcessWire.php b/wire/core/ProcessWire.php index ccef294d5..4862c8e25 100644 --- a/wire/core/ProcessWire.php +++ b/wire/core/ProcessWire.php @@ -80,7 +80,7 @@ class ProcessWire extends Wire { * Reversion revision number * */ - const versionRevision = 246; + const versionRevision = 247; /** * Version suffix string (when applicable) From b7636bc1df35c977aeadddd7dac4f53b86d28786 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 28 Feb 2025 13:53:03 -0500 Subject: [PATCH 05/35] I seem to be bad at spelling the word langauges oops languages --- .../Inputfield/InputfieldTextTags/InputfieldTextTags.module | 2 +- .../Inputfield/InputfieldToggle/InputfieldToggle.module | 3 +-- wire/modules/LanguageSupport/Languages.php | 2 +- wire/modules/Process/ProcessField/ProcessField.module | 4 ++-- wire/modules/Process/ProcessTemplate/ProcessTemplate.module | 2 +- 5 files changed, 6 insertions(+), 7 deletions(-) diff --git a/wire/modules/Inputfield/InputfieldTextTags/InputfieldTextTags.module b/wire/modules/Inputfield/InputfieldTextTags/InputfieldTextTags.module index f0107b688..b6bc00795 100644 --- a/wire/modules/Inputfield/InputfieldTextTags/InputfieldTextTags.module +++ b/wire/modules/Inputfield/InputfieldTextTags/InputfieldTextTags.module @@ -461,7 +461,7 @@ class InputfieldTextTags extends Inputfield implements * */ public function getTagLabel($tag, $language = null) { - if(!$language && $this->wire()->langauges) $language = $this->wire()->user->language; + if(!$language && $this->wire()->languages) $language = $this->wire()->user->language; $tags = $this->getTagsList($language); if(isset($tags[$tag])) return $tags[$tag]; if($this->allowUserTags()) return $tag; diff --git a/wire/modules/Inputfield/InputfieldToggle/InputfieldToggle.module b/wire/modules/Inputfield/InputfieldToggle/InputfieldToggle.module index fc34ec45e..f13c1b0ba 100644 --- a/wire/modules/Inputfield/InputfieldToggle/InputfieldToggle.module +++ b/wire/modules/Inputfield/InputfieldToggle/InputfieldToggle.module @@ -491,8 +491,7 @@ class InputfieldToggle extends Inputfield { if($labelType === null) $labelType = $this->labelType; - /** @var Languages $langauges */ - $languages = $this->wire('languages'); + $languages = $this->wire()->languages; $setLanguage = false; $languageId = ''; $yes = ''; diff --git a/wire/modules/LanguageSupport/Languages.php b/wire/modules/LanguageSupport/Languages.php index f8f2d0d2f..32c8d4a9e 100644 --- a/wire/modules/LanguageSupport/Languages.php +++ b/wire/modules/LanguageSupport/Languages.php @@ -431,7 +431,7 @@ public function unsetLanguage() { * $languages->setLocale(LC_ALL, 'en_US.UTF-8'); * * // Set locale for specific category (CTYPE) - * $langauges->setLocale(LC_CTYPE, 'en_US.UTF-8'); + * $languages->setLocale(LC_CTYPE, 'en_US.UTF-8'); * * // Try multiple locales till one works (in order) using array * $languages->setLocale(LC_ALL, [ 'en_US.UTF-8', 'en_US', 'en' ]); diff --git a/wire/modules/Process/ProcessField/ProcessField.module b/wire/modules/Process/ProcessField/ProcessField.module index 758216164..5864c578d 100644 --- a/wire/modules/Process/ProcessField/ProcessField.module +++ b/wire/modules/Process/ProcessField/ProcessField.module @@ -1692,7 +1692,7 @@ class ProcessField extends Process implements ConfigurableModule { protected function buildEditFormTypeSelect() { $modules = $this->wire()->modules; - $languages = $this->wire()->langauges; + $languages = $this->wire()->languages; $fields = $this->wire()->fields; $config = $this->wire()->config; $isNew = !$this->field || !$this->field->id; @@ -3263,7 +3263,7 @@ class ProcessField extends Process implements ConfigurableModule { */ public function search($text, array $options = array()) { - $languages = $this->wire()->langauges; + $languages = $this->wire()->languages; $page = $this->getProcessPage(); $result = array( diff --git a/wire/modules/Process/ProcessTemplate/ProcessTemplate.module b/wire/modules/Process/ProcessTemplate/ProcessTemplate.module index be0631d25..991a10abd 100644 --- a/wire/modules/Process/ProcessTemplate/ProcessTemplate.module +++ b/wire/modules/Process/ProcessTemplate/ProcessTemplate.module @@ -3851,7 +3851,7 @@ class ProcessTemplate extends Process implements ConfigurableModule { */ public function search($text, array $options = array()) { - $languages = $this->wire()->langauges; + $languages = $this->wire()->languages; $page = $this->getProcessPage(); $property = isset($options['property']) ? $options['property'] : ''; From 0c3c15c29d684142c74b1f7082496cebf4201560 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 28 Feb 2025 14:00:45 -0500 Subject: [PATCH 06/35] Fix issue processwire/processwire-issues#2052 --- wire/modules/Process/ProcessPageSearch/ProcessPageSearchLive.php | 1 + 1 file changed, 1 insertion(+) diff --git a/wire/modules/Process/ProcessPageSearch/ProcessPageSearchLive.php b/wire/modules/Process/ProcessPageSearch/ProcessPageSearchLive.php index b1dc3ad3b..7c9476b82 100644 --- a/wire/modules/Process/ProcessPageSearch/ProcessPageSearchLive.php +++ b/wire/modules/Process/ProcessPageSearch/ProcessPageSearchLive.php @@ -262,6 +262,7 @@ protected function init(array $presets = array()) { $q = empty($presets['q']) ? $input->get('q') : $presets['q']; if(empty($q)) $q = $input->get('admin_search'); // legacy name + $q = (string) $q; if(strpos($q, '~@') !== false) $q = str_replace('~@', '', $q); // disallow placeholder prefix if(empty($operator)) $q = str_replace(array_keys($opHolders), array_values($opHolders), $q); $q = $sanitizer->text($q, array('reduceSpace' => true)); From afacf9179242a941e6a7e0f076f09dd619cdf256 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 28 Feb 2025 14:27:41 -0500 Subject: [PATCH 07/35] Fix issue processwire/processwire-issues#2051 --- .../Inputfield/InputfieldTextTags/InputfieldTextTags.module | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/wire/modules/Inputfield/InputfieldTextTags/InputfieldTextTags.module b/wire/modules/Inputfield/InputfieldTextTags/InputfieldTextTags.module index b6bc00795..b4ea34585 100644 --- a/wire/modules/Inputfield/InputfieldTextTags/InputfieldTextTags.module +++ b/wire/modules/Inputfield/InputfieldTextTags/InputfieldTextTags.module @@ -602,7 +602,9 @@ class InputfieldTextTags extends Inputfield implements $cfgName = $opts['cfgName']; $out .= "<$script>"; foreach($tags as $val => $label) { - $out .= "ProcessWire.config." . $cfgName . "['$val'] = '$label';"; + $val = json_encode($val); + $label = json_encode($label); + $out .= "ProcessWire.config." . $cfgName . "[$val] = $label;"; } $out .= ""; } From a17ebff0cdb5093e4109f5c556aacc28724c0459 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 7 Mar 2025 14:32:38 -0500 Subject: [PATCH 08/35] Normalize background for file/image Inputfields in AdminThemeUikit --- wire/modules/AdminTheme/AdminThemeUikit/AdminThemeUikit.module | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wire/modules/AdminTheme/AdminThemeUikit/AdminThemeUikit.module b/wire/modules/AdminTheme/AdminThemeUikit/AdminThemeUikit.module index 7324482f7..416f8b6cc 100644 --- a/wire/modules/AdminTheme/AdminThemeUikit/AdminThemeUikit.module +++ b/wire/modules/AdminTheme/AdminThemeUikit/AdminThemeUikit.module @@ -363,7 +363,7 @@ class AdminThemeUikit extends AdminThemeFramework implements Module, Configurabl } else if($inputfield instanceof InputfieldSelect && !$inputfield instanceof InputfieldHasArrayValue) { $inputClasses[] = $this->getClass('select'); } else if($inputfield instanceof InputfieldFile) { - $themeColor = 'secondary'; + // $themeColor = 'secondary'; } if($field) { From 422d9c1eb6b31af075f62bd941d1ea982e79b391 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 7 Mar 2025 14:35:46 -0500 Subject: [PATCH 09/35] Adjustment to ProcessLogin --- wire/modules/Process/ProcessLogin/ProcessLogin.css | 13 ++++++++++++- .../Process/ProcessLogin/ProcessLogin.module | 4 ++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/wire/modules/Process/ProcessLogin/ProcessLogin.css b/wire/modules/Process/ProcessLogin/ProcessLogin.css index a6327855e..e681f4548 100644 --- a/wire/modules/Process/ProcessLogin/ProcessLogin.css +++ b/wire/modules/Process/ProcessLogin/ProcessLogin.css @@ -12,6 +12,18 @@ ul.Inputfields #login_pass { width: 100%; } +ul.Inputfields .InputfieldHeaderHidden + .InputfieldContent { + padding: 10px; +} + +ul.Inputfields .Inputfield_login_name .InputfieldContent { + padding: 0 10px 0 10px; +} + +ul.Inputfilds .Inputfield_login_pass .InputfieldContent { + padding: 0 10px 10px 10px; +} + ul.Inputfields .InputfieldSubmit { clear: both; } @@ -31,4 +43,3 @@ ul.Inputfields .InputfieldSubmit { .ProcessLogin #ProcessLoginForm.tfa { width: 300px; } - diff --git a/wire/modules/Process/ProcessLogin/ProcessLogin.module b/wire/modules/Process/ProcessLogin/ProcessLogin.module index 4d10499d3..e5a7fd8ab 100644 --- a/wire/modules/Process/ProcessLogin/ProcessLogin.module +++ b/wire/modules/Process/ProcessLogin/ProcessLogin.module @@ -727,6 +727,8 @@ class ProcessLogin extends Process implements ConfigurableModule { $this->nameField->attr('class', $this->className() . 'Name'); $this->nameField->addClass('InputfieldFocusFirst'); $this->nameField->collapsed = Inputfield::collapsedNever; + $this->nameField->attr('placeholder', $nameInputLabel); + $this->nameField->skipLabel = Inputfield::skipLabelHeader; $this->passField = $modules->get('InputfieldText'); $this->passField->set('label', $this->labels('password')); // Login form: password field label @@ -734,6 +736,8 @@ class ProcessLogin extends Process implements ConfigurableModule { $this->passField->attr('type', 'password'); $this->passField->attr('class', $this->className() . 'Pass'); $this->passField->collapsed = Inputfield::collapsedNever; + $this->passField->attr('placeholder', $this->labels('password')); + $this->passField->skipLabel = Inputfield::skipLabelHeader; $this->submitField = $modules->get('InputfieldSubmit'); $this->submitField->attr('name', 'login_submit'); From 4725ece5f86374a8de73d132e54b0ac4c9ae1f09 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 7 Mar 2025 14:36:11 -0500 Subject: [PATCH 10/35] Fix ProcessPageLister issue when a custom page class is expected for a page without an ID --- wire/modules/Process/ProcessPageLister/ProcessPageLister.module | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wire/modules/Process/ProcessPageLister/ProcessPageLister.module b/wire/modules/Process/ProcessPageLister/ProcessPageLister.module index 0f4add0b2..b50c6a5d3 100644 --- a/wire/modules/Process/ProcessPageLister/ProcessPageLister.module +++ b/wire/modules/Process/ProcessPageLister/ProcessPageLister.module @@ -1147,7 +1147,7 @@ class ProcessPageLister extends Process implements ConfigurableModule { if(count($templates)) { // user specified 1 or more templates $numEditable = 0; - $testPage = $pages->newPage(); + $testPage = $pages->newPage( [ 'template' => reset($templates) ] ); $testPage->id = 999; // required (any ID number works) if($this->wire()->permissions->has('page-publish')) { $testPage->addStatus(Page::statusUnpublished); From 6783c4824b8a3b0afec18e2922c6bd8eec23aa94 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Sun, 16 Mar 2025 10:00:40 -0400 Subject: [PATCH 11/35] Fix function call error in PagesVersions module hasPageVersions method --- wire/modules/Pages/PagesVersions/PagesVersions.module.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wire/modules/Pages/PagesVersions/PagesVersions.module.php b/wire/modules/Pages/PagesVersions/PagesVersions.module.php index 1ecd169c5..e8b327cc9 100644 --- a/wire/modules/Pages/PagesVersions/PagesVersions.module.php +++ b/wire/modules/Pages/PagesVersions/PagesVersions.module.php @@ -425,7 +425,7 @@ public function hasPageVersion(Page $page, $version = 0) { * */ public function hasPageVersions(Page $page) { - $database = $this->wire()->database(); + $database = $this->wire()->database; $table = self::versionsTable; $sql = "SELECT COUNT(*) FROM $table WHERE pages_id=:pages_id"; $query = $database->prepare($sql); From bc8a1959f351d481c4a911fbc2dfc5407d085bce Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 28 Mar 2025 13:05:54 -0400 Subject: [PATCH 12/35] Fix issue processwire/processwire-issues#2058 --- wire/modules/Fieldtype/FieldtypePage.module | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wire/modules/Fieldtype/FieldtypePage.module b/wire/modules/Fieldtype/FieldtypePage.module index db3a454a2..71a85b10c 100644 --- a/wire/modules/Fieldtype/FieldtypePage.module +++ b/wire/modules/Fieldtype/FieldtypePage.module @@ -150,7 +150,7 @@ class FieldtypePage extends FieldtypeMulti implements Module, ConfigurableModule public function ___getFieldSetups() { $setups = parent::___getFieldSetups(); /** @var InputfieldPage $f */ - $f = $this->wire()->modules->getModule('InputfieldPage', array('noInit' => true)); + $f = $this->wire()->modules->getModule('InputfieldPage'); return array_merge($setups, $f->getFieldSetups()); } From dae4e59db9050df993e466543bc668954fb7a542 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 28 Mar 2025 13:21:05 -0400 Subject: [PATCH 13/35] Fix issue processwire/processwire-issues#2057 --- wire/core/PageComparison.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wire/core/PageComparison.php b/wire/core/PageComparison.php index 352d8f668..afe84a131 100644 --- a/wire/core/PageComparison.php +++ b/wire/core/PageComparison.php @@ -177,8 +177,8 @@ public function _if(Page $page, $key, $yes = '', $no = '') { // action is just a string to return $result = $action; } - - } else if(is_callable($action)) { + + } else if(is_callable($action) && (!is_object($action) || $action instanceof \Closure)) { // action is callable $result = call_user_func_array($action, array($val, $key, $page)); From ee96262e4429119237dcda1f1edb38c9167edb59 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 28 Mar 2025 13:22:34 -0400 Subject: [PATCH 14/35] Fix issue processwire/processwire-issues#2056 --- wire/core/InputfieldWrapper.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wire/core/InputfieldWrapper.php b/wire/core/InputfieldWrapper.php index 42d37a129..4d8c6ac2a 100644 --- a/wire/core/InputfieldWrapper.php +++ b/wire/core/InputfieldWrapper.php @@ -769,7 +769,7 @@ public function ___render() { if(in_array($collapsed, $lockedStates)) $renderValueMode = true; $ffOut = $this->renderInputfield($inputfield, $renderValueMode); - if(!strlen($ffOut)) continue; + if(!strlen("$ffOut")) continue; $collapsed = (int) $inputfield->getSetting('collapsed'); // retrieve again after render $entityEncodeText = $inputfield->getSetting('entityEncodeText') === false ? false : true; From 2715611949782f024cd8ea498fd863548cf69196 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 28 Mar 2025 14:10:24 -0400 Subject: [PATCH 15/35] Updates for ProcessLogin and Inputfield::skipLabelHidden option --- wire/core/InputfieldWrapper.php | 6 ++++-- wire/modules/AdminTheme/AdminThemeUikit/init.php | 3 +-- wire/modules/Process/ProcessLogin/ProcessLogin.css | 10 +++++----- wire/modules/Process/ProcessLogin/ProcessLogin.module | 10 ++++++---- 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/wire/core/InputfieldWrapper.php b/wire/core/InputfieldWrapper.php index 4d8c6ac2a..c0fbdb6d1 100644 --- a/wire/core/InputfieldWrapper.php +++ b/wire/core/InputfieldWrapper.php @@ -89,7 +89,7 @@ class InputfieldWrapper extends Inputfield implements \Countable, \IteratorAggre 'list' => "
    {out}
", 'item' => "
  • {out}
  • ", 'item_label' => "", - 'item_label_hidden' => "", + 'item_label_hidden' => "", 'item_content' => "
    {out}
    ", 'item_error' => "

    {out}

    ", 'item_description' => "

    {out}

    ", @@ -894,7 +894,9 @@ public function ___render() { } if($skipLabel === Inputfield::skipLabelHeader || $quietMode) { // label only shows when field is collapsed - $label = str_replace('{out}', $icon . $label . $toggle, $markup['item_label_hidden']); + $labelHidden = $markup['item_label_hidden']; + if(strpos($labelHidden, '{for}')) $labelHidden = str_replace('{for}', $inputfield->attr('id'), $labelHidden); + $label = str_replace('{out}', $icon . $label . $toggle, $labelHidden); } else { // label always visible $label = str_replace('{out}', $icon . $label . $toggle, $markup['item_label']); diff --git a/wire/modules/AdminTheme/AdminThemeUikit/init.php b/wire/modules/AdminTheme/AdminThemeUikit/init.php index f0e4d3a68..ceca8c0fa 100644 --- a/wire/modules/AdminTheme/AdminThemeUikit/init.php +++ b/wire/modules/AdminTheme/AdminThemeUikit/init.php @@ -150,7 +150,7 @@ $markup = InputfieldWrapper::getMarkup(); $markup['list'] = "
      {out}
    "; $markup['item_label'] = ""; -$markup['item_label_hidden'] = ""; +$markup['item_label_hidden'] = ""; $markup['item_content'] = "
    {out}
    "; InputfieldWrapper::setMarkup($markup); @@ -161,4 +161,3 @@ } else { $config->InputfieldWrapper('useColumnWidth', 2); // 2=use both style='width:%' and data-colwidth attributes } - diff --git a/wire/modules/Process/ProcessLogin/ProcessLogin.css b/wire/modules/Process/ProcessLogin/ProcessLogin.css index e681f4548..b3db7e228 100644 --- a/wire/modules/Process/ProcessLogin/ProcessLogin.css +++ b/wire/modules/Process/ProcessLogin/ProcessLogin.css @@ -12,18 +12,18 @@ ul.Inputfields #login_pass { width: 100%; } -ul.Inputfields .InputfieldHeaderHidden + .InputfieldContent { - padding: 10px; -} - ul.Inputfields .Inputfield_login_name .InputfieldContent { padding: 0 10px 0 10px; } -ul.Inputfilds .Inputfield_login_pass .InputfieldContent { +ul.Inputfields .Inputfield_login_pass .InputfieldContent { padding: 0 10px 10px 10px; } +ul.Inputfields .Inputfield_login_pass > .InputfieldHeaderHidden + .InputfieldContent { + padding-top: 10px; +} + ul.Inputfields .InputfieldSubmit { clear: both; } diff --git a/wire/modules/Process/ProcessLogin/ProcessLogin.module b/wire/modules/Process/ProcessLogin/ProcessLogin.module index e5a7fd8ab..b851e30f8 100644 --- a/wire/modules/Process/ProcessLogin/ProcessLogin.module +++ b/wire/modules/Process/ProcessLogin/ProcessLogin.module @@ -19,6 +19,7 @@ * @property array $tfaRememberFingerprints Means by which to fingerprint user’s browser * @property string $tfaAutoType Auto-enable type, aka module name (default='') * @property array $tfaAutoRoleIDs Auto-enable for these role IDs, or blank for all roles. Applies only if $tfaAutoType selected (default=[]) + * @property int $skipLabel Optionally populate with an Inputfield::skipLabel* constant to be used on the login form inputs. * * @method void beforeLogin() #pw-hooker * @method void afterLogin() #pw-hooker @@ -170,6 +171,7 @@ class ProcessLogin extends Process implements ConfigurableModule { $this->set('tfaAutoRoleIDs', array()); $this->set('allowEmail', false); $this->set('emailField', 'email'); + $this->set('skipLabel', Inputfield::skipLabelNo); // Alternate is: Inputfield::InputfieldHeaderHidden $this->customMarkup['forgot-icon'] = wireIconMarkup('question-circle', 'fw'); $this->customMarkup['home-icon'] = wireIconMarkup('home', 'fw'); parent::__construct(); @@ -727,8 +729,8 @@ class ProcessLogin extends Process implements ConfigurableModule { $this->nameField->attr('class', $this->className() . 'Name'); $this->nameField->addClass('InputfieldFocusFirst'); $this->nameField->collapsed = Inputfield::collapsedNever; - $this->nameField->attr('placeholder', $nameInputLabel); - $this->nameField->skipLabel = Inputfield::skipLabelHeader; + $this->nameField->skipLabel = $this->skipLabel; + if($this->skipLabel) $this->nameField->attr('placeholder', $nameInputLabel); $this->passField = $modules->get('InputfieldText'); $this->passField->set('label', $this->labels('password')); // Login form: password field label @@ -736,8 +738,8 @@ class ProcessLogin extends Process implements ConfigurableModule { $this->passField->attr('type', 'password'); $this->passField->attr('class', $this->className() . 'Pass'); $this->passField->collapsed = Inputfield::collapsedNever; - $this->passField->attr('placeholder', $this->labels('password')); - $this->passField->skipLabel = Inputfield::skipLabelHeader; + $this->passField->skipLabel = $this->skipLabel; + if($this->skipLabel) $this->passField->attr('placeholder', $this->labels('password')); $this->submitField = $modules->get('InputfieldSubmit'); $this->submitField->attr('name', 'login_submit'); From 725d89e664157c81873e5a0c08f35e1c5f5d81ba Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 28 Mar 2025 14:46:17 -0400 Subject: [PATCH 16/35] Fix issue processwire/processwire-issues#2053 --- wire/core/PageArray.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/wire/core/PageArray.php b/wire/core/PageArray.php index 2d6f35f52..a9d0d0d14 100644 --- a/wire/core/PageArray.php +++ b/wire/core/PageArray.php @@ -392,7 +392,7 @@ public function getSelectors($getString = false) { * * This is applicable to and destructive to the WireArray. * - * @param string|Selectors|array $selectors AttributeSelector string to use as the filter. + * @param string|Selectors|array $selectors Selector string to use as the filter. * @param bool|int $not Make this a "not" filter? Use int 1 for "not all". (default is false) * @return PageArray|WireArray reference to current [filtered] PageArray * @@ -407,7 +407,7 @@ protected function filterData($selectors, $not = false) { * * #pw-internal * - * @param string $selector AttributeSelector string to use as the filter. + * @param string $selector Selector string to use as the filter. * @return PageArray|PaginatedArray|WireArray reference to current PageArray instance. * */ @@ -416,11 +416,11 @@ public function filter($selector) { } /** - * Filter out pages that don't match the selector (destructive) + * Filter out pages that DO match the selector (destructive) * * #pw-internal * - * @param string $selector AttributeSelector string to use as the filter. + * @param string $selector Selector string to use * @return PageArray|PaginatedArray|WireArray reference to current PageArray instance. * */ @@ -452,7 +452,7 @@ public function getPage($key) { * * #pw-internal * - * @param string $selector AttributeSelector string. + * @param string $selector Selector string. * @return PageArray|WireArray New PageArray instance * @see WireArray::find() * From 570bdb4b8138e4f839ee30242004ba02e428e96c Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Thu, 17 Apr 2025 11:59:47 -0400 Subject: [PATCH 17/35] Fix issue processwire/processwire-issues#2060 --- wire/modules/Inputfield/InputfieldFile/InputfieldFile.js | 2 ++ wire/modules/Inputfield/InputfieldFile/InputfieldFile.min.js | 2 +- wire/modules/Inputfield/InputfieldFile/InputfieldFile.module | 4 +++- wire/modules/Inputfield/InputfieldImage/InputfieldImage.js | 2 ++ .../modules/Inputfield/InputfieldImage/InputfieldImage.min.js | 2 +- 5 files changed, 9 insertions(+), 3 deletions(-) diff --git a/wire/modules/Inputfield/InputfieldFile/InputfieldFile.js b/wire/modules/Inputfield/InputfieldFile/InputfieldFile.js index 658d0a969..ff61f3884 100755 --- a/wire/modules/Inputfield/InputfieldFile/InputfieldFile.js +++ b/wire/modules/Inputfield/InputfieldFile/InputfieldFile.js @@ -190,6 +190,8 @@ $(document).ready(function() { } postUrl += (postUrl.indexOf('?') > -1 ? '&' : '?') + 'InputfieldFileAjax=1'; + var $f = $('#Inputfield_id'); + if($f.length) postUrl += '&eid=' + $f.val(); // CSRF protection var $postToken = $form.find('input._post_token'); diff --git a/wire/modules/Inputfield/InputfieldFile/InputfieldFile.min.js b/wire/modules/Inputfield/InputfieldFile/InputfieldFile.min.js index 54ff52042..0d4d6ddeb 100644 --- a/wire/modules/Inputfield/InputfieldFile/InputfieldFile.min.js +++ b/wire/modules/Inputfield/InputfieldFile/InputfieldFile.min.js @@ -1 +1 @@ -$(document).ready(function(){$(document).on("change",".InputfieldFileDelete input",function(){setInputfieldFileStatus($(this))}).on("dblclick",".InputfieldFileDelete",function(){var $input=$(this).find("input");var $items=$(this).parents(".InputfieldFileList").find(".InputfieldFileDelete input");if($input.is(":checked")){$items.prop("checked",false).trigger("change")}else{$items.prop("checked",true).trigger("change")}return false});function setInputfieldFileStatus($t){var $info=$t.parents(".InputfieldFileInfo");var collapsed=$t.closest(".InputfieldFile").hasClass("InputfieldItemListCollapse");if($t.is(":checked")){$info.addClass("ui-state-error");if(!collapsed)$info.siblings(".InputfieldFileData").slideUp("fast")}else{$info.removeClass("ui-state-error");if(!collapsed)$info.siblings(".InputfieldFileData").slideDown("fast")}}function initSortable($fileLists){$fileLists.each(function(){var $this=$(this);var qty=$this.children("li").length;if($this.closest(".InputfieldRenderValueMode").length)return;var $inputfield=$this.closest(".Inputfield");if(qty<2){if(qty==0)$inputfield.addClass("InputfieldFileEmpty").removeClass("InputfieldFileMultiple InputfieldFileSingle");else $inputfield.addClass("InputfieldFileSingle").removeClass("InputfieldFileEmpty InputfieldFileMultiple");return}else{$this.closest(".Inputfield").removeClass("InputfieldFileSingle InputfieldFileEmpty").addClass("InputfieldFileMultiple")}$this.sortable({start:function(e,ui){ui.item.children(".InputfieldFileInfo").addClass("ui-state-highlight")},stop:function(e,ui){$(this).children("li").each(function(n){$(this).find(".InputfieldFileSort").val(n)});ui.item.children(".InputfieldFileInfo").removeClass("ui-state-highlight");$inputfield.addClass("InputfieldFileJustSorted InputfieldStateChanged");setTimeout(function(){$inputfield.removeClass("InputfieldFileJustSorted")},500)},update:function(e,ui){$inputfield.trigger("sorted",[ui.item])}})}).find(".ui-widget-header, .ui-state-default").on("mouseenter",function(){$(this).addClass("ui-state-hover")}).on("mouseleave",function(){$(this).removeClass("ui-state-hover")})}function InitOldSchool(){$("body").addClass("ie-no-drop");$(document).on("change",".InputfieldFileUpload input[type=file]",function(){var $t=$(this);var $mask=$t.closest(".InputMask");if($t.val().length>1){$mask.addClass("ui-state-disabled")}else{$mask.removeClass("ui-state-disabled")}if($mask.next(".InputMask").length>0)return;var $inputfield=$t.closest(".InputfieldFile");var $upload=$t.closest(".InputfieldFileUpload");var $list=$inputfield.find(".InputfieldFileList");var maxFiles=parseInt($upload.find(".InputfieldFileMaxFiles").val());var numFiles=$list.children("li").length+$upload.find("input[type=file]").length+1;var maxFilesize=parseInt($upload.attr("data-maxfilesize"));var abort=false;$upload.find("input[type=file]").each(function(){if(typeof this.files[0]!=="undefined"){var size=this.files[0].size;if(size>maxFilesize){ProcessWire.alert("File "+this.files[0].name+" is "+size+" bytes which exceeds max allowed size of "+maxFilesize+" bytes");$(this).val("").closest(".InputMask").removeClass("ui-state-disabled ui-state-active");abort=true}}});if(abort)return false;if(maxFiles>0&&numFiles>=maxFiles){}else{$upload.find(".InputMask").not(":last").each(function(){var $m=$(this);if($m.find("input[type=file]").val()<1)$m.remove()});var $mask2=$mask.clone().removeClass("ui-state-disabled");var $input=$mask2.find("input[type=file]");$input.attr("id",$input.attr("id")+"-");$input.val("");$mask2.insertAfter($mask);$mask2.css("margin-left","0.5em").removeClass("ui-state-active")}var name=$t.val();var pos=name.lastIndexOf("/");if(pos===-1)pos=name.lastIndexOf("\\");name=name.substring(pos+1);$mask.find(".ui-button-text").text(name).prepend("");$mask.removeClass("ui-state-active")})}function InitHTML5($inputfield){if($inputfield.length>0){var $target=$inputfield.find(".InputfieldFileUpload")}else{var $target=$(".InputfieldFileUpload")}$target.closest(".InputfieldContent").each(function(i){if($(this).hasClass("InputfieldFileInit"))return;initHTML5Item($(this),i);$(this).addClass("InputfieldFileInit")});function initHTML5Item($this,i){var $form=$this.parents("form");var $repeaterItem=$this.closest(".InputfieldRepeaterItem");var $uploadData=$this.find(".InputfieldFileUpload");var postUrl=$uploadData.data("posturl");if($repeaterItem.length){postUrl=$repeaterItem.attr("data-editUrl")}else if(!postUrl){postUrl=$form.attr("action")}postUrl+=(postUrl.indexOf("?")>-1?"&":"?")+"InputfieldFileAjax=1";var $postToken=$form.find("input._post_token");var postTokenName=$postToken.attr("name");var postTokenValue=$postToken.val();var fieldName=$uploadData.data("fieldname");if(fieldName.indexOf("[")>-1)fieldName=fieldName.slice(0,-2);var extensions=$uploadData.data("extensions").toLowerCase();var maxFilesize=$uploadData.data("maxfilesize");var filesUpload=$this.find("input[type=file]").get(0);var dropArea=$this.get(0);var $fileList=$this.find(".InputfieldFileList");if($fileList.length<1){$fileList=$("
      ");$this.find(".InputfieldFileListPlaceholder").replaceWith($fileList);$this.parent(".Inputfield").addClass("InputfieldFileEmpty")}var fileList=$fileList.get(0);var maxFiles=parseInt($this.find(".InputfieldFileMaxFiles").val());$fileList.children().addClass("InputfieldFileItemExisting");$this.find(".AjaxUploadDropHere").show();var doneTimer=null;function uploadFile(file){var $progressItem=$('
    • '),$progressBar=$('
      '),$progressBarValue=$('
      '),img,reader,xhr,fileData;$progressBar.append($progressBarValue);$progressItem.append($progressBar);xhr=new XMLHttpRequest;xhr.upload.addEventListener("progress",function(evt){if(evt.lengthComputable){var completion=evt.loaded/evt.total*100;$progressBarValue.width(completion+"%");if(completion>4){$progressBarValue.html(""+parseInt(completion)+"%")}$("body").addClass("pw-uploading")}else{}},false);xhr.addEventListener("load",function(){xhr.getAllResponseHeaders();var response=JSON.parse(xhr.responseText);if(response.error!==undefined)response=[response];for(var n=0;n0)$child.slideUp("fast",function(){$child.remove()})}var $input=$this.find("input[type=file]");if($input.val())$input.replaceWith($input.clone(true));var $markup=$(r.markup);$markup.hide();if(r.overwrite){var basename=$markup.find(".InputfieldFileName").text();var $item=null;$fileList.children(".InputfieldFileItemExisting").each(function(){if($item===null&&$(this).find(".InputfieldFileName").text()==basename){$item=$(this)}});if($item!==null){var $newInfo=$markup.find(".InputfieldFileInfo");var $newLink=$markup.find(".InputfieldFileLink");var $info=$item.find(".InputfieldFileInfo");var $link=$item.find(".InputfieldFileLink");$info.html($newInfo.html()+"");$link.html($newLink.html());$item.addClass("InputfieldFileItemExisting");$item.effect("highlight",500)}else{$fileList.append($markup);$markup.slideDown();$markup.addClass("InputfieldFileItemExisting")}}else{$fileList.append($markup);$markup.slideDown()}}setTimeout(function(){var $inputfields=$markup.find(".Inputfield");if($inputfields.length){InputfieldsInit($markup.find(".Inputfields"));$inputfields.trigger("reloaded",["InputfieldFileUpload"])}},500)}$progressItem.remove();if(doneTimer)clearTimeout(doneTimer);doneTimer=setTimeout(function(){$("body").removeClass("pw-uploading");if(maxFiles!=1&&!$fileList.is(".ui-sortable"))initSortable($fileList);$fileList.trigger("AjaxUploadDone")},500)},false);xhr.open("POST",postUrl,true);xhr.setRequestHeader("X-FILENAME",encodeURIComponent(file.name));xhr.setRequestHeader("X-FIELDNAME",fieldName);xhr.setRequestHeader("Content-Type","application/octet-stream");xhr.setRequestHeader("X-"+postTokenName,postTokenValue);xhr.setRequestHeader("X-REQUESTED-WITH","XMLHttpRequest");xhr.send(file);fileData=""+" "+''+file.name+""+' • '+parseInt(file.size/1024,10)+" kb";$progressItem.find("p.ui-widget-header").html(fileData);$fileList.append($progressItem);var $inputfield=$fileList.closest(".Inputfield");$inputfield.addClass("InputfieldStateChanged");var numFiles=$inputfield.find(".InputfieldFileItem").length;if(numFiles==1){$inputfield.removeClass("InputfieldFileEmpty").removeClass("InputfieldFileMultiple").addClass("InputfieldFileSingle")}else if(numFiles>1){$inputfield.removeClass("InputfieldFileEmpty").removeClass("InputfieldFileSingle").addClass("InputfieldFileMultiple")}}function traverseFiles(files){function errorItem(filename,message){return'
    • '+'

        '+filename+" "+' • '+message+"

    • "}var errorMsg="";if(typeof files!=="undefined"){for(var i=0,l=files.length;imaxFilesize&&maxFilesize>2e6){var maxKB=parseInt(maxFilesize/1024,10);if(typeof ProcessWire.config.InputfieldFile.labels["too-big"]!="undefined"){errorMsg=ProcessWire.config.InputfieldFile.labels["too-big"];errorMsg=errorMsg.replace("MAX_KB",maxKB)}else{var fileSize=parseInt(files[i].size/1024,10);errorMsg="Filesize "+fileSize+" kb is too big. Maximum allowed is "+maxKB+" kb"}$fileList.append(errorItem(files[i].name,errorMsg))}else{uploadFile(files[i])}if(maxFiles==1)break}}else{fileList.innerHTML="No support for the File API in this web browser"}}filesUpload.addEventListener("change",function(evt){traverseFiles(this.files);evt.preventDefault();evt.stopPropagation();this.value=""},false);dropArea.addEventListener("dragleave",function(){$(this).removeClass("ui-state-hover");$(this).closest(".Inputfield").removeClass("pw-drag-in-file")},false);dropArea.addEventListener("dragenter",function(evt){evt.preventDefault();$(this).addClass("ui-state-hover");$(this).closest(".Inputfield").addClass("pw-drag-in-file")},false);dropArea.addEventListener("dragover",function(evt){if(!$(this).is("ui-state-hover")){$(this).addClass("ui-state-hover");$(this).closest(".Inputfield").addClass("pw-drag-in-file")}evt.preventDefault();evt.stopPropagation()},false);dropArea.addEventListener("drop",function(evt){traverseFiles(evt.dataTransfer.files);$(this).removeClass("ui-state-hover").closest(".Inputfield").removeClass("pw-drag-in-file");evt.preventDefault();evt.stopPropagation()},false)}}function initTags($inputfields){$inputfields.each(function(){var $inputfield=$(this);var $inputs=$inputfield.find("input.InputfieldFileTagsInput:not(.selectized)");var $selects=$inputfield.find("input.InputfieldFileTagsSelect:not(.selectized)");if($inputs.length){$inputs.selectize({plugins:["remove_button","drag_drop"],delimiter:" ",persist:false,createOnBlur:true,submitOnReturn:false,create:function(input){return{value:input,text:input}}})}if($selects.length){if(!$inputfield.hasClass("Inputfield"))$inputfield=$inputfield.closest(".Inputfield");var configName=$inputfield.attr("data-configName");var settings=ProcessWire.config[configName];var options=[];if(typeof settings==="undefined"){if(configName.indexOf("_repeater")>-1){configName=configName.replace(/_repeater\d+(_?)/,"$1");settings=ProcessWire.config[configName];if(typeof settings==="undefined")settings=null}}if(settings){for(var n=0;n"+escape(item.value)+""},option:function(item,escape){return"
      "+escape(item.value)+"
      "}}})}})}initSortable($(".InputfieldFileList"));initTags($(".InputfieldFileHasTags"));var allowAjax=false;if(window.File&&window.FileList&&window.FileReader&&($("#PageIDIndicator").length>0||$(".InputfieldAllowAjaxUpload").length>0)){InitHTML5("");allowAjax=true}else{InitOldSchool()}var minContainerWidth=767;var resizeActive=false;var windowResize=function(){if(!allowAjax)return;$(".AjaxUploadDropHere").each(function(){var $t=$(this);if($t.parent().width()<=minContainerWidth){$t.hide()}else{$t.show()}});resizeActive=false};if(allowAjax){$(window).on("resize",function(){if(resizeActive)return;resizeActive=true;setTimeout(windowResize,1e3)}).trigger("resize");$(document).on("AjaxUploadDone",".InputfieldFileHasTags",function(event){initTags($(this))})}$(document).on("reloaded",".InputfieldHasFileList",function(event){initSortable($(this).find(".InputfieldFileList"));InitHTML5($(this));initTags($(this));if(allowAjax)windowResize()})}); \ No newline at end of file +$(document).ready(function(){$(document).on("change",".InputfieldFileDelete input",function(){setInputfieldFileStatus($(this))}).on("dblclick",".InputfieldFileDelete",function(){var $input=$(this).find("input");var $items=$(this).parents(".InputfieldFileList").find(".InputfieldFileDelete input");if($input.is(":checked")){$items.prop("checked",false).trigger("change")}else{$items.prop("checked",true).trigger("change")}return false});function setInputfieldFileStatus($t){var $info=$t.parents(".InputfieldFileInfo");var collapsed=$t.closest(".InputfieldFile").hasClass("InputfieldItemListCollapse");if($t.is(":checked")){$info.addClass("ui-state-error");if(!collapsed)$info.siblings(".InputfieldFileData").slideUp("fast")}else{$info.removeClass("ui-state-error");if(!collapsed)$info.siblings(".InputfieldFileData").slideDown("fast")}}function initSortable($fileLists){$fileLists.each(function(){var $this=$(this);var qty=$this.children("li").length;if($this.closest(".InputfieldRenderValueMode").length)return;var $inputfield=$this.closest(".Inputfield");if(qty<2){if(qty==0)$inputfield.addClass("InputfieldFileEmpty").removeClass("InputfieldFileMultiple InputfieldFileSingle");else $inputfield.addClass("InputfieldFileSingle").removeClass("InputfieldFileEmpty InputfieldFileMultiple");return}else{$this.closest(".Inputfield").removeClass("InputfieldFileSingle InputfieldFileEmpty").addClass("InputfieldFileMultiple")}$this.sortable({start:function(e,ui){ui.item.children(".InputfieldFileInfo").addClass("ui-state-highlight")},stop:function(e,ui){$(this).children("li").each(function(n){$(this).find(".InputfieldFileSort").val(n)});ui.item.children(".InputfieldFileInfo").removeClass("ui-state-highlight");$inputfield.addClass("InputfieldFileJustSorted InputfieldStateChanged");setTimeout(function(){$inputfield.removeClass("InputfieldFileJustSorted")},500)},update:function(e,ui){$inputfield.trigger("sorted",[ui.item])}})}).find(".ui-widget-header, .ui-state-default").on("mouseenter",function(){$(this).addClass("ui-state-hover")}).on("mouseleave",function(){$(this).removeClass("ui-state-hover")})}function InitOldSchool(){$("body").addClass("ie-no-drop");$(document).on("change",".InputfieldFileUpload input[type=file]",function(){var $t=$(this);var $mask=$t.closest(".InputMask");if($t.val().length>1){$mask.addClass("ui-state-disabled")}else{$mask.removeClass("ui-state-disabled")}if($mask.next(".InputMask").length>0)return;var $inputfield=$t.closest(".InputfieldFile");var $upload=$t.closest(".InputfieldFileUpload");var $list=$inputfield.find(".InputfieldFileList");var maxFiles=parseInt($upload.find(".InputfieldFileMaxFiles").val());var numFiles=$list.children("li").length+$upload.find("input[type=file]").length+1;var maxFilesize=parseInt($upload.attr("data-maxfilesize"));var abort=false;$upload.find("input[type=file]").each(function(){if(typeof this.files[0]!=="undefined"){var size=this.files[0].size;if(size>maxFilesize){ProcessWire.alert("File "+this.files[0].name+" is "+size+" bytes which exceeds max allowed size of "+maxFilesize+" bytes");$(this).val("").closest(".InputMask").removeClass("ui-state-disabled ui-state-active");abort=true}}});if(abort)return false;if(maxFiles>0&&numFiles>=maxFiles){}else{$upload.find(".InputMask").not(":last").each(function(){var $m=$(this);if($m.find("input[type=file]").val()<1)$m.remove()});var $mask2=$mask.clone().removeClass("ui-state-disabled");var $input=$mask2.find("input[type=file]");$input.attr("id",$input.attr("id")+"-");$input.val("");$mask2.insertAfter($mask);$mask2.css("margin-left","0.5em").removeClass("ui-state-active")}var name=$t.val();var pos=name.lastIndexOf("/");if(pos===-1)pos=name.lastIndexOf("\\");name=name.substring(pos+1);$mask.find(".ui-button-text").text(name).prepend("");$mask.removeClass("ui-state-active")})}function InitHTML5($inputfield){if($inputfield.length>0){var $target=$inputfield.find(".InputfieldFileUpload")}else{var $target=$(".InputfieldFileUpload")}$target.closest(".InputfieldContent").each(function(i){if($(this).hasClass("InputfieldFileInit"))return;initHTML5Item($(this),i);$(this).addClass("InputfieldFileInit")});function initHTML5Item($this,i){var $form=$this.parents("form");var $repeaterItem=$this.closest(".InputfieldRepeaterItem");var $uploadData=$this.find(".InputfieldFileUpload");var postUrl=$uploadData.data("posturl");if($repeaterItem.length){postUrl=$repeaterItem.attr("data-editUrl")}else if(!postUrl){postUrl=$form.attr("action")}postUrl+=(postUrl.indexOf("?")>-1?"&":"?")+"InputfieldFileAjax=1";var $f=$("#Inputfield_id");if($f.length)postUrl+="&eid="+$f.val();var $postToken=$form.find("input._post_token");var postTokenName=$postToken.attr("name");var postTokenValue=$postToken.val();var fieldName=$uploadData.data("fieldname");if(fieldName.indexOf("[")>-1)fieldName=fieldName.slice(0,-2);var extensions=$uploadData.data("extensions").toLowerCase();var maxFilesize=$uploadData.data("maxfilesize");var filesUpload=$this.find("input[type=file]").get(0);var dropArea=$this.get(0);var $fileList=$this.find(".InputfieldFileList");if($fileList.length<1){$fileList=$("
        ");$this.find(".InputfieldFileListPlaceholder").replaceWith($fileList);$this.parent(".Inputfield").addClass("InputfieldFileEmpty")}var fileList=$fileList.get(0);var maxFiles=parseInt($this.find(".InputfieldFileMaxFiles").val());$fileList.children().addClass("InputfieldFileItemExisting");$this.find(".AjaxUploadDropHere").show();var doneTimer=null;function uploadFile(file){var $progressItem=$('
      • '),$progressBar=$('
        '),$progressBarValue=$('
        '),img,reader,xhr,fileData;$progressBar.append($progressBarValue);$progressItem.append($progressBar);xhr=new XMLHttpRequest;xhr.upload.addEventListener("progress",function(evt){if(evt.lengthComputable){var completion=evt.loaded/evt.total*100;$progressBarValue.width(completion+"%");if(completion>4){$progressBarValue.html(""+parseInt(completion)+"%")}$("body").addClass("pw-uploading")}else{}},false);xhr.addEventListener("load",function(){xhr.getAllResponseHeaders();var response=JSON.parse(xhr.responseText);if(response.error!==undefined)response=[response];for(var n=0;n0)$child.slideUp("fast",function(){$child.remove()})}var $input=$this.find("input[type=file]");if($input.val())$input.replaceWith($input.clone(true));var $markup=$(r.markup);$markup.hide();if(r.overwrite){var basename=$markup.find(".InputfieldFileName").text();var $item=null;$fileList.children(".InputfieldFileItemExisting").each(function(){if($item===null&&$(this).find(".InputfieldFileName").text()==basename){$item=$(this)}});if($item!==null){var $newInfo=$markup.find(".InputfieldFileInfo");var $newLink=$markup.find(".InputfieldFileLink");var $info=$item.find(".InputfieldFileInfo");var $link=$item.find(".InputfieldFileLink");$info.html($newInfo.html()+"");$link.html($newLink.html());$item.addClass("InputfieldFileItemExisting");$item.effect("highlight",500)}else{$fileList.append($markup);$markup.slideDown();$markup.addClass("InputfieldFileItemExisting")}}else{$fileList.append($markup);$markup.slideDown()}}setTimeout(function(){var $inputfields=$markup.find(".Inputfield");if($inputfields.length){InputfieldsInit($markup.find(".Inputfields"));$inputfields.trigger("reloaded",["InputfieldFileUpload"])}},500)}$progressItem.remove();if(doneTimer)clearTimeout(doneTimer);doneTimer=setTimeout(function(){$("body").removeClass("pw-uploading");if(maxFiles!=1&&!$fileList.is(".ui-sortable"))initSortable($fileList);$fileList.trigger("AjaxUploadDone")},500)},false);xhr.open("POST",postUrl,true);xhr.setRequestHeader("X-FILENAME",encodeURIComponent(file.name));xhr.setRequestHeader("X-FIELDNAME",fieldName);xhr.setRequestHeader("Content-Type","application/octet-stream");xhr.setRequestHeader("X-"+postTokenName,postTokenValue);xhr.setRequestHeader("X-REQUESTED-WITH","XMLHttpRequest");xhr.send(file);fileData=""+" "+''+file.name+""+' • '+parseInt(file.size/1024,10)+" kb";$progressItem.find("p.ui-widget-header").html(fileData);$fileList.append($progressItem);var $inputfield=$fileList.closest(".Inputfield");$inputfield.addClass("InputfieldStateChanged");var numFiles=$inputfield.find(".InputfieldFileItem").length;if(numFiles==1){$inputfield.removeClass("InputfieldFileEmpty").removeClass("InputfieldFileMultiple").addClass("InputfieldFileSingle")}else if(numFiles>1){$inputfield.removeClass("InputfieldFileEmpty").removeClass("InputfieldFileSingle").addClass("InputfieldFileMultiple")}}function traverseFiles(files){function errorItem(filename,message){return'
      • '+'

          '+filename+" "+' • '+message+"

      • "}var errorMsg="";if(typeof files!=="undefined"){for(var i=0,l=files.length;imaxFilesize&&maxFilesize>2e6){var maxKB=parseInt(maxFilesize/1024,10);if(typeof ProcessWire.config.InputfieldFile.labels["too-big"]!="undefined"){errorMsg=ProcessWire.config.InputfieldFile.labels["too-big"];errorMsg=errorMsg.replace("MAX_KB",maxKB)}else{var fileSize=parseInt(files[i].size/1024,10);errorMsg="Filesize "+fileSize+" kb is too big. Maximum allowed is "+maxKB+" kb"}$fileList.append(errorItem(files[i].name,errorMsg))}else{uploadFile(files[i])}if(maxFiles==1)break}}else{fileList.innerHTML="No support for the File API in this web browser"}}filesUpload.addEventListener("change",function(evt){traverseFiles(this.files);evt.preventDefault();evt.stopPropagation();this.value=""},false);dropArea.addEventListener("dragleave",function(){$(this).removeClass("ui-state-hover");$(this).closest(".Inputfield").removeClass("pw-drag-in-file")},false);dropArea.addEventListener("dragenter",function(evt){evt.preventDefault();$(this).addClass("ui-state-hover");$(this).closest(".Inputfield").addClass("pw-drag-in-file")},false);dropArea.addEventListener("dragover",function(evt){if(!$(this).is("ui-state-hover")){$(this).addClass("ui-state-hover");$(this).closest(".Inputfield").addClass("pw-drag-in-file")}evt.preventDefault();evt.stopPropagation()},false);dropArea.addEventListener("drop",function(evt){traverseFiles(evt.dataTransfer.files);$(this).removeClass("ui-state-hover").closest(".Inputfield").removeClass("pw-drag-in-file");evt.preventDefault();evt.stopPropagation()},false)}}function initTags($inputfields){$inputfields.each(function(){var $inputfield=$(this);var $inputs=$inputfield.find("input.InputfieldFileTagsInput:not(.selectized)");var $selects=$inputfield.find("input.InputfieldFileTagsSelect:not(.selectized)");if($inputs.length){$inputs.selectize({plugins:["remove_button","drag_drop"],delimiter:" ",persist:false,createOnBlur:true,submitOnReturn:false,create:function(input){return{value:input,text:input}}})}if($selects.length){if(!$inputfield.hasClass("Inputfield"))$inputfield=$inputfield.closest(".Inputfield");var configName=$inputfield.attr("data-configName");var settings=ProcessWire.config[configName];var options=[];if(typeof settings==="undefined"){if(configName.indexOf("_repeater")>-1){configName=configName.replace(/_repeater\d+(_?)/,"$1");settings=ProcessWire.config[configName];if(typeof settings==="undefined")settings=null}}if(settings){for(var n=0;n"+escape(item.value)+""},option:function(item,escape){return"
        "+escape(item.value)+"
        "}}})}})}initSortable($(".InputfieldFileList"));initTags($(".InputfieldFileHasTags"));var allowAjax=false;if(window.File&&window.FileList&&window.FileReader&&($("#PageIDIndicator").length>0||$(".InputfieldAllowAjaxUpload").length>0)){InitHTML5("");allowAjax=true}else{InitOldSchool()}var minContainerWidth=767;var resizeActive=false;var windowResize=function(){if(!allowAjax)return;$(".AjaxUploadDropHere").each(function(){var $t=$(this);if($t.parent().width()<=minContainerWidth){$t.hide()}else{$t.show()}});resizeActive=false};if(allowAjax){$(window).on("resize",function(){if(resizeActive)return;resizeActive=true;setTimeout(windowResize,1e3)}).trigger("resize");$(document).on("AjaxUploadDone",".InputfieldFileHasTags",function(event){initTags($(this))})}$(document).on("reloaded",".InputfieldHasFileList",function(event){initSortable($(this).find(".InputfieldFileList"));InitHTML5($(this));initTags($(this));if(allowAjax)windowResize()})}); \ No newline at end of file diff --git a/wire/modules/Inputfield/InputfieldFile/InputfieldFile.module b/wire/modules/Inputfield/InputfieldFile/InputfieldFile.module index 8ad60691a..54620121a 100644 --- a/wire/modules/Inputfield/InputfieldFile/InputfieldFile.module +++ b/wire/modules/Inputfield/InputfieldFile/InputfieldFile.module @@ -1508,7 +1508,9 @@ class InputfieldFile extends Inputfield implements InputfieldItemList, Inputfiel $hasPage = $this->hasPage; if($hasPage && wireInstanceOf($hasPage, 'RepeaterPage')) { $process = $this->wire()->process; - if($process instanceof WirePageEditor && $process->getPage()->id === $hasPage->id) { + $eid = (int) $this->wire()->input->get('eid'); + if(!$eid) $eid = $process->getPage()->id; + if($process instanceof WirePageEditor && $eid === $hasPage->id) { // repeater page being edited directly or in front-end modal // so no '_repeater' suffix is necessary here } else if(strpos($this->name, '_repeater') === false) { diff --git a/wire/modules/Inputfield/InputfieldImage/InputfieldImage.js b/wire/modules/Inputfield/InputfieldImage/InputfieldImage.js index 83b4b195e..edbe1b256 100755 --- a/wire/modules/Inputfield/InputfieldImage/InputfieldImage.js +++ b/wire/modules/Inputfield/InputfieldImage/InputfieldImage.js @@ -1663,6 +1663,8 @@ function InputfieldImage($) { } postUrl += (postUrl.indexOf('?') > -1 ? '&' : '?') + 'InputfieldFileAjax=1'; + var $f = $('#Inputfield_id'); + if($f.length) postUrl += '&eid=' + $f.val(); if(fieldName.indexOf('[') > -1) fieldName = fieldName.slice(0,-2); // trim trailing [] diff --git a/wire/modules/Inputfield/InputfieldImage/InputfieldImage.min.js b/wire/modules/Inputfield/InputfieldImage/InputfieldImage.min.js index 6b55f2054..2764cf4fd 100644 --- a/wire/modules/Inputfield/InputfieldImage/InputfieldImage.min.js +++ b/wire/modules/Inputfield/InputfieldImage/InputfieldImage.min.js @@ -1 +1 @@ -function InputfieldImage($){var $uploadBeforeItem=null;var uploadReplace={file:"",item:null,edit:null};var magnificOptions={type:"image",closeOnContentClick:true,closeBtnInside:true};var cookieData=null;var retryGridItems=[];var gridSliding=false;function useAjaxUpload(){if(typeof ProcessWire.config.demo!=="undefined")return false;var isFileReaderSupport=window.File&&window.FileList&&window.FileReader;var isAjaxUpload=$(".InputfieldAllowAjaxUpload").length>0;var isPageIDIndicator=$("#PageIDIndicator").length>0;return isFileReaderSupport&&(isPageIDIndicator||isAjaxUpload)}function throttle(fn,threshhold,scope){threshhold||(threshhold=250);var last,deferTimer;return function(){var context=scope||this;var now=+new Date,args=arguments;if(last&&now .gridImage",start:function(e,ui){var size=getCookieData($el.closest(".Inputfield"),"size");ui.placeholder.append($("
        ").css({display:"block",height:size+"px",width:size+"px"}));timer=window.setTimeout(function(){closeEdit($el,null)},100);$el.addClass("InputfieldImageSorting")},stop:function(e,ui){var $this=$(this);if(timer!==null){ui.item.find(".InputfieldImageEdit__edit").trigger("click");clearTimeout(timer)}$this.children("li").each(function(n){var $sort=$(this).find(".InputfieldFileSort");if($sort.val()!=n)$sort.val(n).trigger("change")});$el.removeClass("InputfieldImageSorting");ui.item.find(".Inputfield").trigger("sort-stop")},update:function(e,ui){$el.trigger("sorted",[ui.item])},cancel:".InputfieldImageEdit,.focusArea,input,textarea,button,select,option"};$el.sortable(sortableOptions)}function setupMagnificForRenderValue($el){var options=$.extend(true,{},magnificOptions);options.callbacks={elementParse:function(item){var src=$(item.el).attr("data-original");if(typeof src=="undefined"||!src)src=$(item.el).attr("src");item.src=src}};options.gallery={enabled:true};$el.find("img").magnificPopup(options)}function setupMagnificForSingle($el){var options=$.extend(true,{},magnificOptions);options.callbacks={elementParse:function(item){item.src=$(item.el).attr("src")}};options.gallery={enabled:false};$el.find("img").magnificPopup(options)}function findEditedElement($parent){return $parent.find(".InputfieldImageEdit--active")}function findEditMarkup($edit){return $("#"+$edit.find(".InputfieldImageEdit__edit").attr("data-current"))}function setDeleteStateOnAllItems($input){var checked=$input.is(":checked");var $items=$input.parents(".gridImages").find(".gridImage__deletebox");if(checked){$items.prop("checked","checked").trigger("change")}else{$items.prop("checked",false).trigger("change")}}function updateGrid($inputfield){var $gridImages;if(typeof $inputfield=="undefined"){$gridImages=$(".gridImages")}else{$gridImages=$inputfield.find(".gridImages")}$gridImages.each(function(){var $grid=$(this),$edit=findEditedElement($grid);if($edit.length){moveEdit(findEditMarkup($edit),$edit)}})}function checkInputfieldWidth($inputfield){var narrowItems=[];var mediumItems=[];var wideItems=[];var n=0,ni=0,mi=0,wi=0;var $inputfields;var $item;if(typeof $inputfield=="undefined"){$inputfields=$(".InputfieldImage.Inputfield")}else{$inputfields=$inputfield}$inputfields.removeClass("InputfieldImageNarrow InputfieldImageMedium InputfieldImageWide");$inputfields.each(function(){$item=$(this);var width=$item.width();if(width<1)return;if(width<=500){narrowItems[ni]=$item;ni++}else if(width<=900){mediumItems[mi]=$item;mi++}else{wideItems[wi]=$item;wi++}});for(n=0;n100?100:top,left:left>100?100:left,zoom:zoom>100?0:zoom};return focusData}function getFocusStr(focusObj){if(typeof focusObj=="undefined")focusObj=getFocus();return focusObj.top+" "+focusObj.left+" "+focusObj.zoom}function getFocusProperty(property){var focus=getFocus();return focus[property]}function setFocus(focusObj){focusData=focusObj;var focusStr=focusObj.top+" "+focusObj.left+" "+focusObj.zoom;$thumb.attr("data-focus",focusStr);$input=$edit.find(".InputfieldImageFocus");if(focusStr!=$input.val()){$input.val(focusStr).trigger("change")}}function setFocusProperty(property,value){var focus=getFocus();focus[property]=value;setFocus(focus)}function setFocusDragPosition(){var focus=getFocus();var $overlay=$focusCircle.parent();var w=$overlay.width();var h=$overlay.height();var x=Math.round(focus.left/100*w);var y=Math.round(focus.top/100*h);if(x<0)x=0;if(y<0)y=0;if(x>w)x=w;if(y>h)y=h;$focusCircle.css({top:y+"px",left:x+"px"})}$focusArea=$img.siblings(".focusArea");if(!$focusArea.length){$focusArea=$("
        ").addClass("focusArea");$img.after($focusArea)}$focusArea.css({height:$img.height()+"px",width:$img.width()+"px","background-color":"rgba(0,0,0,0.7)"}).addClass("focusActive");$focusCircle=$focusArea.find(".focusCircle");if(!$focusCircle.length){$focusCircle=$("
        ").addClass("focusCircle");$focusArea.append($focusCircle)}$img.parent().addClass("focusWrap");setFocusDragPosition();var zoomSlide=function(zoomPercent){var zoomBoxSize,focus,faWidth,faHeight;if(typeof zoomPercent=="undefined")zoomPercent=lastZoomPercent;lastZoomPercent=zoomPercent;faWidth=$focusArea.width();faHeight=$focusArea.height();if(faWidth>faHeight){$zoomBox.height(100-zoomPercent+"%");zoomBoxSize=$zoomBox.height();$zoomBox.width(zoomBoxSize)}else{$zoomBox.width(100-zoomPercent+"%");zoomBoxSize=$zoomBox.width();$zoomBox.height(zoomBoxSize)}focus=getFocus();var crop=getFocusZoomCropDimensions(focus.left,focus.top,zoomPercent,faWidth,faHeight,zoomBoxSize);$zoomBox.css({top:crop.top+"px",left:crop.left+"px","background-position":"-"+crop.left+"px -"+crop.top+"px","background-size":faWidth+"px "+faHeight+"px"});focus.zoom=zoomPercent;setFocusProperty("zoom",focus.zoom);if(mode=="grid")setGridSizeItem($thumb.parent(),gridSize,false,focus)};var dragEvent=function(event,ui){var $this=$(this);var circleSize=$this.outerHeight();var w=$this.parent().width();var h=$this.parent().height();var top=ui.position.top>0?ui.position.top:0;var left=ui.position.left>0?ui.position.left:0;top=top>0?top/h*100:0;left=left>0?left/w*100:0;var newFocus={top:top,left:left,zoom:getFocusProperty("zoom")};setFocus(newFocus);if(useZoomFocus){zoomSlide(newFocus.zoom)}else if(mode=="grid"){setGridSizeItem($thumb.parent(),gridSize,false,newFocus)}};$focusCircle.draggable({containment:"parent",drag:dragEvent,stop:dragEvent});if(useZoomFocus){var zoom=getFocusProperty("zoom");$zoomSlider=$("
        ").addClass("focusZoomSlider").css({"margin-top":"5px"});$zoomBox=$("
        ").addClass("focusZoomBox").css({position:"absolute",background:"transparent","background-image":"url("+$img.attr("src")+")"});$focusArea.prepend($zoomBox);$img.after($zoomSlider);$thumb.attr("src",$img.attr("src"));$zoomSlider.slider({min:0,max:50,value:zoom,range:"max",slide:function(event,ui){zoomSlide(ui.value)}});zoomSlide(zoom)}else{$focusArea.css("background-color","rgba(0,0,0,0.5)")}}function stopFocus($edit){$focusCircle=$edit.find(".focusCircle");if($focusCircle.length){var $focusWrap=$focusCircle.closest(".focusWrap");$focusWrap.find(".focusZoomSlider").slider("destroy").remove();$focusWrap.find(".focusZoomBox").remove();$focusWrap.removeClass("focusWrap");$focusCircle.draggable("destroy");$focusCircle.parent().removeClass("focusActive");$focusCircle.remove();var $button=$edit.find(".InputfieldImageButtonFocus");if($button.length){$icon=$button.find("i");$icon.removeClass("focusIconActive").toggleClass($icon.attr("data-toggle"))}}}function getFocusZoomPosition(focusPercent,sourceDimension,cropDimension){var focusPX=parseInt(sourceDimension*focusPercent/100);var position=parseInt(focusPX-cropDimension/2);var maxPosition=parseInt(sourceDimension-cropDimension);if(0>position)position=0;if(maxPosition=percentH?faWidth:faHeight;var cropDimension=maxDimension-maxDimension*zoomPercent/100;var posLeft=getFocusZoomPosition(focusLeft,faWidth,cropDimension);var posTop=getFocusZoomPosition(focusTop,faHeight,cropDimension);return{left:posLeft,top:posTop,width:cropDimension,height:cropDimension}}function getFocusZoomPosition4GridviewSquare(focusPercent,sourceDimPX,gridViewPX,zoomPercent,scale,smallestSidePX){sourceDimPX=sourceDimPX*scale;var gridViewPercent=gridViewPX/sourceDimPX*100;var adjustPercent=gridViewPercent/2;var posPercent=focusPercent-adjustPercent;var posMinVal=0;var posMaxVal=100-gridViewPercent;if(posPercent<=posMinVal)posPercent=0;if(posPercent>=posMaxVal)posPercent=posMaxVal;var posPX=sourceDimPX/100*posPercent/scale;posPX=-1*parseInt(posPX);return posPX}function getFocusZoomCropDimensions4GridviewSquare(focusLeft,focusTop,zoomPercent,w,h,gridViewSize,scale){var smallestSidePX=w>=h?h:w;var posLeft=getFocusZoomPosition4GridviewSquare(focusLeft,w,gridViewSize,zoomPercent,scale,smallestSidePX);var posTop=getFocusZoomPosition4GridviewSquare(focusTop,h,gridViewSize,zoomPercent,scale,smallestSidePX);var transformLeft=parseInt(posLeft);var transformTop=parseInt(posTop);return{transformLeft:transformLeft,transformTop:transformTop,scale:scale}}function tearDownEdit($edit){stopFocus($edit);$edit.off("click",".InputfieldImageButtonFocus");$inputArea=$edit.find(".InputfieldImageEdit__edit");if($inputArea.children().not(".InputfieldFileSort").length){var $items=$inputArea.children();$("#"+$inputArea.attr("data-current")).find(".ImageData").append($items)}}function closeEdit($parent,$not){var $edit;if($parent){$edit=$parent.find(".InputfieldImageEdit--active")}else if($not){$edit=$(".InputfieldImageEdit--active").not($not.find(".InputfieldImageEdit--active"))}else{$edit=$(".InputfieldImageEdit--active")}if($edit.length){tearDownEdit($edit);$edit.removeClass("InputfieldImageEdit--active").removeAttr("id");$("#"+$edit.attr("data-for")).removeClass("gridImageEditing")}$(".InputfieldImageEdit__replace").removeClass("InputfieldImageEdit__replace")}function moveEdit($el,$edit){if(!$el||!$el.length)return;var $children=$el.parent().children().not(".InputfieldImageEdit");var lastTop=0;var found=false;var $insertBeforeItem=null;$children.each(function(){if($insertBeforeItem)return;var $item=$(this);var top=$item.offset().top;if(found&&top!=lastTop){$insertBeforeItem=$item}else if($item.attr("id")==$el.attr("id")){found=true}lastTop=top});if($insertBeforeItem){$edit.insertBefore($insertBeforeItem)}else{$edit.insertAfter($children.eq($children.length-1))}var $arrow=$edit.find(".InputfieldImageEdit__arrow");if($arrow.length)$arrow.css("left",$el.position().left+$el.outerWidth()/2+"px")}function initGridEvents(){$(window).on("resize",throttle(windowResize,200));$(document).on("click dblclick",".gridImage__trash",function(e){var $input=$(this).find("input");$input.prop("checked",inverseState).trigger("change");if(e.type=="dblclick"){setDeleteStateOnAllItems($input);e.preventDefault();e.stopPropagation()}});$(document).on("change",".gridImage__deletebox",function(){updateDeleteClass($(this))});$(document).on("click",".gridImage__edit",function(e){var $el=$(this).closest(".gridImage");if(!$el.length)return;if($el.closest(".InputfieldImageEditAll").length)return false;var $all=$el.closest(".gridImages");var $edit=$all.find(".InputfieldImageEdit");if($el.hasClass("gridImageEditing")){$edit.find(".InputfieldImageEdit__close").trigger("click")}else{moveEdit($el,$edit);tearDownEdit($edit);setupEdit($el,$edit);$edit.addClass("InputfieldImageEdit--active").attr("data-for",$el.attr("id"));$all.find(".gridImageEditing").removeClass("gridImageEditing");$el.addClass("gridImageEditing")}}).on("click",".InputfieldImageEditAll img",function(e){e.stopPropagation();e.preventDefault();$.magnificPopup.close();var options=$.extend(true,{},magnificOptions);var $img=$(this);options["items"]={src:$img.attr("data-original"),title:$img.attr("alt")};$.magnificPopup.open(options);return true}).on("click",".InputfieldImageButtonFocus",function(){var $button=$(this);var $icon=$button.find("i");var $edit=$button.closest(".InputfieldImageEdit, .gridImage");var $focusCircle=$edit.find(".focusCircle");if($focusCircle.length){stopFocus($edit)}else{startFocus($edit);$icon.addClass("focusIconActive");$icon.toggleClass($icon.attr("data-toggle"))}});$(document).on("click",function(e){var $el=$(e.target);if(typeof clickLanguageTabActive!="undefined"&&clickLanguageTabActive){return}if($el.closest(".InputfieldImageEdit").length){closeEdit(null,$el.parents(".gridImages"))}else if($el.is("input, textarea")&&$el.closest(".InputfieldImageEditAll").length){$el.trigger("focus").one("blur",function(){$el.closest(".gridImages").sortable("enable")});$el.closest(".gridImages").sortable("disable")}else if($el.closest(".gridImage__inner").length){closeEdit(null,$el.parents(".gridImages"))}else if($el.closest(".mfp-container").length){return}else if($el.closest(".ui-dialog").length){return}else if($el.is(".mfp-close")){return}else if($el.is("a.remove")){return}else{closeEdit(null,null)}});$(document).on("click",".InputfieldImageEdit__close",function(e){closeEdit($(this).parents(".gridImages"),null)});$(document).on("change",".InputfieldImage",function(){$(this).find(".InputfieldImageButtonCrop:not(.pw-modal-dblclick)").addClass("pw-modal-dblclick ui-state-disabled")}).on("click",".InputfieldImageButtonCrop.ui-state-disabled",function(e){var $button=$(this);var $list=$button.closest(".gridImages");if(!$list.hasClass("gridImagesAlerted")){ProcessWire.alert(ProcessWire.config.InputfieldImage.labels.changes);$list.addClass("gridImagesAlerted")}setTimeout(function(){$button.removeClass("ui-state-active")},500);return false});$(".ImagesGrid").on("click","button.pw-modal",function(e){e.preventDefault()});setupEditableFilename();checkInputfieldWidth()}function setupEditableFilename(){$(document).on("click",".InputfieldImageEdit__name",function(e){var $span=$(this).children("span");var $input=$span.closest(".gridImage, .InputfieldImageEdit").find(".InputfieldFileRename");var $list=$span.closest(".gridImages");var sortable=$list.hasClass("ui-sortable");if(sortable)$list.sortable("disable");$input.val($span.text());$span.on("keypress",function(e){if(e.which==13){$span.trigger("blur");return false}return true});$span.attr("autocomplete","off").attr("autocorrect","off").attr("autocapitalize","off").attr("spellcheck","false");$span.trigger("focus").on("blur",function(){var val=$(this).text();if(val.trim().length<1){$span.text($input.val())}else if(val!=$input.val()){$input.val(val).trigger("change");$list.closest(".Inputfield").trigger("change")}$span.off("keypress");if(sortable)$list.sortable("enable")})})}function setListSize($inputfield,pct){pct=Math.floor(pct);$inputfield.find(".gridImage__overflow").each(function(){var dataPct=100-pct;var $this=$(this);$this.css("width",pct+"%");$this.siblings(".ImageData").css("width",dataPct+"%");$this.find("img").css({top:0,left:0,transform:"none"})});setCookieData($inputfield,"listSize",pct)}function setGridSize($inputfield,gridSize,ragged){if(!gridSize)return;var size=gridSize+"px";var $gridImages=$inputfield.find(".gridImages");if(typeof ragged=="undefined"||ragged==null)ragged=$gridImages.attr("data-ragged")?true:false;if(ragged){$gridImages.attr("data-ragged",1)}else{$gridImages.removeAttr("data-ragged")}$gridImages.find(".gridImage__overflow").each(function(){setGridSizeItem($(this),gridSize,ragged)});$gridImages.find(".gridImage__edit, .gridImage__resize").css("line-height",size);$gridImages.attr("data-size",gridSize);setCookieData($inputfield,"size",gridSize);if(retryGridItems.length)setTimeout(function(){while(retryGridItems.length){var item=retryGridItems.pop();setGridSizeItem(item.item,item.gridSize,ragged)}},150)}function setGridSizeItem($item,gridSize,ragged,focus){var $img;if($item.hasClass("gridImage__overflow")){$img=$item.children("img")}else if($item.is("img")){$img=$item;$item=$img.closest(".gridImage__overflow")}else{return}if(!gridSize){$img.removeAttr("width").removeAttr("height");$item.width("auto").height("auto");return}var zoom=0;var w=$img.width();var h=$img.height();var dataW=parseInt($img.attr("data-w"));var dataH=parseInt($img.attr("data-h"));if(!w)w=dataW;if(!h)h=dataH;if(!ragged&&typeof focus=="undefined"){var focusStr=$img.attr("data-focus");if(typeof focusStr=="undefined")focusStr="50.0 50.0 0";var focusArray=focusStr.split(" ");focus={top:parseFloat(focusArray[0]),left:parseFloat(focusArray[1]),zoom:parseInt(focusArray[2])}}if(!ragged)zoom=focus.zoom;if(ragged){$img.attr("height",gridSize).removeAttr("width");$img.css({"max-height":"100%","max-width":"none",top:"50%",left:"50%",transform:"translate3d(-50%, -50%, 0)"})}else if(zoom>0&&$item.closest(".InputfieldImageFocusZoom").length&&!gridSliding){var maxHeight,maxWidth;if(w>=h){maxHeight="100%";maxWidth="none";if(w==dataW){h=gridSize;w=h/dataH*dataW}}else{maxHeight="none";maxWidth="100%";if(h==dataH){w=gridSize;h=w/dataW*dataH}}var scale=1+zoom/100*2;var crop=getFocusZoomCropDimensions4GridviewSquare(focus.left,focus.top,zoom,w,h,gridSize,scale);$img.css({left:"0px",top:"0px","transform-origin":"0px 0px",transform:"scale("+crop.scale+") translate3d("+crop.transformLeft+"px, "+crop.transformTop+"px, 0)","max-width":maxWidth,"max-height":maxHeight})}else if(w>=h){$img.attr("height",gridSize).removeAttr("width");if(focus.left<1)focus.left=.001;$img.css({"max-height":"100%","max-width":"none",top:"50%",left:focus.left+"%",transform:"translate3d(-"+focus.left+"%, -50%, 0)"})}else if(h>w){$img.attr("width",gridSize).removeAttr("height");if(focus.top<1)focus.top=.001;$img.css({"max-height":"none","max-width":"100%",top:focus.top+"%",left:"50%",transform:"translate3d(-50%, -"+focus.top+"%, 0)"})}else{$img.css({"max-height":"100%","max-width":"none",top:"50%",left:"50%",transform:"translate3d(-50%, -50%, 0)"});$img.removeAttr("width").attr("height",gridSize)}w=$img.width();if(w){$item.css({width:ragged?w+"px":gridSize+"px",height:gridSize+"px"})}else{var tries=$item.attr("data-tries");if(!tries)tries=0;if(typeof tries=="undefined")tries=0;tries=parseInt(tries);if(tries>3){$item.css({width:gridSize+"px",height:gridSize+"px"})}else{retryGridItems.push({item:$item,gridSize:gridSize});$item.attr("data-tries",tries+1)}}}function setupImageListToggle($target){if($target.find(".InputfieldImageListToggle").length)return;var $list=$("").append("");var $left=$("").append("");var $grid=$("").append("");var activeClass="InputfieldImageListToggle--active";var defaultMode="";var toggleClick=function(e){var $a=$(this);var $inputfield=$a.closest(".Inputfield");var href=$a.attr("href");var size;var $aPrev=$a.parent().children("."+activeClass);var hrefPrev=$aPrev.attr("href");$aPrev.removeClass(activeClass);$a.addClass(activeClass);stopFocus($inputfield);if(href=="list"){if(!$inputfield.hasClass("InputfieldImageEditAll")){$inputfield.find(".InputfieldImageEdit--active .InputfieldImageEdit__close").trigger("click");$inputfield.addClass("InputfieldImageEditAll")}size=getCookieData($inputfield,"listSize");setListSize($inputfield,size);setCookieData($inputfield,"mode","list")}else if(href=="left"){$inputfield.removeClass("InputfieldImageEditAll");size=getCookieData($inputfield,"size");setGridSize($inputfield,size,true);setCookieData($inputfield,"mode","left");updateGrid()}else if(href=="grid"){$inputfield.removeClass("InputfieldImageEditAll");size=getCookieData($inputfield,"size");setGridSize($inputfield,size,false);setCookieData($inputfield,"mode","grid");if(hrefPrev=="left")setTimeout(function(){setGridSize($inputfield,size,false)},100)}setupSortable($inputfield.find(".gridImages"));$a.trigger("blur");return false};$list.on("click",toggleClick);$left.on("click",toggleClick);$grid.on("click",toggleClick);if($target.hasClass("InputfieldImage")){$target.children(".InputfieldHeader").append($list).append($left).append($grid);defaultMode=getCookieData($target,"mode")}else{$(".InputfieldImage > .InputfieldHeader",$target).append($list).append($left).append($grid)}if(defaultMode=="list"){$list.trigger("click")}else if(defaultMode=="left"){$left.trigger("click")}else{}}function setupSizeSlider($inputfield){var $header=$inputfield.children(".InputfieldHeader");if($header.children(".InputfieldImageSizeSlider").length)return;var $gridImages=$inputfield.find(".gridImages");var gridSize=$gridImages.attr("data-gridsize");var min=gridSize/2;var max=gridSize*2;var $slider=$('');$header.append($slider);var sizeSlide=function(event,ui){var value=ui.value;var minPct=15;var divisor=Math.floor(gridSize/minPct);var v=value-min;var listSize=Math.floor(minPct+v/divisor);if($inputfield.hasClass("InputfieldImageEditAll")){setCookieData($inputfield,"size",value);setListSize($inputfield,listSize)}else{setCookieData($inputfield,"listSize",listSize);setGridSize($inputfield,value)}};$slider.slider({min:min,max:max,value:getCookieData($inputfield,"size"),range:"min",slide:sizeSlide,start:function(event,ui){gridSliding=true;if($inputfield.find(".InputfieldImageEdit:visible").length){$inputfield.find(".InputfieldImageEdit__close").trigger("click")}},stop:function(event,ui){gridSliding=false;sizeSlide(event,ui);updateGrid($inputfield)}})}function setCookieData($inputfield,property,value){var data=getCookieData($inputfield);var id=$inputfield.attr("id");var name=id?id.replace("wrap_Inputfield_",""):"";if(!name.length||typeof value=="undefined")return;if(data[name][property]==value)return;data[name][property]=value;$.cookie("InputfieldImage",data,{secure:window.location.protocol.indexOf("https:")===0});cookieData=data}function getCookieData($inputfield,property){if(cookieData&&typeof property=="undefined")return cookieData;var id=$inputfield.attr("id");var name=id?id.replace("wrap_Inputfield_",""):"na";var data=cookieData?cookieData:$.cookie("InputfieldImage");var value=null;if(!data)data={};if(typeof data[name]=="undefined")data[name]={};if(typeof data[name].size=="undefined"||!data[name].size){data[name].size=parseInt($inputfield.find(".gridImages").attr("data-size"));if(!data[name].size)data[name].size=130}if(typeof data[name].listSize=="undefined"||!data[name].listSize){data[name].listSize=23}if(typeof data[name].mode=="undefined"||!data[name].mode){data[name].mode=$inputfield.find(".gridImages").attr("data-gridMode");if(!data[name].mode)data[name].mode="list"}if(cookieData==null)cookieData=data;if(typeof property=="undefined"){value=data}else if(property===true){value=data[name]}else if(typeof data[name][property]!="undefined"){value=data[name][property]}return value}function initInputfield($inputfield){if($inputfield.hasClass("InputfieldStateCollapsed"))return;var maxFiles=parseInt($inputfield.find(".InputfieldImageMaxFiles").val());var $gridImages=$inputfield.find(".gridImages");var size=getCookieData($inputfield,"size");var mode=getCookieData($inputfield,"mode");var ragged=mode=="left"?true:false;var renderValueMode=$inputfield.hasClass("InputfieldRenderValueMode");if(!size)size=$gridImages.attr("data-gridsize");size=parseInt(size);if(!renderValueMode&&($inputfield.hasClass("InputfieldImageEditAll")||mode=="list")){var listSize=getCookieData($inputfield,"listSize");setListSize($inputfield,listSize)}else{setGridSize($inputfield,size,ragged)}if(!$inputfield.hasClass("InputfieldImageInit")){$inputfield.addClass("InputfieldImageInit");if(renderValueMode){return setupMagnificForRenderValue($inputfield)}else if(maxFiles==1){$inputfield.addClass("InputfieldImageMax1");setupMagnificForSingle($inputfield)}else{setupSortable($gridImages)}setupImageListToggle($inputfield);setupSizeSlider($inputfield)}checkInputfieldWidth($inputfield);$inputfield.on("change",".InputfieldFileActionSelect",function(){var $note=$(this).next(".InputfieldFileActionNote");if($(this).val().length){$note.fadeIn()}else{$note.hide()}})}function initUploadOldSchool(){$("body").addClass("ie-no-drop");$(".InputfieldImage.InputfieldFileMultiple").each(function(){var $field=$(this),maxFiles=parseInt($field.find(".InputfieldFileMaxFiles").val()),$list=$field.find(".gridImages"),$uploadArea=$field.find(".InputfieldImageUpload");$uploadArea.on("change","input[type=file]",function(){var $t=$(this),$mask=$t.parent(".InputMask");if($t.val().length>1)$mask.addClass("ui-state-disabled");else $mask.removeClass("ui-state-disabled");if($t.next("input.InputfieldFile").length>0)return;var numFiles=$list.children("li").length+$uploadArea.find("input[type=file]").length+1;if(maxFiles>0&&numFiles>=maxFiles)return;$uploadArea.find(".InputMask").not(":last").each(function(){var $m=$(this);if($m.find("input[type=file]").val()<1)$m.remove()});var $i=$mask.clone().removeClass("ui-state-disabled");$i.children("input[type=file]").val("");$i.insertAfter($mask)})})}function initUploadHTML5($inputfield){var $target;if($inputfield.length>0){$target=$inputfield.find(".InputfieldImageUpload")}else{$target=$(".InputfieldImageUpload")}$target.each(function(i){var $this=$(this);var $content=$this.closest(".InputfieldContent");if($this.hasClass("InputfieldImageInitUpload"))return;initHTML5Item($content,i);$this.addClass("InputfieldImageInitUpload")});function initHTML5Item($this,i){var $form=$this.parents("form");var $repeaterItem=$this.closest(".InputfieldRepeaterItem");var $uploadAttrs=$this.find(".InputfieldImageUpload");var postUrl=$uploadAttrs.data("posturl");var $postToken=$form.find("input._post_token");var postTokenName=$postToken.attr("name");var postTokenValue=$postToken.val();var $errorParent=$this.find(".InputfieldImageErrors").first();var fieldName=$uploadAttrs.data("fieldname");var $inputfield=$this.closest(".Inputfield.InputfieldImage");var extensions=$uploadAttrs.data("extensions").toLowerCase();var maxFilesize=$uploadAttrs.data("maxfilesize");var filesUpload=$this.find("input[type=file]").get(0);var $fileList=$this.find(".gridImages");var fileList=$fileList.get(0);var gridSize=$fileList.data("gridsize");var doneTimer=null;var maxFiles=parseInt($this.find(".InputfieldImageMaxFiles").val());var resizeSettings=getClientResizeSettings($inputfield);var useClientResize=resizeSettings.maxWidth>0||resizeSettings.maxHeight>0||resizeSettings.maxSize>0;if($repeaterItem.length){postUrl=$repeaterItem.attr("data-editUrl")}else if(!postUrl){postUrl=$form.attr("action")}postUrl+=(postUrl.indexOf("?")>-1?"&":"?")+"InputfieldFileAjax=1";if(fieldName.indexOf("[")>-1)fieldName=fieldName.slice(0,-2);setupDropzone($this);if(maxFiles!=1)setupDropInPlace($fileList);$fileList.children().addClass("InputfieldFileItemExisting");$inputfield.on("pwimageupload",function(event,data){traverseFiles([data.file],data.xhr)});function errorItem(message,filename){if(typeof filename!=="undefined")message=""+filename+": "+message;var icon=" ";return"
      • "+icon+message+"
      • "}function basename(str){var base=new String(str).substring(str.lastIndexOf("/")+1);if(base.lastIndexOf(".")!=-1)base=base.substring(0,base.lastIndexOf("."));return base}function setupDropzone($el){if($el.hasClass("InputfieldImageDropzoneInit"))return;var el=$el.get(0);var $inputfield=$el.closest(".Inputfield");function dragStart(){if($inputfield.hasClass("pw-drag-in-file"))return;$el.addClass("ui-state-hover");$inputfield.addClass("pw-drag-in-file")}function dragStop(){if(!$inputfield.hasClass("pw-drag-in-file"))return;$el.removeClass("ui-state-hover");$inputfield.removeClass("pw-drag-in-file")}el.addEventListener("dragleave",function(){dragStop()},false);el.addEventListener("dragenter",function(evt){evt.preventDefault();dragStart()},false);el.addEventListener("dragover",function(evt){if(!$el.is("ui-state-hover"))dragStart();evt.preventDefault();evt.stopPropagation();return false},false);el.addEventListener("drop",function(evt){traverseFiles(evt.dataTransfer.files);dragStop();evt.preventDefault();evt.stopPropagation();return false},false);$el.addClass("InputfieldImageDropzoneInit")}function setupDropInPlace($gridImages){var $i=null;var haltDrag=false;var timer=null;var $inputfield=$gridImages.closest(".Inputfield");function addInputfieldClass(){$inputfield.addClass("pw-drag-in-file")}function removeInputfieldClass(){$inputfield.removeClass("pw-drag-in-file")}function getCenterCoordinates($el){var offset=$el.offset();var width=$el.width();var height=$el.height();var centerX=offset.left+width/2;var centerY=offset.top+height/2;return{clientX:centerX,clientY:centerY}}function noDropInPlace(){return $gridImages.find(".InputfieldImageEdit--active").length>0}function dragEnter(evt){if(noDropInPlace())return;evt.preventDefault();evt.stopPropagation();addInputfieldClass();haltDrag=false;if($i==null){var gridSize=$gridImages.attr("data-size")+"px";var $o=$("
        ").addClass("gridImage__overflow");if($gridImages.closest(".InputfieldImageEditAll").length){$o.css({width:"100%",height:gridSize})}else{$o.css({width:gridSize,height:gridSize})}$i=$("
      • ").addClass("ImageOuter gridImage gridImagePlaceholder").append($o);$gridImages.append($i)}var coords=getCenterCoordinates($i);$i.simulate("mousedown",coords)}function dragOver(evt){if(noDropInPlace())return;evt.preventDefault();evt.stopPropagation();addInputfieldClass();haltDrag=false;if($i==null)return;var coords={clientX:evt.originalEvent.clientX,clientY:evt.originalEvent.clientY};$i.simulate("mousemove",coords)}function dragEnd(evt){if(noDropInPlace())return;evt.preventDefault();evt.stopPropagation();if($i==null)return false;haltDrag=true;if(timer)clearTimeout(timer);timer=setTimeout(function(){if(!haltDrag||$i==null)return;$i.remove();$i=null;removeInputfieldClass()},1e3)}function drop(evt){if(noDropInPlace())return;removeInputfieldClass();haltDrag=false;var coords={clientX:evt.clientX,clientY:evt.clientY};$i.simulate("mouseup",coords);$uploadBeforeItem=$i.next(".gridImage");$i.remove();$i=null}if($gridImages.length&&!$gridImages.hasClass("gridImagesInitDropInPlace")){$gridImages.on("dragenter",dragEnter);$gridImages.on("dragover",dragOver);$gridImages.on("dragleave",dragEnd);$gridImages.on("drop",drop);$gridImages.addClass("gridImagesInitDropInPlace")}}function uploadFile(file,extension,xhrsub){var labels=ProcessWire.config.InputfieldImage.labels;var filesizeStr=parseInt(file.size/1024,10)+" kB";var tooltipMarkup=""+'
        '+""+""+'"+""+""+""+""+""+""+"
        "+labels.dimensions+"'+labels.na+"
        "+labels.filesize+""+filesizeStr+"
        "+labels.variations+"0
        "+"
        ";var $progressItem=$('
      • '),$tooltip=$(tooltipMarkup),$imgWrapper=$('
        '),$imageData=$('
        '),$hover=$("
        "),$progressBar=$(""),$edit=$(' '),$spinner=$('
        '),reader,xhr,fileData,fileUrl=URL.createObjectURL(file),$fileList=$inputfield.find(".gridImages"),singleMode=maxFiles==1,size=getCookieData($inputfield,"size"),listSize=getCookieData($inputfield,"listSize"),listMode=$inputfield.hasClass("InputfieldImageEditAll"),$img=$('');$imgWrapper.append($img);$hover.find(".gridImage__inner").append($edit);$hover.find(".gridImage__inner").append($spinner.css("display","none"));$hover.find(".gridImage__inner").append($progressBar);$imageData.append($(""+'

        '+file.name+"

        "+''+filesizeStr+""));if(listMode){$imgWrapper.css("width",listSize+"%");$imageData.css("width",100-listSize+"%")}else{$imgWrapper.css({width:size+"px",height:size+"px"})}$progressItem.append($tooltip).append($imgWrapper).append($hover).append($imageData);$img.attr({src:fileUrl,"data-original":fileUrl});img=new Image;img.addEventListener("load",function(){$tooltip.find(".dimensions").html(this.width+" × "+this.height);var factor=Math.min(this.width,this.height)/size;$img.attr({width:this.width/factor,height:this.height/factor})},false);img.src=fileUrl;if(typeof xhrsub!="undefined"){xhr=xhrsub}else{xhr=new XMLHttpRequest}function updateProgress(evt){if(typeof evt!="undefined"){if(!evt.lengthComputable)return;$progressBar.val(parseInt(evt.loaded/evt.total*100))}$("body").addClass("pw-uploading");$spinner.css("display","block")}xhr.upload.addEventListener("progress",updateProgress,false);xhr.addEventListener("load",function(){xhr.getAllResponseHeaders();var response=JSON.parse(xhr.responseText);if(typeof response.ajaxResponse!="undefined")response=response.ajaxResponse;var wasZipFile=response.length>1;if(response.error!==undefined)response=[response];for(var n=0;n-1){uploadReplaceName=uploadReplaceName.substring(0,uploadReplaceName.indexOf("?"))}var uploadReplaceExt=uploadReplaceName.substring(uploadReplaceName.lastIndexOf(".")+1).toLowerCase();uploadReplaceName=uploadReplaceName.substring(0,uploadReplaceName.lastIndexOf("."));if(uploadReplaceExt==uploadNewExt){$imageEditName.children("span").text(uploadReplaceName).removeAttr("contenteditable")}$markup.find(".gridImage__edit").trigger("click")}uploadReplace.file="";uploadReplace.item=null;uploadReplace.edit=null}if(doneTimer)clearTimeout(doneTimer);$uploadBeforeItem=null;doneTimer=setTimeout(function(){if(maxFiles!=1){setupSortable($fileList)}else{setupMagnificForSingle($inputfield)}$("body").removeClass("pw-uploading");$fileList.trigger("AjaxUploadDone")},500);$inputfield.trigger("change").removeClass("InputfieldFileEmpty")},false);if(uploadReplace.edit){uploadReplace.edit.find(".InputfieldImageEdit__close").trigger("click")}else if($inputfield.find(".InputfieldImageEdit:visible").length){$inputfield.find(".InputfieldImageEdit__close").trigger("click")}if(uploadReplace.item){uploadReplace.item.replaceWith($progressItem);uploadReplace.item=$progressItem}else if($uploadBeforeItem&&$uploadBeforeItem.length){$uploadBeforeItem.before($progressItem)}else{$fileList.append($progressItem)}function sendUpload(file,imageData){if(typeof xhrsub=="undefined"){xhr.open("POST",postUrl,true)}xhr.setRequestHeader("X-FILENAME",encodeURIComponent(file.name));xhr.setRequestHeader("X-FIELDNAME",fieldName);if(uploadReplace.item)xhr.setRequestHeader("X-REPLACENAME",uploadReplace.file);xhr.setRequestHeader("Content-Type","application/octet-stream");xhr.setRequestHeader("X-"+postTokenName,postTokenValue);xhr.setRequestHeader("X-REQUESTED-WITH","XMLHttpRequest");if(typeof imageData!="undefined"&&imageData!=false){xhr.send(imageData)}else{xhr.send(file)}updateGrid();$inputfield.trigger("change");var numFiles=$inputfield.find(".InputfieldFileItem").length;if(numFiles==1){$inputfield.removeClass("InputfieldFileEmpty").removeClass("InputfieldFileMultiple").addClass("InputfieldFileSingle")}else if(numFiles>1){$inputfield.removeClass("InputfieldFileEmpty").removeClass("InputfieldFileSingle").addClass("InputfieldFileMultiple")}}updateProgress();if(typeof file.name==="undefined")file.name=getUploadFilename(file);var ext=file.name.substring(file.name.lastIndexOf(".")+1).toLowerCase();if(useClientResize&&(ext=="jpg"||ext=="jpeg"||ext=="png"||ext=="gif")){var resizer=new PWImageResizer(resizeSettings);$spinner.addClass("pw-resizing");resizer.resize(file,function(imageData){$spinner.removeClass("pw-resizing");sendUpload(file,imageData)})}else{sendUpload(file)}}function traverseFiles(files,xhr){var toKilobyte=function(i){return parseInt(i/1024,10)};if(typeof files==="undefined"){fileList.innerHTML="No support for the File API in this web browser";return}for(var i=0,l=files.length;imaxFilesize&&maxFilesize>2e6){var filesizeKB=toKilobyte(files[i].size),maxFilesizeKB=toKilobyte(maxFilesize);if(typeof ProcessWire.config.InputfieldFile.labels["too-big"]!="undefined"){message=ProcessWire.config.InputfieldFile.labels["too-big"];message=message.replace("MAX_KB",maxFilesizeKB)}else{message="Filesize "+filesizeKB+" kb is too big. Maximum allowed is "+maxFilesizeKB+" kb"}$errorParent.append(errorItem(message,files[i].name))}else if(typeof xhr!="undefined"){uploadFile(files[i],extension,xhr)}else{uploadFile(files[i],extension)}if(maxFiles==1)break}}function getUploadFilename(file){if(typeof file.name!=="undefined")return file.name;var ext="";switch(file.type){case"image/jpeg":ext=".jpg";break;case"image/png":ext=".png";break;case"image/gif":ext=".gif";break;case"image/svg+xml":ext=".svg";break;case"image/webp":ext=".webp"}return $inputfield.attr("id").replace("wrap_Inputfield_","")+ext}filesUpload.addEventListener("change",function(evt){traverseFiles(this.files);evt.preventDefault();evt.stopPropagation();this.value=""},false)}function setupEnlargementDropzones(){var sel=".InputfieldImageEdit__imagewrapper img";$(document).on("dragenter",sel,function(){var $this=$(this);if($this.closest(".InputfieldImageMax1").length)return;var src=$this.attr("src");var $edit=$this.closest(".InputfieldImageEdit");var $parent=$this.closest(".InputfieldImageEdit__imagewrapper");$parent.addClass("InputfieldImageEdit__replace");uploadReplace.file=new String(src).substring(src.lastIndexOf("/")+1);uploadReplace.item=$("#"+$edit.attr("data-for"));uploadReplace.edit=$edit}).on("dragleave",sel,function(){var $this=$(this);if($this.closest(".InputfieldImageMax1").length)return;var $parent=$this.closest(".InputfieldImageEdit__imagewrapper");$parent.removeClass("InputfieldImageEdit__replace");uploadReplace.file="";uploadReplace.item=null;uploadReplace.edit=null})}setupEnlargementDropzones()}function getClientResizeSettings($inputfield){var settings={maxWidth:0,maxHeight:0,maxSize:0,quality:1,autoRotate:true,debug:ProcessWire.config.debug};var data=$inputfield.attr("data-resize");if(typeof data!="undefined"&&data.length){data=data.split(";");settings.maxWidth=data[0].length?parseInt(data[0]):0;settings.maxHeight=data[1].length?parseInt(data[1]):0;settings.maxSize=data[2].length?parseFloat(data[2]):0;settings.quality=parseFloat(data[3])}return settings}function init(){$(".InputfieldImage.Inputfield").each(function(){initInputfield($(this))});initGridEvents();if(useAjaxUpload()){initUploadHTML5("")}else{initUploadOldSchool()}$(document).on("reloaded",".InputfieldImage",function(){var $inputfield=$(this);$inputfield.removeClass("InputfieldImageInit");initInputfield($inputfield);initUploadHTML5($inputfield);Inputfields.init($inputfield);$(".InputfieldImageListToggle--active",$inputfield).trigger("click")}).on("wiretabclick",function(e,$newTab,$oldTab){$newTab.find(".InputfieldImage").each(function(){initInputfield($(this))})}).on("opened",function(){var $t=$(this);if($t.hasClass("InputfieldImage")){initInputfield($t)}else{$t.find(".InputfieldImage").each(function(){initInputfield($(this))})}})}init()}jQuery(document).ready(function($){InputfieldImage($)}); \ No newline at end of file +function InputfieldImage($){var $uploadBeforeItem=null;var uploadReplace={file:"",item:null,edit:null};var magnificOptions={type:"image",closeOnContentClick:true,closeBtnInside:true};var cookieData=null;var retryGridItems=[];var gridSliding=false;function useAjaxUpload(){if(typeof ProcessWire.config.demo!=="undefined")return false;var isFileReaderSupport=window.File&&window.FileList&&window.FileReader;var isAjaxUpload=$(".InputfieldAllowAjaxUpload").length>0;var isPageIDIndicator=$("#PageIDIndicator").length>0;return isFileReaderSupport&&(isPageIDIndicator||isAjaxUpload)}function throttle(fn,threshhold,scope){threshhold||(threshhold=250);var last,deferTimer;return function(){var context=scope||this;var now=+new Date,args=arguments;if(last&&now .gridImage",start:function(e,ui){var size=getCookieData($el.closest(".Inputfield"),"size");ui.placeholder.append($("
        ").css({display:"block",height:size+"px",width:size+"px"}));timer=window.setTimeout(function(){closeEdit($el,null)},100);$el.addClass("InputfieldImageSorting")},stop:function(e,ui){var $this=$(this);if(timer!==null){ui.item.find(".InputfieldImageEdit__edit").trigger("click");clearTimeout(timer)}$this.children("li").each(function(n){var $sort=$(this).find(".InputfieldFileSort");if($sort.val()!=n)$sort.val(n).trigger("change")});$el.removeClass("InputfieldImageSorting");ui.item.find(".Inputfield").trigger("sort-stop")},update:function(e,ui){$el.trigger("sorted",[ui.item])},cancel:".InputfieldImageEdit,.focusArea,input,textarea,button,select,option"};$el.sortable(sortableOptions)}function setupMagnificForRenderValue($el){var options=$.extend(true,{},magnificOptions);options.callbacks={elementParse:function(item){var src=$(item.el).attr("data-original");if(typeof src=="undefined"||!src)src=$(item.el).attr("src");item.src=src}};options.gallery={enabled:true};$el.find("img").magnificPopup(options)}function setupMagnificForSingle($el){var options=$.extend(true,{},magnificOptions);options.callbacks={elementParse:function(item){item.src=$(item.el).attr("src")}};options.gallery={enabled:false};$el.find("img").magnificPopup(options)}function findEditedElement($parent){return $parent.find(".InputfieldImageEdit--active")}function findEditMarkup($edit){return $("#"+$edit.find(".InputfieldImageEdit__edit").attr("data-current"))}function setDeleteStateOnAllItems($input){var checked=$input.is(":checked");var $items=$input.parents(".gridImages").find(".gridImage__deletebox");if(checked){$items.prop("checked","checked").trigger("change")}else{$items.prop("checked",false).trigger("change")}}function updateGrid($inputfield){var $gridImages;if(typeof $inputfield=="undefined"){$gridImages=$(".gridImages")}else{$gridImages=$inputfield.find(".gridImages")}$gridImages.each(function(){var $grid=$(this),$edit=findEditedElement($grid);if($edit.length){moveEdit(findEditMarkup($edit),$edit)}})}function checkInputfieldWidth($inputfield){var narrowItems=[];var mediumItems=[];var wideItems=[];var n=0,ni=0,mi=0,wi=0;var $inputfields;var $item;if(typeof $inputfield=="undefined"){$inputfields=$(".InputfieldImage.Inputfield")}else{$inputfields=$inputfield}$inputfields.removeClass("InputfieldImageNarrow InputfieldImageMedium InputfieldImageWide");$inputfields.each(function(){$item=$(this);var width=$item.width();if(width<1)return;if(width<=500){narrowItems[ni]=$item;ni++}else if(width<=900){mediumItems[mi]=$item;mi++}else{wideItems[wi]=$item;wi++}});for(n=0;n100?100:top,left:left>100?100:left,zoom:zoom>100?0:zoom};return focusData}function getFocusStr(focusObj){if(typeof focusObj=="undefined")focusObj=getFocus();return focusObj.top+" "+focusObj.left+" "+focusObj.zoom}function getFocusProperty(property){var focus=getFocus();return focus[property]}function setFocus(focusObj){focusData=focusObj;var focusStr=focusObj.top+" "+focusObj.left+" "+focusObj.zoom;$thumb.attr("data-focus",focusStr);$input=$edit.find(".InputfieldImageFocus");if(focusStr!=$input.val()){$input.val(focusStr).trigger("change")}}function setFocusProperty(property,value){var focus=getFocus();focus[property]=value;setFocus(focus)}function setFocusDragPosition(){var focus=getFocus();var $overlay=$focusCircle.parent();var w=$overlay.width();var h=$overlay.height();var x=Math.round(focus.left/100*w);var y=Math.round(focus.top/100*h);if(x<0)x=0;if(y<0)y=0;if(x>w)x=w;if(y>h)y=h;$focusCircle.css({top:y+"px",left:x+"px"})}$focusArea=$img.siblings(".focusArea");if(!$focusArea.length){$focusArea=$("
        ").addClass("focusArea");$img.after($focusArea)}$focusArea.css({height:$img.height()+"px",width:$img.width()+"px","background-color":"rgba(0,0,0,0.7)"}).addClass("focusActive");$focusCircle=$focusArea.find(".focusCircle");if(!$focusCircle.length){$focusCircle=$("
        ").addClass("focusCircle");$focusArea.append($focusCircle)}$img.parent().addClass("focusWrap");setFocusDragPosition();var zoomSlide=function(zoomPercent){var zoomBoxSize,focus,faWidth,faHeight;if(typeof zoomPercent=="undefined")zoomPercent=lastZoomPercent;lastZoomPercent=zoomPercent;faWidth=$focusArea.width();faHeight=$focusArea.height();if(faWidth>faHeight){$zoomBox.height(100-zoomPercent+"%");zoomBoxSize=$zoomBox.height();$zoomBox.width(zoomBoxSize)}else{$zoomBox.width(100-zoomPercent+"%");zoomBoxSize=$zoomBox.width();$zoomBox.height(zoomBoxSize)}focus=getFocus();var crop=getFocusZoomCropDimensions(focus.left,focus.top,zoomPercent,faWidth,faHeight,zoomBoxSize);$zoomBox.css({top:crop.top+"px",left:crop.left+"px","background-position":"-"+crop.left+"px -"+crop.top+"px","background-size":faWidth+"px "+faHeight+"px"});focus.zoom=zoomPercent;setFocusProperty("zoom",focus.zoom);if(mode=="grid")setGridSizeItem($thumb.parent(),gridSize,false,focus)};var dragEvent=function(event,ui){var $this=$(this);var circleSize=$this.outerHeight();var w=$this.parent().width();var h=$this.parent().height();var top=ui.position.top>0?ui.position.top:0;var left=ui.position.left>0?ui.position.left:0;top=top>0?top/h*100:0;left=left>0?left/w*100:0;var newFocus={top:top,left:left,zoom:getFocusProperty("zoom")};setFocus(newFocus);if(useZoomFocus){zoomSlide(newFocus.zoom)}else if(mode=="grid"){setGridSizeItem($thumb.parent(),gridSize,false,newFocus)}};$focusCircle.draggable({containment:"parent",drag:dragEvent,stop:dragEvent});if(useZoomFocus){var zoom=getFocusProperty("zoom");$zoomSlider=$("
        ").addClass("focusZoomSlider").css({"margin-top":"5px"});$zoomBox=$("
        ").addClass("focusZoomBox").css({position:"absolute",background:"transparent","background-image":"url("+$img.attr("src")+")"});$focusArea.prepend($zoomBox);$img.after($zoomSlider);$thumb.attr("src",$img.attr("src"));$zoomSlider.slider({min:0,max:50,value:zoom,range:"max",slide:function(event,ui){zoomSlide(ui.value)}});zoomSlide(zoom)}else{$focusArea.css("background-color","rgba(0,0,0,0.5)")}}function stopFocus($edit){$focusCircle=$edit.find(".focusCircle");if($focusCircle.length){var $focusWrap=$focusCircle.closest(".focusWrap");$focusWrap.find(".focusZoomSlider").slider("destroy").remove();$focusWrap.find(".focusZoomBox").remove();$focusWrap.removeClass("focusWrap");$focusCircle.draggable("destroy");$focusCircle.parent().removeClass("focusActive");$focusCircle.remove();var $button=$edit.find(".InputfieldImageButtonFocus");if($button.length){$icon=$button.find("i");$icon.removeClass("focusIconActive").toggleClass($icon.attr("data-toggle"))}}}function getFocusZoomPosition(focusPercent,sourceDimension,cropDimension){var focusPX=parseInt(sourceDimension*focusPercent/100);var position=parseInt(focusPX-cropDimension/2);var maxPosition=parseInt(sourceDimension-cropDimension);if(0>position)position=0;if(maxPosition=percentH?faWidth:faHeight;var cropDimension=maxDimension-maxDimension*zoomPercent/100;var posLeft=getFocusZoomPosition(focusLeft,faWidth,cropDimension);var posTop=getFocusZoomPosition(focusTop,faHeight,cropDimension);return{left:posLeft,top:posTop,width:cropDimension,height:cropDimension}}function getFocusZoomPosition4GridviewSquare(focusPercent,sourceDimPX,gridViewPX,zoomPercent,scale,smallestSidePX){sourceDimPX=sourceDimPX*scale;var gridViewPercent=gridViewPX/sourceDimPX*100;var adjustPercent=gridViewPercent/2;var posPercent=focusPercent-adjustPercent;var posMinVal=0;var posMaxVal=100-gridViewPercent;if(posPercent<=posMinVal)posPercent=0;if(posPercent>=posMaxVal)posPercent=posMaxVal;var posPX=sourceDimPX/100*posPercent/scale;posPX=-1*parseInt(posPX);return posPX}function getFocusZoomCropDimensions4GridviewSquare(focusLeft,focusTop,zoomPercent,w,h,gridViewSize,scale){var smallestSidePX=w>=h?h:w;var posLeft=getFocusZoomPosition4GridviewSquare(focusLeft,w,gridViewSize,zoomPercent,scale,smallestSidePX);var posTop=getFocusZoomPosition4GridviewSquare(focusTop,h,gridViewSize,zoomPercent,scale,smallestSidePX);var transformLeft=parseInt(posLeft);var transformTop=parseInt(posTop);return{transformLeft:transformLeft,transformTop:transformTop,scale:scale}}function tearDownEdit($edit){stopFocus($edit);$edit.off("click",".InputfieldImageButtonFocus");$inputArea=$edit.find(".InputfieldImageEdit__edit");if($inputArea.children().not(".InputfieldFileSort").length){var $items=$inputArea.children();$("#"+$inputArea.attr("data-current")).find(".ImageData").append($items)}}function closeEdit($parent,$not){var $edit;if($parent){$edit=$parent.find(".InputfieldImageEdit--active")}else if($not){$edit=$(".InputfieldImageEdit--active").not($not.find(".InputfieldImageEdit--active"))}else{$edit=$(".InputfieldImageEdit--active")}if($edit.length){tearDownEdit($edit);$edit.removeClass("InputfieldImageEdit--active").removeAttr("id");$("#"+$edit.attr("data-for")).removeClass("gridImageEditing")}$(".InputfieldImageEdit__replace").removeClass("InputfieldImageEdit__replace")}function moveEdit($el,$edit){if(!$el||!$el.length)return;var $children=$el.parent().children().not(".InputfieldImageEdit");var lastTop=0;var found=false;var $insertBeforeItem=null;$children.each(function(){if($insertBeforeItem)return;var $item=$(this);var top=$item.offset().top;if(found&&top!=lastTop){$insertBeforeItem=$item}else if($item.attr("id")==$el.attr("id")){found=true}lastTop=top});if($insertBeforeItem){$edit.insertBefore($insertBeforeItem)}else{$edit.insertAfter($children.eq($children.length-1))}var $arrow=$edit.find(".InputfieldImageEdit__arrow");if($arrow.length)$arrow.css("left",$el.position().left+$el.outerWidth()/2+"px")}function initGridEvents(){$(window).on("resize",throttle(windowResize,200));$(document).on("click dblclick",".gridImage__trash",function(e){var $input=$(this).find("input");$input.prop("checked",inverseState).trigger("change");if(e.type=="dblclick"){setDeleteStateOnAllItems($input);e.preventDefault();e.stopPropagation()}});$(document).on("change",".gridImage__deletebox",function(){updateDeleteClass($(this))});$(document).on("click",".gridImage__edit",function(e){var $el=$(this).closest(".gridImage");if(!$el.length)return;if($el.closest(".InputfieldImageEditAll").length)return false;var $all=$el.closest(".gridImages");var $edit=$all.find(".InputfieldImageEdit");if($el.hasClass("gridImageEditing")){$edit.find(".InputfieldImageEdit__close").trigger("click")}else{moveEdit($el,$edit);tearDownEdit($edit);setupEdit($el,$edit);$edit.addClass("InputfieldImageEdit--active").attr("data-for",$el.attr("id"));$all.find(".gridImageEditing").removeClass("gridImageEditing");$el.addClass("gridImageEditing")}}).on("click",".InputfieldImageEditAll img",function(e){e.stopPropagation();e.preventDefault();$.magnificPopup.close();var options=$.extend(true,{},magnificOptions);var $img=$(this);options["items"]={src:$img.attr("data-original"),title:$img.attr("alt")};$.magnificPopup.open(options);return true}).on("click",".InputfieldImageButtonFocus",function(){var $button=$(this);var $icon=$button.find("i");var $edit=$button.closest(".InputfieldImageEdit, .gridImage");var $focusCircle=$edit.find(".focusCircle");if($focusCircle.length){stopFocus($edit)}else{startFocus($edit);$icon.addClass("focusIconActive");$icon.toggleClass($icon.attr("data-toggle"))}});$(document).on("click",function(e){var $el=$(e.target);if(typeof clickLanguageTabActive!="undefined"&&clickLanguageTabActive){return}if($el.closest(".InputfieldImageEdit").length){closeEdit(null,$el.parents(".gridImages"))}else if($el.is("input, textarea")&&$el.closest(".InputfieldImageEditAll").length){$el.trigger("focus").one("blur",function(){$el.closest(".gridImages").sortable("enable")});$el.closest(".gridImages").sortable("disable")}else if($el.closest(".gridImage__inner").length){closeEdit(null,$el.parents(".gridImages"))}else if($el.closest(".mfp-container").length){return}else if($el.closest(".ui-dialog").length){return}else if($el.is(".mfp-close")){return}else if($el.is("a.remove")){return}else{closeEdit(null,null)}});$(document).on("click",".InputfieldImageEdit__close",function(e){closeEdit($(this).parents(".gridImages"),null)});$(document).on("change",".InputfieldImage",function(){$(this).find(".InputfieldImageButtonCrop:not(.pw-modal-dblclick)").addClass("pw-modal-dblclick ui-state-disabled")}).on("click",".InputfieldImageButtonCrop.ui-state-disabled",function(e){var $button=$(this);var $list=$button.closest(".gridImages");if(!$list.hasClass("gridImagesAlerted")){ProcessWire.alert(ProcessWire.config.InputfieldImage.labels.changes);$list.addClass("gridImagesAlerted")}setTimeout(function(){$button.removeClass("ui-state-active")},500);return false});$(".ImagesGrid").on("click","button.pw-modal",function(e){e.preventDefault()});setupEditableFilename();checkInputfieldWidth()}function setupEditableFilename(){$(document).on("click",".InputfieldImageEdit__name",function(e){var $span=$(this).children("span");var $input=$span.closest(".gridImage, .InputfieldImageEdit").find(".InputfieldFileRename");var $list=$span.closest(".gridImages");var sortable=$list.hasClass("ui-sortable");if(sortable)$list.sortable("disable");$input.val($span.text());$span.on("keypress",function(e){if(e.which==13){$span.trigger("blur");return false}return true});$span.attr("autocomplete","off").attr("autocorrect","off").attr("autocapitalize","off").attr("spellcheck","false");$span.trigger("focus").on("blur",function(){var val=$(this).text();if(val.trim().length<1){$span.text($input.val())}else if(val!=$input.val()){$input.val(val).trigger("change");$list.closest(".Inputfield").trigger("change")}$span.off("keypress");if(sortable)$list.sortable("enable")})})}function setListSize($inputfield,pct){pct=Math.floor(pct);$inputfield.find(".gridImage__overflow").each(function(){var dataPct=100-pct;var $this=$(this);$this.css("width",pct+"%");$this.siblings(".ImageData").css("width",dataPct+"%");$this.find("img").css({top:0,left:0,transform:"none"})});setCookieData($inputfield,"listSize",pct)}function setGridSize($inputfield,gridSize,ragged){if(!gridSize)return;var size=gridSize+"px";var $gridImages=$inputfield.find(".gridImages");if(typeof ragged=="undefined"||ragged==null)ragged=$gridImages.attr("data-ragged")?true:false;if(ragged){$gridImages.attr("data-ragged",1)}else{$gridImages.removeAttr("data-ragged")}$gridImages.find(".gridImage__overflow").each(function(){setGridSizeItem($(this),gridSize,ragged)});$gridImages.find(".gridImage__edit, .gridImage__resize").css("line-height",size);$gridImages.attr("data-size",gridSize);setCookieData($inputfield,"size",gridSize);if(retryGridItems.length)setTimeout(function(){while(retryGridItems.length){var item=retryGridItems.pop();setGridSizeItem(item.item,item.gridSize,ragged)}},150)}function setGridSizeItem($item,gridSize,ragged,focus){var $img;if($item.hasClass("gridImage__overflow")){$img=$item.children("img")}else if($item.is("img")){$img=$item;$item=$img.closest(".gridImage__overflow")}else{return}if(!gridSize){$img.removeAttr("width").removeAttr("height");$item.width("auto").height("auto");return}var zoom=0;var w=$img.width();var h=$img.height();var dataW=parseInt($img.attr("data-w"));var dataH=parseInt($img.attr("data-h"));if(!w)w=dataW;if(!h)h=dataH;if(!ragged&&typeof focus=="undefined"){var focusStr=$img.attr("data-focus");if(typeof focusStr=="undefined")focusStr="50.0 50.0 0";var focusArray=focusStr.split(" ");focus={top:parseFloat(focusArray[0]),left:parseFloat(focusArray[1]),zoom:parseInt(focusArray[2])}}if(!ragged)zoom=focus.zoom;if(ragged){$img.attr("height",gridSize).removeAttr("width");$img.css({"max-height":"100%","max-width":"none",top:"50%",left:"50%",transform:"translate3d(-50%, -50%, 0)"})}else if(zoom>0&&$item.closest(".InputfieldImageFocusZoom").length&&!gridSliding){var maxHeight,maxWidth;if(w>=h){maxHeight="100%";maxWidth="none";if(w==dataW){h=gridSize;w=h/dataH*dataW}}else{maxHeight="none";maxWidth="100%";if(h==dataH){w=gridSize;h=w/dataW*dataH}}var scale=1+zoom/100*2;var crop=getFocusZoomCropDimensions4GridviewSquare(focus.left,focus.top,zoom,w,h,gridSize,scale);$img.css({left:"0px",top:"0px","transform-origin":"0px 0px",transform:"scale("+crop.scale+") translate3d("+crop.transformLeft+"px, "+crop.transformTop+"px, 0)","max-width":maxWidth,"max-height":maxHeight})}else if(w>=h){$img.attr("height",gridSize).removeAttr("width");if(focus.left<1)focus.left=.001;$img.css({"max-height":"100%","max-width":"none",top:"50%",left:focus.left+"%",transform:"translate3d(-"+focus.left+"%, -50%, 0)"})}else if(h>w){$img.attr("width",gridSize).removeAttr("height");if(focus.top<1)focus.top=.001;$img.css({"max-height":"none","max-width":"100%",top:focus.top+"%",left:"50%",transform:"translate3d(-50%, -"+focus.top+"%, 0)"})}else{$img.css({"max-height":"100%","max-width":"none",top:"50%",left:"50%",transform:"translate3d(-50%, -50%, 0)"});$img.removeAttr("width").attr("height",gridSize)}w=$img.width();if(w){$item.css({width:ragged?w+"px":gridSize+"px",height:gridSize+"px"})}else{var tries=$item.attr("data-tries");if(!tries)tries=0;if(typeof tries=="undefined")tries=0;tries=parseInt(tries);if(tries>3){$item.css({width:gridSize+"px",height:gridSize+"px"})}else{retryGridItems.push({item:$item,gridSize:gridSize});$item.attr("data-tries",tries+1)}}}function setupImageListToggle($target){if($target.find(".InputfieldImageListToggle").length)return;var $list=$("").append("");var $left=$("").append("");var $grid=$("").append("");var activeClass="InputfieldImageListToggle--active";var defaultMode="";var toggleClick=function(e){var $a=$(this);var $inputfield=$a.closest(".Inputfield");var href=$a.attr("href");var size;var $aPrev=$a.parent().children("."+activeClass);var hrefPrev=$aPrev.attr("href");$aPrev.removeClass(activeClass);$a.addClass(activeClass);stopFocus($inputfield);if(href=="list"){if(!$inputfield.hasClass("InputfieldImageEditAll")){$inputfield.find(".InputfieldImageEdit--active .InputfieldImageEdit__close").trigger("click");$inputfield.addClass("InputfieldImageEditAll")}size=getCookieData($inputfield,"listSize");setListSize($inputfield,size);setCookieData($inputfield,"mode","list")}else if(href=="left"){$inputfield.removeClass("InputfieldImageEditAll");size=getCookieData($inputfield,"size");setGridSize($inputfield,size,true);setCookieData($inputfield,"mode","left");updateGrid()}else if(href=="grid"){$inputfield.removeClass("InputfieldImageEditAll");size=getCookieData($inputfield,"size");setGridSize($inputfield,size,false);setCookieData($inputfield,"mode","grid");if(hrefPrev=="left")setTimeout(function(){setGridSize($inputfield,size,false)},100)}setupSortable($inputfield.find(".gridImages"));$a.trigger("blur");return false};$list.on("click",toggleClick);$left.on("click",toggleClick);$grid.on("click",toggleClick);if($target.hasClass("InputfieldImage")){$target.children(".InputfieldHeader").append($list).append($left).append($grid);defaultMode=getCookieData($target,"mode")}else{$(".InputfieldImage > .InputfieldHeader",$target).append($list).append($left).append($grid)}if(defaultMode=="list"){$list.trigger("click")}else if(defaultMode=="left"){$left.trigger("click")}else{}}function setupSizeSlider($inputfield){var $header=$inputfield.children(".InputfieldHeader");if($header.children(".InputfieldImageSizeSlider").length)return;var $gridImages=$inputfield.find(".gridImages");var gridSize=$gridImages.attr("data-gridsize");var min=gridSize/2;var max=gridSize*2;var $slider=$('');$header.append($slider);var sizeSlide=function(event,ui){var value=ui.value;var minPct=15;var divisor=Math.floor(gridSize/minPct);var v=value-min;var listSize=Math.floor(minPct+v/divisor);if($inputfield.hasClass("InputfieldImageEditAll")){setCookieData($inputfield,"size",value);setListSize($inputfield,listSize)}else{setCookieData($inputfield,"listSize",listSize);setGridSize($inputfield,value)}};$slider.slider({min:min,max:max,value:getCookieData($inputfield,"size"),range:"min",slide:sizeSlide,start:function(event,ui){gridSliding=true;if($inputfield.find(".InputfieldImageEdit:visible").length){$inputfield.find(".InputfieldImageEdit__close").trigger("click")}},stop:function(event,ui){gridSliding=false;sizeSlide(event,ui);updateGrid($inputfield)}})}function setCookieData($inputfield,property,value){var data=getCookieData($inputfield);var id=$inputfield.attr("id");var name=id?id.replace("wrap_Inputfield_",""):"";if(!name.length||typeof value=="undefined")return;if(data[name][property]==value)return;data[name][property]=value;$.cookie("InputfieldImage",data,{secure:window.location.protocol.indexOf("https:")===0});cookieData=data}function getCookieData($inputfield,property){if(cookieData&&typeof property=="undefined")return cookieData;var id=$inputfield.attr("id");var name=id?id.replace("wrap_Inputfield_",""):"na";var data=cookieData?cookieData:$.cookie("InputfieldImage");var value=null;if(!data)data={};if(typeof data[name]=="undefined")data[name]={};if(typeof data[name].size=="undefined"||!data[name].size){data[name].size=parseInt($inputfield.find(".gridImages").attr("data-size"));if(!data[name].size)data[name].size=130}if(typeof data[name].listSize=="undefined"||!data[name].listSize){data[name].listSize=23}if(typeof data[name].mode=="undefined"||!data[name].mode){data[name].mode=$inputfield.find(".gridImages").attr("data-gridMode");if(!data[name].mode)data[name].mode="list"}if(cookieData==null)cookieData=data;if(typeof property=="undefined"){value=data}else if(property===true){value=data[name]}else if(typeof data[name][property]!="undefined"){value=data[name][property]}return value}function initInputfield($inputfield){if($inputfield.hasClass("InputfieldStateCollapsed"))return;var maxFiles=parseInt($inputfield.find(".InputfieldImageMaxFiles").val());var $gridImages=$inputfield.find(".gridImages");var size=getCookieData($inputfield,"size");var mode=getCookieData($inputfield,"mode");var ragged=mode=="left"?true:false;var renderValueMode=$inputfield.hasClass("InputfieldRenderValueMode");if(!size)size=$gridImages.attr("data-gridsize");size=parseInt(size);if(!renderValueMode&&($inputfield.hasClass("InputfieldImageEditAll")||mode=="list")){var listSize=getCookieData($inputfield,"listSize");setListSize($inputfield,listSize)}else{setGridSize($inputfield,size,ragged)}if(!$inputfield.hasClass("InputfieldImageInit")){$inputfield.addClass("InputfieldImageInit");if(renderValueMode){return setupMagnificForRenderValue($inputfield)}else if(maxFiles==1){$inputfield.addClass("InputfieldImageMax1");setupMagnificForSingle($inputfield)}else{setupSortable($gridImages)}setupImageListToggle($inputfield);setupSizeSlider($inputfield)}checkInputfieldWidth($inputfield);$inputfield.on("change",".InputfieldFileActionSelect",function(){var $note=$(this).next(".InputfieldFileActionNote");if($(this).val().length){$note.fadeIn()}else{$note.hide()}})}function initUploadOldSchool(){$("body").addClass("ie-no-drop");$(".InputfieldImage.InputfieldFileMultiple").each(function(){var $field=$(this),maxFiles=parseInt($field.find(".InputfieldFileMaxFiles").val()),$list=$field.find(".gridImages"),$uploadArea=$field.find(".InputfieldImageUpload");$uploadArea.on("change","input[type=file]",function(){var $t=$(this),$mask=$t.parent(".InputMask");if($t.val().length>1)$mask.addClass("ui-state-disabled");else $mask.removeClass("ui-state-disabled");if($t.next("input.InputfieldFile").length>0)return;var numFiles=$list.children("li").length+$uploadArea.find("input[type=file]").length+1;if(maxFiles>0&&numFiles>=maxFiles)return;$uploadArea.find(".InputMask").not(":last").each(function(){var $m=$(this);if($m.find("input[type=file]").val()<1)$m.remove()});var $i=$mask.clone().removeClass("ui-state-disabled");$i.children("input[type=file]").val("");$i.insertAfter($mask)})})}function initUploadHTML5($inputfield){var $target;if($inputfield.length>0){$target=$inputfield.find(".InputfieldImageUpload")}else{$target=$(".InputfieldImageUpload")}$target.each(function(i){var $this=$(this);var $content=$this.closest(".InputfieldContent");if($this.hasClass("InputfieldImageInitUpload"))return;initHTML5Item($content,i);$this.addClass("InputfieldImageInitUpload")});function initHTML5Item($this,i){var $form=$this.parents("form");var $repeaterItem=$this.closest(".InputfieldRepeaterItem");var $uploadAttrs=$this.find(".InputfieldImageUpload");var postUrl=$uploadAttrs.data("posturl");var $postToken=$form.find("input._post_token");var postTokenName=$postToken.attr("name");var postTokenValue=$postToken.val();var $errorParent=$this.find(".InputfieldImageErrors").first();var fieldName=$uploadAttrs.data("fieldname");var $inputfield=$this.closest(".Inputfield.InputfieldImage");var extensions=$uploadAttrs.data("extensions").toLowerCase();var maxFilesize=$uploadAttrs.data("maxfilesize");var filesUpload=$this.find("input[type=file]").get(0);var $fileList=$this.find(".gridImages");var fileList=$fileList.get(0);var gridSize=$fileList.data("gridsize");var doneTimer=null;var maxFiles=parseInt($this.find(".InputfieldImageMaxFiles").val());var resizeSettings=getClientResizeSettings($inputfield);var useClientResize=resizeSettings.maxWidth>0||resizeSettings.maxHeight>0||resizeSettings.maxSize>0;if($repeaterItem.length){postUrl=$repeaterItem.attr("data-editUrl")}else if(!postUrl){postUrl=$form.attr("action")}postUrl+=(postUrl.indexOf("?")>-1?"&":"?")+"InputfieldFileAjax=1";var $f=$("#Inputfield_id");if($f.length)postUrl+="&eid="+$f.val();if(fieldName.indexOf("[")>-1)fieldName=fieldName.slice(0,-2);setupDropzone($this);if(maxFiles!=1)setupDropInPlace($fileList);$fileList.children().addClass("InputfieldFileItemExisting");$inputfield.on("pwimageupload",function(event,data){traverseFiles([data.file],data.xhr)});function errorItem(message,filename){if(typeof filename!=="undefined")message=""+filename+": "+message;var icon=" ";return"
      • "+icon+message+"
      • "}function basename(str){var base=new String(str).substring(str.lastIndexOf("/")+1);if(base.lastIndexOf(".")!=-1)base=base.substring(0,base.lastIndexOf("."));return base}function setupDropzone($el){if($el.hasClass("InputfieldImageDropzoneInit"))return;var el=$el.get(0);var $inputfield=$el.closest(".Inputfield");function dragStart(){if($inputfield.hasClass("pw-drag-in-file"))return;$el.addClass("ui-state-hover");$inputfield.addClass("pw-drag-in-file")}function dragStop(){if(!$inputfield.hasClass("pw-drag-in-file"))return;$el.removeClass("ui-state-hover");$inputfield.removeClass("pw-drag-in-file")}el.addEventListener("dragleave",function(){dragStop()},false);el.addEventListener("dragenter",function(evt){evt.preventDefault();dragStart()},false);el.addEventListener("dragover",function(evt){if(!$el.is("ui-state-hover"))dragStart();evt.preventDefault();evt.stopPropagation();return false},false);el.addEventListener("drop",function(evt){traverseFiles(evt.dataTransfer.files);dragStop();evt.preventDefault();evt.stopPropagation();return false},false);$el.addClass("InputfieldImageDropzoneInit")}function setupDropInPlace($gridImages){var $i=null;var haltDrag=false;var timer=null;var $inputfield=$gridImages.closest(".Inputfield");function addInputfieldClass(){$inputfield.addClass("pw-drag-in-file")}function removeInputfieldClass(){$inputfield.removeClass("pw-drag-in-file")}function getCenterCoordinates($el){var offset=$el.offset();var width=$el.width();var height=$el.height();var centerX=offset.left+width/2;var centerY=offset.top+height/2;return{clientX:centerX,clientY:centerY}}function noDropInPlace(){return $gridImages.find(".InputfieldImageEdit--active").length>0}function dragEnter(evt){if(noDropInPlace())return;evt.preventDefault();evt.stopPropagation();addInputfieldClass();haltDrag=false;if($i==null){var gridSize=$gridImages.attr("data-size")+"px";var $o=$("
        ").addClass("gridImage__overflow");if($gridImages.closest(".InputfieldImageEditAll").length){$o.css({width:"100%",height:gridSize})}else{$o.css({width:gridSize,height:gridSize})}$i=$("
      • ").addClass("ImageOuter gridImage gridImagePlaceholder").append($o);$gridImages.append($i)}var coords=getCenterCoordinates($i);$i.simulate("mousedown",coords)}function dragOver(evt){if(noDropInPlace())return;evt.preventDefault();evt.stopPropagation();addInputfieldClass();haltDrag=false;if($i==null)return;var coords={clientX:evt.originalEvent.clientX,clientY:evt.originalEvent.clientY};$i.simulate("mousemove",coords)}function dragEnd(evt){if(noDropInPlace())return;evt.preventDefault();evt.stopPropagation();if($i==null)return false;haltDrag=true;if(timer)clearTimeout(timer);timer=setTimeout(function(){if(!haltDrag||$i==null)return;$i.remove();$i=null;removeInputfieldClass()},1e3)}function drop(evt){if(noDropInPlace())return;removeInputfieldClass();haltDrag=false;var coords={clientX:evt.clientX,clientY:evt.clientY};$i.simulate("mouseup",coords);$uploadBeforeItem=$i.next(".gridImage");$i.remove();$i=null}if($gridImages.length&&!$gridImages.hasClass("gridImagesInitDropInPlace")){$gridImages.on("dragenter",dragEnter);$gridImages.on("dragover",dragOver);$gridImages.on("dragleave",dragEnd);$gridImages.on("drop",drop);$gridImages.addClass("gridImagesInitDropInPlace")}}function uploadFile(file,extension,xhrsub){var labels=ProcessWire.config.InputfieldImage.labels;var filesizeStr=parseInt(file.size/1024,10)+" kB";var tooltipMarkup=""+'
        '+""+""+'"+""+""+""+""+""+""+"
        "+labels.dimensions+"'+labels.na+"
        "+labels.filesize+""+filesizeStr+"
        "+labels.variations+"0
        "+"
        ";var $progressItem=$('
      • '),$tooltip=$(tooltipMarkup),$imgWrapper=$('
        '),$imageData=$('
        '),$hover=$("
        "),$progressBar=$(""),$edit=$(' '),$spinner=$('
        '),reader,xhr,fileData,fileUrl=URL.createObjectURL(file),$fileList=$inputfield.find(".gridImages"),singleMode=maxFiles==1,size=getCookieData($inputfield,"size"),listSize=getCookieData($inputfield,"listSize"),listMode=$inputfield.hasClass("InputfieldImageEditAll"),$img=$('');$imgWrapper.append($img);$hover.find(".gridImage__inner").append($edit);$hover.find(".gridImage__inner").append($spinner.css("display","none"));$hover.find(".gridImage__inner").append($progressBar);$imageData.append($(""+'

        '+file.name+"

        "+''+filesizeStr+""));if(listMode){$imgWrapper.css("width",listSize+"%");$imageData.css("width",100-listSize+"%")}else{$imgWrapper.css({width:size+"px",height:size+"px"})}$progressItem.append($tooltip).append($imgWrapper).append($hover).append($imageData);$img.attr({src:fileUrl,"data-original":fileUrl});img=new Image;img.addEventListener("load",function(){$tooltip.find(".dimensions").html(this.width+" × "+this.height);var factor=Math.min(this.width,this.height)/size;$img.attr({width:this.width/factor,height:this.height/factor})},false);img.src=fileUrl;if(typeof xhrsub!="undefined"){xhr=xhrsub}else{xhr=new XMLHttpRequest}function updateProgress(evt){if(typeof evt!="undefined"){if(!evt.lengthComputable)return;$progressBar.val(parseInt(evt.loaded/evt.total*100))}$("body").addClass("pw-uploading");$spinner.css("display","block")}xhr.upload.addEventListener("progress",updateProgress,false);xhr.addEventListener("load",function(){xhr.getAllResponseHeaders();var response=JSON.parse(xhr.responseText);if(typeof response.ajaxResponse!="undefined")response=response.ajaxResponse;var wasZipFile=response.length>1;if(response.error!==undefined)response=[response];for(var n=0;n-1){uploadReplaceName=uploadReplaceName.substring(0,uploadReplaceName.indexOf("?"))}var uploadReplaceExt=uploadReplaceName.substring(uploadReplaceName.lastIndexOf(".")+1).toLowerCase();uploadReplaceName=uploadReplaceName.substring(0,uploadReplaceName.lastIndexOf("."));if(uploadReplaceExt==uploadNewExt){$imageEditName.children("span").text(uploadReplaceName).removeAttr("contenteditable")}$markup.find(".gridImage__edit").trigger("click")}uploadReplace.file="";uploadReplace.item=null;uploadReplace.edit=null}if(doneTimer)clearTimeout(doneTimer);$uploadBeforeItem=null;doneTimer=setTimeout(function(){if(maxFiles!=1){setupSortable($fileList)}else{setupMagnificForSingle($inputfield)}$("body").removeClass("pw-uploading");$fileList.trigger("AjaxUploadDone")},500);$inputfield.trigger("change").removeClass("InputfieldFileEmpty")},false);if(uploadReplace.edit){uploadReplace.edit.find(".InputfieldImageEdit__close").trigger("click")}else if($inputfield.find(".InputfieldImageEdit:visible").length){$inputfield.find(".InputfieldImageEdit__close").trigger("click")}if(uploadReplace.item){uploadReplace.item.replaceWith($progressItem);uploadReplace.item=$progressItem}else if($uploadBeforeItem&&$uploadBeforeItem.length){$uploadBeforeItem.before($progressItem)}else{$fileList.append($progressItem)}function sendUpload(file,imageData){if(typeof xhrsub=="undefined"){xhr.open("POST",postUrl,true)}xhr.setRequestHeader("X-FILENAME",encodeURIComponent(file.name));xhr.setRequestHeader("X-FIELDNAME",fieldName);if(uploadReplace.item)xhr.setRequestHeader("X-REPLACENAME",uploadReplace.file);xhr.setRequestHeader("Content-Type","application/octet-stream");xhr.setRequestHeader("X-"+postTokenName,postTokenValue);xhr.setRequestHeader("X-REQUESTED-WITH","XMLHttpRequest");if(typeof imageData!="undefined"&&imageData!=false){xhr.send(imageData)}else{xhr.send(file)}updateGrid();$inputfield.trigger("change");var numFiles=$inputfield.find(".InputfieldFileItem").length;if(numFiles==1){$inputfield.removeClass("InputfieldFileEmpty").removeClass("InputfieldFileMultiple").addClass("InputfieldFileSingle")}else if(numFiles>1){$inputfield.removeClass("InputfieldFileEmpty").removeClass("InputfieldFileSingle").addClass("InputfieldFileMultiple")}}updateProgress();if(typeof file.name==="undefined")file.name=getUploadFilename(file);var ext=file.name.substring(file.name.lastIndexOf(".")+1).toLowerCase();if(useClientResize&&(ext=="jpg"||ext=="jpeg"||ext=="png"||ext=="gif")){var resizer=new PWImageResizer(resizeSettings);$spinner.addClass("pw-resizing");resizer.resize(file,function(imageData){$spinner.removeClass("pw-resizing");sendUpload(file,imageData)})}else{sendUpload(file)}}function traverseFiles(files,xhr){var toKilobyte=function(i){return parseInt(i/1024,10)};if(typeof files==="undefined"){fileList.innerHTML="No support for the File API in this web browser";return}for(var i=0,l=files.length;imaxFilesize&&maxFilesize>2e6){var filesizeKB=toKilobyte(files[i].size),maxFilesizeKB=toKilobyte(maxFilesize);if(typeof ProcessWire.config.InputfieldFile.labels["too-big"]!="undefined"){message=ProcessWire.config.InputfieldFile.labels["too-big"];message=message.replace("MAX_KB",maxFilesizeKB)}else{message="Filesize "+filesizeKB+" kb is too big. Maximum allowed is "+maxFilesizeKB+" kb"}$errorParent.append(errorItem(message,files[i].name))}else if(typeof xhr!="undefined"){uploadFile(files[i],extension,xhr)}else{uploadFile(files[i],extension)}if(maxFiles==1)break}}function getUploadFilename(file){if(typeof file.name!=="undefined")return file.name;var ext="";switch(file.type){case"image/jpeg":ext=".jpg";break;case"image/png":ext=".png";break;case"image/gif":ext=".gif";break;case"image/svg+xml":ext=".svg";break;case"image/webp":ext=".webp"}return $inputfield.attr("id").replace("wrap_Inputfield_","")+ext}filesUpload.addEventListener("change",function(evt){traverseFiles(this.files);evt.preventDefault();evt.stopPropagation();this.value=""},false)}function setupEnlargementDropzones(){var sel=".InputfieldImageEdit__imagewrapper img";$(document).on("dragenter",sel,function(){var $this=$(this);if($this.closest(".InputfieldImageMax1").length)return;var src=$this.attr("src");var $edit=$this.closest(".InputfieldImageEdit");var $parent=$this.closest(".InputfieldImageEdit__imagewrapper");$parent.addClass("InputfieldImageEdit__replace");uploadReplace.file=new String(src).substring(src.lastIndexOf("/")+1);uploadReplace.item=$("#"+$edit.attr("data-for"));uploadReplace.edit=$edit}).on("dragleave",sel,function(){var $this=$(this);if($this.closest(".InputfieldImageMax1").length)return;var $parent=$this.closest(".InputfieldImageEdit__imagewrapper");$parent.removeClass("InputfieldImageEdit__replace");uploadReplace.file="";uploadReplace.item=null;uploadReplace.edit=null})}setupEnlargementDropzones()}function getClientResizeSettings($inputfield){var settings={maxWidth:0,maxHeight:0,maxSize:0,quality:1,autoRotate:true,debug:ProcessWire.config.debug};var data=$inputfield.attr("data-resize");if(typeof data!="undefined"&&data.length){data=data.split(";");settings.maxWidth=data[0].length?parseInt(data[0]):0;settings.maxHeight=data[1].length?parseInt(data[1]):0;settings.maxSize=data[2].length?parseFloat(data[2]):0;settings.quality=parseFloat(data[3])}return settings}function init(){$(".InputfieldImage.Inputfield").each(function(){initInputfield($(this))});initGridEvents();if(useAjaxUpload()){initUploadHTML5("")}else{initUploadOldSchool()}$(document).on("reloaded",".InputfieldImage",function(){var $inputfield=$(this);$inputfield.removeClass("InputfieldImageInit");initInputfield($inputfield);initUploadHTML5($inputfield);Inputfields.init($inputfield);$(".InputfieldImageListToggle--active",$inputfield).trigger("click")}).on("wiretabclick",function(e,$newTab,$oldTab){$newTab.find(".InputfieldImage").each(function(){initInputfield($(this))})}).on("opened",function(){var $t=$(this);if($t.hasClass("InputfieldImage")){initInputfield($t)}else{$t.find(".InputfieldImage").each(function(){initInputfield($(this))})}})}init()}jQuery(document).ready(function($){InputfieldImage($)}); \ No newline at end of file From b4ddc89fb9b84cf130d943e20bbce9d368354294 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Thu, 17 Apr 2025 12:03:53 -0400 Subject: [PATCH 18/35] Add support in MarkupRegions for removing class names by wildcard. For instance, `
        ` would remove all class names from #content div starting with "uk-width-". Regex patterns are also supported when pattern is identifed by `/`, i.e. `
        ` would remove all class names from $content starting with "uk-text" or "uk-width". --- wire/core/WireMarkupRegions.php | 36 +++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/wire/core/WireMarkupRegions.php b/wire/core/WireMarkupRegions.php index f3190663e..bcfc4de13 100644 --- a/wire/core/WireMarkupRegions.php +++ b/wire/core/WireMarkupRegions.php @@ -956,14 +956,38 @@ public function mergeTags($htmlTag, $mergeTag) { $classes = explode(' ', $value); $classes = array_merge($tagInfo['classes'], $classes); $classes = array_unique($classes); - // identify remove classes + $forceAddClasses = []; + $removeMatchClasses = []; + // identify force add and remove classes foreach($classes as $key => $class) { - if(strpos($class, '-') !== 0) continue; - $removeClass = ltrim($class, '-'); - unset($classes[$key]); - while(false !== ($k = array_search($removeClass, $classes))) unset($classes[$k]); + if(strpos($class, '+') === 0){ + $class = ltrim($class, '+'); + $forceAddClasses[$class] = $class; + unset($classes[$key]); + } else if(strpos($class, '-') === 0) { + $removeClass = substr($class, 1); + if(strpos($removeClass, '*') !== false) $removeMatchClasses[] = $removeClass; + unset($classes[$key]); + while(false !== ($k = array_search($removeClass, $classes))) unset($classes[$k]); + } + } + if(count($classes) && count($removeMatchClasses)) { + foreach($removeMatchClasses as $removeClass) { + if(strpos($removeClass, '/') === 0) { + // already a regex + if(strrpos($removeClass, '/') === 0) $removeClass .= '/'; + } else { + // convert wildcard to regex + $removeClass = '/^' . str_replace('\\*', '.+', preg_quote($removeClass, '/')) . '$/'; + } + foreach($classes as $key => $class) { + if(preg_match($removeClass, $class)) { + unset($classes[$key]); + } + } + } } - $attrs['class'] = implode(' ', $classes); + $attrs['class'] = implode(' ', array_merge($forceAddClasses, $classes)); } else { // replace $attrs[$name] = $value; From 0a317971f84142fa06ed6db5c1817e119da99ae1 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Thu, 17 Apr 2025 12:13:47 -0400 Subject: [PATCH 19/35] Phpdoc updates in Page.php --- wire/core/Page.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/wire/core/Page.php b/wire/core/Page.php index 7f32237be..0ff38f09f 100644 --- a/wire/core/Page.php +++ b/wire/core/Page.php @@ -3579,7 +3579,7 @@ public function ___loaded() { } * * The output formatting state determines if a page's output is allowed to be filtered by runtime formatters. * Pages used for output should have output formatting on. Pages you intend to manipulate and save should - * have it off. + * have it off. See this post about [output formatting](https://processwire.com/blog/posts/output-formatting/). * * ~~~~~ * // Set output formatting state off, for page manipulation @@ -3596,6 +3596,7 @@ public function ___loaded() { } * @param bool $outputFormatting Optional, default true * @return $this * @see Page::outputFormatting(), Page::of() + * @link https://processwire.com/blog/posts/output-formatting/ * */ public function setOutputFormatting($outputFormatting = true) { @@ -3626,6 +3627,8 @@ public function outputFormatting() { * - Pages used for front-end output should have output formatting turned ON. * * - Pages that you are manipulating and saving should have output formatting turned OFF. + * + * See this post about [output formatting](https://processwire.com/blog/posts/output-formatting/). * * ~~~~~ * // Set output formatting state off, for page manipulation @@ -3640,6 +3643,7 @@ public function outputFormatting() { * * @param bool $outputFormatting If specified, sets output formatting state ON or OFF. If not specified, nothing is changed. * @return bool Current output formatting state (before this function call, if it was changed) + * @link https://processwire.com/blog/posts/output-formatting/ * */ public function of($outputFormatting = null) { From 5f17f5ff9d4be3efc329e70e3c81732d8d036641 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Thu, 17 Apr 2025 12:14:26 -0400 Subject: [PATCH 20/35] Phpdoc update in InputfieldWrapper for ProcessWireAPI docs --- wire/core/InputfieldWrapper.php | 84 +++++++++++++++++---------------- 1 file changed, 43 insertions(+), 41 deletions(-) diff --git a/wire/core/InputfieldWrapper.php b/wire/core/InputfieldWrapper.php index c0fbdb6d1..d0bb71b4b 100644 --- a/wire/core/InputfieldWrapper.php +++ b/wire/core/InputfieldWrapper.php @@ -15,6 +15,8 @@ * * InputfieldWrapper is not designed to render an Inputfield specifically, but you can set a value attribute * containing content that will be rendered before the wrapper. + * + * #pw-summary-properties Access any common Inputfield type class name from an InputfieldWrapper and it will return a new instance of that Inputfield, i.e. `$f = $inputfields->InputfieldText;` Below are several examples. * * @property bool $renderValueMode True when only rendering values, i.e. no inputs (default=false). #pw-internal * @property bool $quietMode True to suppress label, description and notes, often combined with renderValueMode (default=false). #pw-internal @@ -27,47 +29,47 @@ * @method Inputfield new($typeName, $name = '', $label = '', array $settings = []) #pw-group-manipulation * @method bool allowProcessInput(Inputfield $inputfield) Allow Inputfield to have input processed? (3.0.207+) #pw-internal * - * @property InputfieldAsmSelect $InputfieldAsmSelect - * @property InputfieldButton $InputfieldButton - * @property InputfieldCheckbox $InputfieldCheckbox - * @property InputfieldCheckboxes $InputfieldCheckboxes - * @property InputfieldCKEditor $InputfieldCkeditor - * @property InputfieldCommentsAdmin $InputfieldCommentsAdmin - * @property InputfieldDatetime $InputfieldDatetime - * @property InputfieldEmail $InputfieldEmail - * @property InputfieldFieldset $InputfieldFieldset - * @property InputfieldFieldsetClose $InputfieldlFieldsetClose - * @property InputfieldFieldsetOpen $InputfieldFieldsetOpen - * @property InputfieldFieldsetTabOpen $InputfieldFieldsetTabOpen - * @property InputfieldFile $InputfieldFile - * @property InputfieldFloat $InputfieldFloat - * @property InputfieldForm $InputfieldForm - * @property InputfieldHidden $InputfieldHidden - * @property InputfieldIcon $InputfieldIcon - * @property InputfieldImage $InputfieldImage - * @property InputfieldInteger $InputfieldInteger - * @property InputfieldMarkup $InputfieldMarkup - * @property InputfieldName $InputfieldName - * @property InputfieldPage $InputfieldPage - * @property InputfieldPageAutocomplete $InputfieldPageAutocomplete - * @property InputfieldPageListSelect $InputfieldPageListSelect - * @property InputfieldPageListSelectMultiple $InputfieldPageListSelectMultiple - * @property InputfieldPageName $InputfieldPageName - * @property InputfieldPageTable $InputfieldPageTable - * @property InputfieldPageTitle $InputfieldPageTitle - * @property InputfieldPassword $InputfieldPassword - * @property InputfieldRadios $InputfieldRadios - * @property InputfieldRepeater $InputfieldRepeater - * @property InputfieldSelect $InputfieldSelect - * @property InputfieldSelectMultiple $InputfieldSelectMultiple - * @property InputfieldSelector $InputfieldSelector - * @property InputfieldSubmit $InputfieldSubmit - * @property InputfieldText $InputfieldText - * @property InputfieldTextarea $InputfieldTextarea - * @property InputfieldTextTags $InputfieldTextTags - * @property InputfieldToggle $InputfieldToggle - * @property InputfieldURL $InputfieldURL - * @property InputfieldWrapper $InputfieldWrapper + * @property InputfieldAsmSelect $InputfieldAsmSelect Create new asmSelect Inputfield #pw-group-properties + * @property InputfieldButton $InputfieldButton Create new button Inputfield #pw-group-properties + * @property InputfieldCheckbox $InputfieldCheckbox Create new checkbox Inputfield #pw-group-properties + * @property InputfieldCheckboxes $InputfieldCheckboxes Create new checkboxes Inputfield #pw-group-properties + * @property InputfieldCKEditor $InputfieldCKEditor Create new CKEditor Inputfield #pw-group-properties + * @property InputfieldCommentsAdmin $InputfieldCommentsAdmin #pw-internal + * @property InputfieldDatetime $InputfieldDatetime Create new date/time Inputfield #pw-group-properties + * @property InputfieldEmail $InputfieldEmail Create new email Inputfield #pw-group-properties + * @property InputfieldFieldset $InputfieldFieldset Create new Fieldset InputfieldWrapper #pw-group-properties + * @property InputfieldFieldsetClose $InputfieldlFieldsetClose #pw-internal + * @property InputfieldFieldsetOpen $InputfieldFieldsetOpen #pw-internal + * @property InputfieldFieldsetTabOpen $InputfieldFieldsetTabOpen #pw-internal + * @property InputfieldFile $InputfieldFile Create new file Inputfield #pw-group-properties + * @property InputfieldFloat $InputfieldFloat Create new float Inputfield #pw-group-properties + * @property InputfieldForm $InputfieldForm Create new form InputfieldWrapper #pw-group-properties + * @property InputfieldHidden $InputfieldHidden Create new hidden Inputfield #pw-group-properties + * @property InputfieldIcon $InputfieldIcon Create new icon Inputfield #pw-group-properties + * @property InputfieldImage $InputfieldImage Create new image Inputfield #pw-group-properties + * @property InputfieldInteger $InputfieldInteger Create new integer Inputfield #pw-group-properties + * @property InputfieldMarkup $InputfieldMarkup Create new markup Inputfield #pw-group-properties + * @property InputfieldName $InputfieldName #pw-internal + * @property InputfieldPage $InputfieldPage Create new Page selection Inputfield #pw-group-properties + * @property InputfieldPageAutocomplete $InputfieldPageAutocomplete Create new Page selection autocomplete Inputfield #pw-group-properties + * @property InputfieldPageListSelect $InputfieldPageListSelect Create new PageListSelect Inputfield #pw-group-properties + * @property InputfieldPageListSelectMultiple $InputfieldPageListSelectMultiple Create new multiple PageListSelect Inputfield #pw-group-properties + * @property InputfieldPageName $InputfieldPageName #pw-internal + * @property InputfieldPageTable $InputfieldPageTable #pw-internal + * @property InputfieldPageTitle $InputfieldPageTitle #pw-internal + * @property InputfieldPassword $InputfieldPassword #pw-internal + * @property InputfieldRadios $InputfieldRadios Create new radio buttons Inputfield #pw-group-properties + * @property InputfieldRepeater $InputfieldRepeater #pw-internal + * @property InputfieldSelect $InputfieldSelect Create new Inputfield #pw-group-properties + * @property InputfieldSelector $InputfieldSelector #pw-internal + * @property InputfieldSubmit $InputfieldSubmit Create new submit button Inputfield #pw-group-properties + * @property InputfieldText $InputfieldText Create new single-line text Inputfield #pw-group-properties + * @property InputfieldTextarea $InputfieldTextarea Create new multi-line