diff --git a/CHANGELOG.md b/CHANGELOG.md index 03472e195..089037189 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -59,6 +59,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Imports: assets take Status, Primary IP (or DHCP), Primary MAC, Network, Link, Second Link and Client Link, Vendor, Order Reference, Install Date, Warranty Expire, Tags and any of their details, besides what they took before. Assigned To, Location, Vendor and Network are the client's own, by name - Assigned To by email too. A virtual machine's Host can be further down the same file. - Imports: contacts take Primary, Important, Billing, Technical, Tags and Notes, and keep a phone's country code; locations take Country, On-site Contact, Primary, Tags and Notes; credentials take URI 2, Favorite, Asset, Contact, Tags and Notes; networks take Site, Provider, Tags and Notes. A credential whose 2FA secret isn't one is not imported, rather than imported without its 2FA. - Imports: vendors, domains, certificates, licenses and services import too, from Import under the arrow beside each list's New button. Vendors go to the client whose vendors it's opened from, or are your own when it's opened from your vendors. A new domain is looked up, and a certificate with a host is checked, on its refresher's next run. A license's Assets and Contacts give it seats, and a service's Runs On, Vendors, People and Domains link it to them - by name, added to what it has. A license Type that isn't a software type yet is added. +- Pictures: your picture, a user's and a contact's, and the photos of assets, locations and racks, show on their form as the picture itself with a camera on it - the person's initials, or a camera, when there isn't one. Click it to open the Picture window: drop, paste or choose a picture, crop it to fit the shape it's shown in - a circle for a person - by dragging and zooming, turn it a quarter at a time, and Use this picture, or Remove the one there is. Photos of assets, locations and racks can also be square, 4:3, 3:4 or the whole photo. What's kept is what's in the frame, at up to 512 pixels across for a person and 2048 for a photo, so a big phone photo goes in at a sensible size, the right way up, without its location or camera details. A person's initials follow their name as it's typed. ### Bug Fixes @@ -103,6 +104,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - `Virtual Machine` in `ASSET_TYPES` (`functions/asset_type.php`) has the `purchase` fields - Vendor, Order / invoice reference and Purchased. - Imports run through one window, `agent/modals/import/import.php?kind=&client_id=`, and one handler, `agent/post/import.php`: `import_check` and `import_run` (both JSON, the file sent each time with the column map) and `import_template`. Each kind is an entry in `importKinds()` (`functions/import_kinds.php`) - its permission module, whether it is a client's, its fields (template and export heading, other headings taken for it, required, help, example), `find` (the record already here), `key` (what makes two rows the same record), `legacy` (the old fixed columns, by position) and `row`, which adds or updates one record from the fields the file has. Adding a kind is an entry and its `row` function. `importProcess()` (`functions/import.php`) runs the rows in a transaction, each behind a savepoint so a row that fails is undone whole, commits it for `import_run` and rolls it back for `import_check` - the check is the import itself, as the email preview is; like it, a check moves `AUTO_INCREMENT` on. `importAutoMap()` matches headings, `importFile()` checks and reads the upload (comma or semicolon, byte-order mark, 10 MB and 5,000 rows at most). The per-kind import windows, their `import_*_csv` and `download_*_csv_template` handlers, `importColumns()`, `importCsvRows()`, `importLegacyColumns()`, `importHeadingsText()`, `importTagIds()`, `importNotesText()` and `NETWORK_CSV_COLUMNS` are gone. Templates need read access to the kind's module - the products template had no check. An asset an import adds or updates gets an `asset_history` row. - Import kinds `vendors`, `domains`, `certificates`, `licenses` and `services` in `importKinds()`, saved through `vendorFormSet()`, `domainFormSet()` with `domainWriteHistory()`, `certificateFormSet()` with `certificateWriteHistory()`, `softwareFormSet()` with `softwareSyncSeats()` and `softwareAddKeys()`, and `serviceFormSet()` with `linkAdd()`. Updating, a kind's row reads the record's current values into the form's fields and lays the file's over them, so it is checked as the form checks it. A kind's `module` can be a callable of the client id (`importModule()`) and its `client` `'optional'` - a vendor is the client's (`module_client`), or with none your own (`module_financial`). `log` names it in the audit log when that isn't its `one` (licenses log as Software). `importClientRecordId()` finds a client's domain, and `importClientRecordIds()` reads a cell of names separated by commas. The Domains and Certificates menus show to an agent who can add, so Import is there on an empty list. +- Picture fields: `pictureField($name, $remove_name, $current, $empty, $opts)` (`functions/picture.php`) renders the picture as a button with a camera badge, a hidden file input named `$name` and a hidden `$remove_name` input; `js/picture_field.js` opens the Picture window over the form's own (the window stacking in `js/app.js`), crops on a canvas and puts the crop in the file input through `DataTransfer` - a JPG for a JPG, else WebP, PNG where the browser can't write WebP - and sets the remove input to 1 on Remove, so the forms post the same fields as before and no handler changed. Options: `round`, `shapes`, `max`, `class` (the new picture's ``), `box` and `name` (the field the initials follow). `picturePhoto()` and `picturePhotoEmpty()` are a photo's two looks. Used on the profile, Admin > Users, contacts, assets, locations and racks, replacing their file inputs, remove boxes and preview scripts. A browser without `DataTransfer` gets the file picker and the file as picked. ## [26.11.8] diff --git a/admin/modals/user/user_form.php b/admin/modals/user/user_form.php index b82c940a6..ccd571629 100644 --- a/admin/modals/user/user_form.php +++ b/admin/modals/user/user_form.php @@ -60,22 +60,11 @@ $value = function ($key) use ($form) {
- + true, 'title' => 'Picture', 'class' => 'itflow-contact-avatar itflow-contact-avatar-lg', 'name' => 'name']) ?>
- -
- - -
-
- JPG, PNG, GIF or WebP, up to 5 MB. Without one, their initials. - -
- - -
- -
+
Picture
+
Click it to add one or change it. Without one, their initials.
@@ -259,46 +248,6 @@ $value = function ($key) use ($form) { } var form = root.closest('form'); - // The picture - shown as soon as it is picked - var avatarInput = root.querySelector('[data-user-avatar-input]'); - var avatarPreview = root.querySelector('[data-user-avatar-preview]'); - var avatarOriginal = avatarPreview.innerHTML; - var avatarRemove = root.querySelector('[data-user-avatar-remove]'); - avatarInput.addEventListener('change', function () { - var file = avatarInput.files && avatarInput.files[0]; - if (file && /^image\//.test(file.type)) { - var img = document.createElement('img'); - img.className = 'itflow-contact-avatar itflow-contact-avatar-lg'; - img.alt = ''; - img.src = URL.createObjectURL(file); - avatarPreview.replaceChildren(img); - if (avatarRemove) { - avatarRemove.checked = false; - } - } else { - avatarPreview.innerHTML = avatarOriginal; - } - }); - if (avatarRemove) { - avatarRemove.addEventListener('change', function () { - avatarPreview.classList.toggle('opacity-25', avatarRemove.checked); - if (avatarRemove.checked) { - avatarInput.value = ''; - avatarPreview.innerHTML = avatarOriginal; - } - }); - } - - // No picture - their initials, as the name is typed - var nameInput = root.querySelector('[data-user-name]'); - nameInput.addEventListener('input', function () { - var initials = avatarPreview.querySelector('span.itflow-contact-avatar'); - if (initials && !(avatarInput.files && avatarInput.files.length)) { - var words = nameInput.value.trim().split(/\s+/).filter(Boolean).slice(0, 2); - initials.textContent = words.map(function (w) { return w.charAt(0).toUpperCase(); }).join('') || '?'; - } - }); - // Make up a password - words, easy to read out over the phone var password = root.querySelector('[data-user-password]'); root.querySelector('[data-user-generate]').addEventListener('click', function () { diff --git a/agent/modals/asset/asset_form.php b/agent/modals/asset/asset_form.php index 6888aaa85..dcce7bfc6 100644 --- a/agent/modals/asset/asset_form.php +++ b/agent/modals/asset/asset_form.php @@ -538,20 +538,9 @@ $asset_form_icons = [
- - -
Current photo">
- -
- - -
- -
- - -
- + + 'square,4:3,whole']) ?>
diff --git a/agent/modals/contact/contact_form.php b/agent/modals/contact/contact_form.php index 01732720d..c3b8bd8b8 100644 --- a/agent/modals/contact/contact_form.php +++ b/agent/modals/contact/contact_form.php @@ -268,19 +268,9 @@ $contact_roles = [
- -
-
- - -
- -
- - -
- -
+ true, 'title' => 'Photo', 'class' => 'itflow-contact-avatar itflow-contact-avatar-lg', 'name' => 'name']) ?> +
Click it to add a photo or change it.
diff --git a/agent/modals/location/location_form.php b/agent/modals/location/location_form.php index 5d8ff7536..0ad46e571 100644 --- a/agent/modals/location/location_form.php +++ b/agent/modals/location/location_form.php @@ -109,20 +109,9 @@ $form_id = 'locationForm' . ($location_form_mode === 'edit' ? $location_id : 'Ne
- - " alt=""> - -
- - -
- - -
- -
The front of the building - so a tech knows it when they pull up.
- -
+ 'square,4:3,whole']) ?> +
The front of the building - so a tech knows it when they pull up. Click it to add a photo or change it.
diff --git a/agent/modals/rack/rack_form.php b/agent/modals/rack/rack_form.php index 9d9e9e2aa..aa05368c6 100644 --- a/agent/modals/rack/rack_form.php +++ b/agent/modals/rack/rack_form.php @@ -137,19 +137,9 @@ isset($mysqli) || die("Direct file access is not allowed");
['file', 'remove_photo', $rack_photo], 'rear' => ['file_rear', 'remove_photo_rear', $rack_photo_rear]] as $photo_side => [$photo_field, $photo_remove_field, $photo_current]) { ?>
- - -
- " alt=" of the rack"> -
- - - -
- - -
- + + ucfirst($photo_side) . ' photo', 'shapes' => '4:3,3:4,whole', 'box' => 'wide']) ?>
diff --git a/agent/user/user_details.php b/agent/user/user_details.php index 1191f96fe..fc74b1d97 100644 --- a/agent/user/user_details.php +++ b/agent/user/user_details.php @@ -24,18 +24,9 @@ $has_avatar = trim((string) $me['user_avatar']) !== '';
- -
- - -
JPG, PNG, GIF or WebP, up to 5 MB.
- -
- - -
- -
+ true, 'title' => 'Your picture', 'class' => 'itflow-contact-avatar itflow-contact-avatar-xl', 'name' => 'name']) ?> +
Click your picture to change it.
@@ -100,37 +91,6 @@ $has_avatar = trim((string) $me['user_avatar']) !== ''; (function () { var form = document.getElementById('profileForm'); - // The picture - shown as soon as it is picked - var input = form.querySelector('[data-profile-avatar-input]'); - var preview = form.querySelector('[data-profile-avatar-preview]'); - var original = preview.innerHTML; - var remove = form.querySelector('[data-profile-avatar-remove]'); - input.addEventListener('change', function () { - var file = input.files && input.files[0]; - if (file && /^image\//.test(file.type)) { - var img = document.createElement('img'); - img.className = 'itflow-contact-avatar itflow-contact-avatar-xl'; - img.alt = ''; - img.src = URL.createObjectURL(file); - preview.replaceChildren(img); - preview.classList.remove('opacity-25'); - if (remove) { - remove.checked = false; - } - } else { - preview.innerHTML = original; - } - }); - if (remove) { - remove.addEventListener('change', function () { - if (remove.checked) { - input.value = ''; - preview.innerHTML = original; - } - preview.classList.toggle('opacity-25', remove.checked); - }); - } - // A new email takes your current password var email = form.querySelector('[data-profile-email]'); var current = form.querySelector('[data-profile-current]'); diff --git a/css/itflow_custom.css b/css/itflow_custom.css index 67a0cf273..f3cee3d76 100644 --- a/css/itflow_custom.css +++ b/css/itflow_custom.css @@ -3902,11 +3902,6 @@ button.itflow-rack-item-body:hover { font-size: .7rem; color: #fff; } -.itflow-rack-form-photo img { - max-width: 100%; - max-height: 8rem; - border-radius: var(--bs-border-radius); -} .itflow-rack-fit:empty { display: none; } @@ -9430,3 +9425,203 @@ a.itflow-portal-request:focus-visible { background-color: transparent !important; border: 1px solid var(--bs-secondary-color); } + +/* + * Picture fields (pictureField(), js/picture_field.js) - the picture on a + * button with a camera badge, which opens the Picture window to pick and crop + */ +.itflow-picture-field { + position: relative; + display: inline-block; + flex: 0 0 auto; +} +.itflow-picture-button { + position: relative; + display: block; + padding: 0; + border: 0; + border-radius: var(--bs-border-radius-lg); + background: none; + color: inherit; + cursor: pointer; +} +.itflow-picture-field.is-round .itflow-picture-button { + border-radius: 50%; +} +.itflow-picture-button:focus-visible { + outline: 2px solid var(--bs-primary); + outline-offset: 3px; +} +.itflow-picture-preview { + display: block; + overflow: hidden; + border-radius: inherit; +} +.itflow-picture-preview > .itflow-contact-avatar { + display: flex; +} +.itflow-picture-field.is-square .itflow-picture-preview { + width: 7rem; + height: 7rem; +} +.itflow-picture-field.is-wide .itflow-picture-preview { + width: 10rem; + height: 7.5rem; +} +.itflow-picture-photo { + display: block; + width: 100%; + height: 100%; + object-fit: cover; +} +/* No photo yet - a camera to add one */ +.itflow-picture-none { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: .35rem; + width: 100%; + height: 100%; + border: 2px dashed var(--bs-border-color); + border-radius: inherit; + background-color: var(--bs-tertiary-bg); + color: var(--bs-secondary-color); + font-size: .8rem; +} +.itflow-picture-none i { + font-size: 1.4rem; +} +/* Darker on hover, with the camera to say it can be changed */ +.itflow-picture-button::after { + position: absolute; + inset: 0; + border-radius: inherit; + background-color: transparent; + content: ""; + transition: background-color .15s ease-in-out; +} +.itflow-picture-button:hover::after { + background-color: rgba(0, 0, 0, .18); +} +.itflow-picture-badge { + position: absolute; + right: -.2rem; + bottom: -.2rem; + z-index: 1; + display: flex; + align-items: center; + justify-content: center; + width: 1.5rem; + height: 1.5rem; + border-radius: 50%; + background-color: var(--bs-primary); + box-shadow: 0 0 0 2px var(--bs-body-bg); + color: #fff; + font-size: .65rem; + transition: transform .15s ease-in-out; +} +.itflow-picture-field:has(.itflow-contact-avatar-xl) .itflow-picture-badge, +.itflow-picture-field.is-photo .itflow-picture-badge { + right: -.35rem; + bottom: -.35rem; + width: 2rem; + height: 2rem; + box-shadow: 0 0 0 3px var(--bs-body-bg); + font-size: .8rem; +} +.itflow-picture-button:hover .itflow-picture-badge { + transform: scale(1.1); +} + +/* The Picture window - drop, paste or choose */ +.itflow-picture-pick { + padding: 1.75rem 1rem; + border: 2px dashed var(--bs-border-color); + border-radius: var(--bs-border-radius-lg); + text-align: center; + cursor: pointer; + transition: border-color .15s ease-in-out, background-color .15s ease-in-out; +} +.itflow-picture-pick:hover, +.itflow-picture-pick:focus-visible, +.itflow-picture-pick.is-over { + border-color: var(--bs-primary); + background-color: var(--bs-primary-bg-subtle); + outline: 0; +} +.itflow-picture-pick-now { + display: inline-block; + overflow: hidden; + width: 9rem; + height: 6.75rem; + border-radius: var(--bs-border-radius-lg); +} +.itflow-picture-pick-now.is-round { + width: 6rem; + height: 6rem; + border-radius: 50%; +} +.itflow-picture-pick-now .itflow-contact-avatar { + width: 100%; + height: 100%; + font-size: 2.2rem; +} + +/* ... and crop it to fit: the picture under a frame, the rest dimmed */ +.itflow-crop-stage { + position: relative; + overflow: hidden; + border-radius: var(--bs-border-radius); + background-color: var(--bs-tertiary-bg); + cursor: grab; + touch-action: none; + user-select: none; +} +.itflow-crop-stage.is-moving { + cursor: grabbing; +} +.itflow-crop-stage:focus-visible { + outline: 2px solid var(--bs-primary); + outline-offset: 2px; +} +.itflow-crop-image { + position: absolute; + top: 0; + left: 0; + max-width: none; + transform-origin: 0 0; + will-change: transform; +} +.itflow-crop-frame { + position: absolute; + box-shadow: 0 0 0 2px rgba(255, 255, 255, .9), 0 0 0 100vmax rgba(0, 0, 0, .55); + pointer-events: none; +} +.itflow-crop-frame.is-round { + border-radius: 50%; +} +/* Thirds, while it's moved */ +.itflow-crop-stage.is-moving .itflow-crop-frame { + background: + linear-gradient(rgba(255, 255, 255, .45), rgba(255, 255, 255, .45)) 33.333% 0 / 1px 100% no-repeat, + linear-gradient(rgba(255, 255, 255, .45), rgba(255, 255, 255, .45)) 66.667% 0 / 1px 100% no-repeat, + linear-gradient(rgba(255, 255, 255, .45), rgba(255, 255, 255, .45)) 0 33.333% / 100% 1px no-repeat, + linear-gradient(rgba(255, 255, 255, .45), rgba(255, 255, 255, .45)) 0 66.667% / 100% 1px no-repeat; +} +.itflow-crop-bar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: .5rem; + margin-top: .75rem; +} +.itflow-crop-zoom { + display: flex; + flex: 1 1 9rem; + align-items: center; + gap: .4rem; + min-width: 9rem; + margin: 0; + color: var(--bs-secondary-color); +} diff --git a/functions.php b/functions.php index acfd85667..2036734ad 100644 --- a/functions.php +++ b/functions.php @@ -20,6 +20,7 @@ require_once __DIR__ . '/functions/domain.php'; require_once __DIR__ . '/functions/certificate.php'; require_once __DIR__ . '/functions/network.php'; require_once __DIR__ . '/functions/user.php'; +require_once __DIR__ . '/functions/picture.php'; require_once __DIR__ . '/functions/roles.php'; require_once __DIR__ . '/functions/api_keys.php'; require_once __DIR__ . '/functions/asset_interface.php'; diff --git a/functions/picture.php b/functions/picture.php new file mode 100644 index 000000000..aaafbafe9 --- /dev/null +++ b/functions/picture.php @@ -0,0 +1,66 @@ + a new picture shows as - for a person + * the avatar's ('itflow-picture-photo' for a photo) + * 'box' a photo's box - 'square' or 'wide' (4:3) + * 'name' the form field with the person's name - their initials follow it + */ +function pictureField($name, $remove_name, $current, $empty, array $opts = []) { + $round = !empty($opts['round']); + $noun = $round ? 'picture' : 'photo'; + $attributes = [ + 'data-picture-field' => '', + 'data-picture-title' => $opts['title'] ?? ucfirst($noun), + 'data-picture-class' => $opts['class'] ?? 'itflow-picture-photo', + 'data-picture-has' => $remove_name !== '' ? '1' : '', + 'data-crop' => $opts['shapes'] ?? 'square', + 'data-crop-max' => (string) intval($opts['max'] ?? ($round ? 512 : 2048)), + 'data-crop-shape' => $round ? 'circle' : 'rect', + 'data-picture-name' => (string) ($opts['name'] ?? ''), + ]; + $html = ''; + foreach ($attributes as $attribute => $value) { + $html .= ' ' . $attribute . '="' . escapeHtml($value) . '"'; + } + $box = $round ? 'is-round' : 'is-photo is-' . ($opts['box'] ?? 'square'); + $label = escapeHtml("Change the $noun"); + return '
' + . '' + . '' + . '' + . ($remove_name !== '' ? '' : '') + . '
'; +} + +/** A photo as a picture field shows it - $src already the page's path to it. HTML. */ +function picturePhoto($src, $alt = '') { + return '' . escapeHtml($alt) . ''; +} + +/** What a photo's field shows without one - a camera and $text. HTML. */ +function picturePhotoEmpty($text = 'Add a photo') { + return '' . escapeHtml($text) . ''; +} diff --git a/includes/footer.php b/includes/footer.php index fe6eb4101..76f14a18a 100644 --- a/includes/footer.php +++ b/includes/footer.php @@ -89,6 +89,7 @@ try { ?> + diff --git a/js/picture_field.js b/js/picture_field.js new file mode 100644 index 000000000..ef1977b35 --- /dev/null +++ b/js/picture_field.js @@ -0,0 +1,718 @@ +/* + * Picture fields (pictureField(), functions/picture.php) - a person's picture, + * or a photo of an asset, a location or a rack, shown as the form shows it, on + * a button with a camera badge. Clicking it opens the Picture window, over the + * form's own window when it is in one: + * + * - drop a picture on it, paste one, or choose one + * - crop it to fit the shape it's shown in - drag it, zoom it (the wheel, a + * pinch, the slider, or + and -), turn it a quarter at a time, or pick + * another shape where the field has more than one + * - Use this picture, or Remove the one there is + * + * The crop goes in the field's hidden file input (through a DataTransfer), + * as a JPG, or a WebP for a picture that may be see-through (PNG where the + * browser can't write WebP), no bigger than data-crop-max and without the + * photo's own data - where it was taken, the camera. Remove sets the field's + * remove input to 1. The form posts them as it always did. Opened again, the + * window has the picture picked as it was left, to change. + * + * A person's initials, where they show, follow the form field named in + * data-picture-name as it is typed. + * + * A browser that can't put a file in a field opens the file picker instead, + * and the picture goes as picked. + */ +(function () { + 'use strict'; + + if (window.itflowPictureField) { + return; + } + window.itflowPictureField = true; + + var SHAPES = { + 'square': { w: 1, h: 1, label: 'Square' }, + '4:3': { w: 4, h: 3, label: '4:3' }, + '3:4': { w: 3, h: 4, label: '3:4' }, + '16:9': { w: 16, h: 9, label: '16:9' }, + 'whole': { w: 0, h: 0, label: 'Whole' } + }; + var TYPES = /^image\/(jpeg|png|gif|webp)$/; + var MARGIN = 24; // pixels of the picture shown, dimmed, round the frame + var FRAME_MAX_HEIGHT = 340; + var SOURCE_MAX = 4096; // a bigger picture is scaled down to this first + var ZOOM_MAX = 8; // times the smallest zoom that fills the frame + + var canReplace = (function () { + try { + return typeof DataTransfer === 'function' && !!new DataTransfer().items && typeof File === 'function'; + } catch (e) { + return false; + } + })(); + + function el(tag, className, text) { + var node = document.createElement(tag); + if (className) { + node.className = className; + } + if (text !== undefined) { + node.textContent = text; + } + return node; + } + + // The picture, upright as the camera meant it (an follows its orientation), no bigger than SOURCE_MAX + function readPicture(file) { + return new Promise(function (resolve, reject) { + var url = URL.createObjectURL(file); + var img = new Image(); + img.onload = function () { + URL.revokeObjectURL(url); + var k = Math.min(1, SOURCE_MAX / Math.max(img.naturalWidth, img.naturalHeight)); + var canvas = document.createElement('canvas'); + canvas.width = Math.max(1, Math.round(img.naturalWidth * k)); + canvas.height = Math.max(1, Math.round(img.naturalHeight * k)); + var context = canvas.getContext('2d'); + context.imageSmoothingQuality = 'high'; + context.drawImage(img, 0, 0, canvas.width, canvas.height); + resolve(canvas); + }; + img.onerror = function () { + URL.revokeObjectURL(url); + reject(new Error('unreadable')); + }; + img.src = url; + }); + } + + function toBlob(canvas, type) { + return new Promise(function (resolve, reject) { + canvas.toBlob(function (blob) { + if (blob) { + resolve(blob); + } else { + reject(new Error('not encoded')); + } + }, type, 0.9); + }); + } + + /* + * The crop - a picture in a frame on the stage, the rest of it dimmed. + * Its state is the frame's centre on the picture (cx, cy) and how far it + * is zoomed past filling the frame (zoom), so a stage that changes size, + * or another shape, keeps what is in the frame. + */ + function Cropper(stage, frame, slider) { + var self = this; + this.stage = stage; + this.frame = frame; + this.slider = slider; + this.pointers = {}; + this.round = false; + this.shape = 'square'; + this.onchange = function () {}; + + stage.addEventListener('pointerdown', function (e) { + if (!self.source || (e.pointerType === 'mouse' && e.button !== 0)) { + return; + } + stage.setPointerCapture(e.pointerId); + self.pointers[e.pointerId] = { x: e.clientX, y: e.clientY }; + stage.classList.add('is-moving'); + e.preventDefault(); + }); + stage.addEventListener('pointermove', function (e) { + var point = self.pointers[e.pointerId]; + if (!point) { + return; + } + var ids = Object.keys(self.pointers); + if (ids.length === 1) { + self.move(e.clientX - point.x, e.clientY - point.y); + } else if (ids.length === 2) { + // A pinch zooms about the middle of the two fingers + var other = self.pointers[ids[0] === String(e.pointerId) ? ids[1] : ids[0]]; + var before = Math.hypot(point.x - other.x, point.y - other.y); + var after = Math.hypot(e.clientX - other.x, e.clientY - other.y); + var rect = stage.getBoundingClientRect(); + if (before > 0) { + self.zoomAt(self.scale * after / before, (e.clientX + other.x) / 2 - rect.left, (e.clientY + other.y) / 2 - rect.top); + } + } + point.x = e.clientX; + point.y = e.clientY; + }); + var end = function (e) { + delete self.pointers[e.pointerId]; + if (!Object.keys(self.pointers).length) { + stage.classList.remove('is-moving'); + } + }; + stage.addEventListener('pointerup', end); + stage.addEventListener('pointercancel', end); + + stage.addEventListener('wheel', function (e) { + if (!self.source) { + return; + } + e.preventDefault(); + var rect = stage.getBoundingClientRect(); + var delta = e.deltaMode === 1 ? e.deltaY * 16 : e.deltaY; + self.zoomAt(self.scale * Math.exp(-delta * 0.0015), e.clientX - rect.left, e.clientY - rect.top); + }, { passive: false }); + + stage.addEventListener('keydown', function (e) { + if (!self.source) { + return; + } + var step = e.shiftKey ? 40 : 10; + var moves = { ArrowLeft: [step, 0], ArrowRight: [-step, 0], ArrowUp: [0, step], ArrowDown: [0, -step] }; + if (moves[e.key]) { + self.move(moves[e.key][0], moves[e.key][1]); + } else if (e.key === '+' || e.key === '=') { + self.zoomAt(self.scale * 1.15); + } else if (e.key === '-' || e.key === '_') { + self.zoomAt(self.scale / 1.15); + } else if (e.key === '0') { + self.fit(); + } else { + return; + } + e.preventDefault(); + }); + + slider.addEventListener('input', function () { + self.zoomAt(self.minScale * Math.pow(ZOOM_MAX, slider.value / 1000)); + }); + + if (window.ResizeObserver) { + new ResizeObserver(function () { + self.layout(); + }).observe(stage); + } + } + + Cropper.prototype.setSource = function (source, state) { + if (this.source && this.source.parentNode) { + this.source.remove(); + } + this.source = source; + if (!source) { + return; + } + source.className = 'itflow-crop-image'; + source.setAttribute('aria-hidden', 'true'); + source.style.width = source.width + 'px'; + source.style.height = source.height + 'px'; + this.stage.insertBefore(source, this.frame); + state = state || {}; + this.zoom = state.zoom || 1; + this.cx = state.cx !== undefined ? state.cx : source.width / 2; + this.cy = state.cy !== undefined ? state.cy : source.height / 2; + this.layout(); + }; + + Cropper.prototype.state = function () { + return { zoom: this.zoom, cx: this.cx, cy: this.cy }; + }; + + // The frame for the stage's width and the shape, and the picture placed in it + Cropper.prototype.layout = function () { + var source = this.source; + var width = this.stage.clientWidth; + if (!source || !width) { + return; + } + var shape = SHAPES[this.shape] || SHAPES.square; + var ratio = shape.w ? shape.w / shape.h : source.width / source.height; + var fw = Math.min(width - MARGIN * 2, this.round ? 300 : Infinity); + var fh = fw / ratio; + if (fh > FRAME_MAX_HEIGHT) { + fh = FRAME_MAX_HEIGHT; + fw = fh * ratio; + } + this.fw = fw; + this.fh = fh; + this.fx = (width - fw) / 2; + this.fy = MARGIN; + this.stage.style.height = Math.round(fh + MARGIN * 2) + 'px'; + this.frame.style.left = this.fx + 'px'; + this.frame.style.top = this.fy + 'px'; + this.frame.style.width = fw + 'px'; + this.frame.style.height = fh + 'px'; + this.frame.classList.toggle('is-round', this.round); + + this.minScale = Math.max(fw / source.width, fh / source.height); + this.zoom = Math.min(ZOOM_MAX, Math.max(1, this.zoom || 1)); + this.scale = this.minScale * this.zoom; + var halfW = fw / 2 / this.scale; + var halfH = fh / 2 / this.scale; + this.cx = Math.min(source.width - halfW, Math.max(halfW, this.cx)); + this.cy = Math.min(source.height - halfH, Math.max(halfH, this.cy)); + var x = this.fx + fw / 2 - this.cx * this.scale; + var y = this.fy + fh / 2 - this.cy * this.scale; + source.style.transform = 'translate(' + x + 'px, ' + y + 'px) scale(' + this.scale + ')'; + this.slider.value = String(Math.round(Math.log(this.zoom) / Math.log(ZOOM_MAX) * 1000)); + this.onchange(); + }; + + Cropper.prototype.fit = function () { + if (!this.source) { + return; + } + this.zoom = 1; + this.cx = this.source.width / 2; + this.cy = this.source.height / 2; + this.layout(); + }; + + Cropper.prototype.setShape = function (shape) { + this.shape = shape; + this.zoom = 1; + this.layout(); + }; + + Cropper.prototype.move = function (dx, dy) { + this.cx -= dx / this.scale; + this.cy -= dy / this.scale; + this.layout(); + }; + + // Zoom keeping the point under (x, y) on the stage still - the frame's centre when not given + Cropper.prototype.zoomAt = function (scale, x, y) { + if (!this.source || !this.fw) { + return; + } + scale = Math.min(this.minScale * ZOOM_MAX, Math.max(this.minScale, scale)); + if (x === undefined) { + x = this.fx + this.fw / 2; + y = this.fy + this.fh / 2; + } + var left = this.fx + this.fw / 2 - this.cx * this.scale; + var top = this.fy + this.fh / 2 - this.cy * this.scale; + var px = (x - left) / this.scale; + var py = (y - top) / this.scale; + this.cx = (this.fx + this.fw / 2 - (x - px * scale)) / scale; + this.cy = (this.fy + this.fh / 2 - (y - py * scale)) / scale; + this.zoom = scale / this.minScale; + this.layout(); + }; + + Cropper.prototype.rotate = function () { + var source = this.source; + if (!source) { + return; + } + var turned = document.createElement('canvas'); + turned.width = source.height; + turned.height = source.width; + var context = turned.getContext('2d'); + context.translate(turned.width, 0); + context.rotate(Math.PI / 2); + context.drawImage(source, 0, 0); + this.setSource(turned); + }; + + // What is in the frame, the longest side no more than $max - its size, before encoding + Cropper.prototype.outputSize = function (max) { + var sw = this.fw / this.scale; + var sh = this.fh / this.scale; + var k = Math.min(1, max / Math.max(sw, sh)); + return [Math.max(1, Math.round(sw * k)), Math.max(1, Math.round(sh * k))]; + }; + + // ... as a file: a JPG for a JPG, else WebP (PNG where WebP can't be written) - { blob, width, height } + Cropper.prototype.encode = function (type, max) { + var size = this.outputSize(max); + var sw = this.fw / this.scale; + var sh = this.fh / this.scale; + var out = document.createElement('canvas'); + out.width = size[0]; + out.height = size[1]; + var context = out.getContext('2d'); + context.imageSmoothingQuality = 'high'; + if (type === 'image/jpeg') { + context.fillStyle = '#fff'; + context.fillRect(0, 0, out.width, out.height); + } + context.drawImage(this.source, this.cx - sw / 2, this.cy - sh / 2, sw, sh, 0, 0, out.width, out.height); + return toBlob(out, type).then(function (blob) { + return blob.type === type || type === 'image/jpeg' ? blob : toBlob(out, 'image/png'); + }).then(function (blob) { + return { blob: blob, width: out.width, height: out.height }; + }); + }; + + /* + * The Picture window - one, set up for the field that opens it. + */ + var win = null; + + function buildWindow() { + var modal = el('div', 'modal fade'); + modal.tabIndex = -1; + modal.setAttribute('aria-hidden', 'true'); + modal.setAttribute('aria-labelledby', 'itflowPictureTitle'); + modal.innerHTML = + ''; + document.body.appendChild(modal); + + var w = { + modal: modal, + title: modal.querySelector('[data-title]'), + pick: modal.querySelector('[data-pick]'), + now: modal.querySelector('[data-now]'), + area: modal.querySelector('[data-crop-area]'), + shapes: modal.querySelector('[data-shapes]'), + size: modal.querySelector('[data-size]'), + error: modal.querySelector('[data-error]'), + file: modal.querySelector('[data-file]'), + remove: modal.querySelector('[data-remove]'), + another: modal.querySelector('[data-another]'), + use: modal.querySelector('[data-use]'), + field: null, + picked: null + }; + w.crop = new Cropper(modal.querySelector('.itflow-crop-stage'), modal.querySelector('.itflow-crop-frame'), modal.querySelector('input[type=range]')); + w.crop.onchange = function () { + if (w.field && w.crop.source) { + var size = w.crop.outputSize(w.field.max); + w.size.textContent = size[0] + ' × ' + size[1]; + } + }; + + var choose = function () { + w.file.value = ''; + w.file.click(); + }; + w.pick.addEventListener('click', choose); + w.pick.addEventListener('keydown', function (e) { + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + choose(); + } + }); + w.another.addEventListener('click', choose); + w.file.addEventListener('change', function () { + if (w.file.files && w.file.files[0]) { + load(w, w.file.files[0]); + } + }); + + // Dropped on the window, or pasted while it's open + ['dragenter', 'dragover'].forEach(function (type) { + modal.addEventListener(type, function (e) { + e.preventDefault(); + w.pick.classList.add('is-over'); + }); + }); + modal.addEventListener('dragleave', function (e) { + if (!modal.contains(e.relatedTarget)) { + w.pick.classList.remove('is-over'); + } + }); + modal.addEventListener('drop', function (e) { + e.preventDefault(); + w.pick.classList.remove('is-over'); + var file = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0]; + if (file) { + load(w, file); + } + }); + document.addEventListener('paste', function (e) { + if (!modal.classList.contains('show') || !e.clipboardData) { + return; + } + var items = Array.prototype.slice.call(e.clipboardData.items || []); + var item = items.filter(function (i) { + return i.kind === 'file' && TYPES.test(i.type); + })[0]; + if (item) { + e.preventDefault(); + load(w, item.getAsFile()); + } + }); + + modal.querySelector('[data-rotate]').addEventListener('click', function () { + w.crop.rotate(); + }); + modal.querySelector('[data-fit]').addEventListener('click', function () { + w.crop.fit(); + }); + w.use.addEventListener('click', function () { + use(w); + }); + w.remove.addEventListener('click', function () { + remove(w); + }); + modal.addEventListener('shown.bs.modal', function () { + w.crop.layout(); + (w.crop.source ? w.crop.stage : w.pick).focus(); + }); + return w; + } + + function showError(w, text) { + w.error.textContent = text || ''; + w.error.hidden = !text; + } + + function showCrop(w, on) { + w.pick.hidden = on; + w.area.hidden = !on; + w.another.hidden = !on; + w.use.disabled = !on; + } + + // A picture picked - into the crop + function load(w, file) { + if (!TYPES.test(file.type)) { + showError(w, 'That isn\'t a JPG, PNG, GIF or WebP picture.'); + return; + } + showError(w, ''); + var field = w.field; + readPicture(file).then(function (source) { + if (w.field !== field) { + return; + } + w.picked = { name: file.name, type: file.type === 'image/jpeg' ? 'image/jpeg' : 'image/webp' }; + showCrop(w, true); + w.crop.setSource(source); + w.crop.stage.focus(); + }).catch(function () { + showError(w, 'That picture couldn\'t be read - try saving it as a JPG or PNG.'); + }); + } + + function shapeButtons(w, field) { + w.shapes.textContent = ''; + w.shapes.hidden = field.shapes.length < 2; + field.shapes.forEach(function (shape) { + var button = el('button', 'btn btn-outline-secondary', SHAPES[shape].label); + button.type = 'button'; + button.setAttribute('aria-pressed', shape === w.crop.shape ? 'true' : 'false'); + button.classList.toggle('active', shape === w.crop.shape); + button.addEventListener('click', function () { + w.crop.setShape(shape); + Array.prototype.forEach.call(w.shapes.children, function (other) { + other.classList.toggle('active', other === button); + other.setAttribute('aria-pressed', other === button ? 'true' : 'false'); + }); + }); + w.shapes.appendChild(button); + }); + } + + // The field's settings, read off it + function fieldOf(node) { + if (!node.itflowPicture) { + var shapes = String(node.getAttribute('data-crop') || 'square').split(',').map(function (shape) { + return shape.trim(); + }).filter(function (shape) { + return SHAPES[shape]; + }); + node.itflowPicture = { + node: node, + input: node.querySelector('[data-picture-input]'), + removeInput: node.querySelector('[data-picture-remove]'), + preview: node.querySelector('[data-picture-preview]'), + empty: node.querySelector('template[data-picture-empty]'), + title: node.getAttribute('data-picture-title') || 'Picture', + imgClass: node.getAttribute('data-picture-class') || 'itflow-picture-photo', + has: node.getAttribute('data-picture-has') === '1', + round: node.getAttribute('data-crop-shape') === 'circle', + shapes: shapes.length ? shapes : ['square'], + max: parseInt(node.getAttribute('data-crop-max'), 10) || 2048, + pending: null + }; + } + return node.itflowPicture; + } + + function open(node) { + var field = fieldOf(node); + win = win || buildWindow(); + var w = win; + w.field = field; + w.title.textContent = field.title; + w.modal.querySelector('.modal-dialog').classList.toggle('modal-lg', !field.round && field.shapes.indexOf('whole') !== -1); + w.now.innerHTML = field.preview.innerHTML; + w.now.classList.toggle('is-round', field.round); + w.crop.round = field.round; + showError(w, ''); + + // Opened again with a picture picked - as it was left + var pending = field.pending; + w.crop.shape = pending ? pending.shape : field.shapes[0]; + shapeButtons(w, field); + if (pending) { + w.picked = { name: pending.name, type: pending.type }; + showCrop(w, true); + w.crop.setSource(pending.source, pending.state); + } else { + w.picked = null; + w.crop.setSource(null); + showCrop(w, false); + } + w.remove.hidden = !(field.has || field.pending); + bootstrap.Modal.getOrCreateInstance(w.modal).show(); + } + + // Use this picture - its crop in the field's file input, and on the button + function use(w) { + var field = w.field; + if (!field || !w.crop.source || !w.picked) { + return; + } + w.use.disabled = true; + var picked = w.picked; + w.crop.encode(picked.type, field.max).then(function (made) { + var extension = { 'image/jpeg': '.jpg', 'image/webp': '.webp', 'image/png': '.png' }[made.blob.type] || '.png'; + var name = (picked.name.replace(/\.[^.]*$/, '') || 'picture') + extension; + var transfer = new DataTransfer(); + transfer.items.add(new File([made.blob], name, { type: made.blob.type, lastModified: Date.now() })); + field.input.files = transfer.files; + if (field.removeInput) { + field.removeInput.value = ''; + } + field.pending = { source: w.crop.source, state: w.crop.state(), shape: w.crop.shape, name: picked.name, type: picked.type }; + if (field.url) { + URL.revokeObjectURL(field.url); + } + field.url = URL.createObjectURL(made.blob); + var img = el('img', field.imgClass); + img.alt = ''; + img.src = field.url; + field.preview.replaceChildren(img); + field.node.classList.add('is-changed'); + field.input.dispatchEvent(new Event('change', { bubbles: true })); + bootstrap.Modal.getOrCreateInstance(w.modal).hide(); + }).catch(function () { + showError(w, 'That crop couldn\'t be saved - try another picture.'); + }).finally(function () { + w.use.disabled = !w.crop.source; + }); + } + + // Remove - no new picture, and the one there was taken off when the form is saved + function remove(w) { + var field = w.field; + if (!field) { + return; + } + field.input.value = ''; + field.pending = null; + if (field.removeInput && field.has) { + field.removeInput.value = '1'; + } + field.has = false; + field.preview.replaceChildren(field.empty.content.cloneNode(true)); + field.node.classList.add('is-changed'); + field.input.dispatchEvent(new Event('change', { bubbles: true })); + bootstrap.Modal.getOrCreateInstance(w.modal).hide(); + } + + document.addEventListener('click', function (e) { + var button = e.target.closest ? e.target.closest('[data-picture-open]') : null; + if (!button) { + return; + } + var node = button.closest('[data-picture-field]'); + if (!node) { + return; + } + e.preventDefault(); + if (!canReplace || !window.bootstrap) { + // Without the window - the file as picked + fieldOf(node).input.click(); + return; + } + open(node); + }); + + // A person's initials follow their name as it is typed - on the button, and for when the picture is removed + document.addEventListener('input', function (e) { + var input = e.target; + if (!input || !input.form || !input.name) { + return; + } + input.form.querySelectorAll('[data-picture-field][data-picture-name]').forEach(function (node) { + if (node.getAttribute('data-picture-name') !== input.name) { + return; + } + // The first letters of the first two words, as personInitials() makes them (functions/format.php) + var text = input.value.trim().split(/\s+/).filter(Boolean).slice(0, 2).map(function (word) { + return word.charAt(0).toUpperCase(); + }).join('') || '?'; + [node.querySelector('[data-picture-preview]'), node.querySelector('template[data-picture-empty]').content].forEach(function (holder) { + var initials = holder && holder.querySelector('span.itflow-contact-avatar'); + if (initials) { + initials.textContent = text; + } + }); + }); + }); + + // Without the window, a picked file still shows on the button + document.addEventListener('change', function (e) { + if (canReplace && window.bootstrap) { + return; + } + var input = e.target; + var node = input && input.matches && input.matches('[data-picture-input]') ? input.closest('[data-picture-field]') : null; + if (node && input.files && input.files[0]) { + var field = fieldOf(node); + var img = el('img', field.imgClass); + img.alt = ''; + img.src = URL.createObjectURL(input.files[0]); + field.preview.replaceChildren(img); + } + }); +})();