From 4dd7f7e258d382dbf73ff5beb1f43e03476b36cf Mon Sep 17 00:00:00 2001
From: Jake Vanderwerf <get@jakevanderwerf.ca>
Date: Tue, 10 Feb 2026 21:08:23 +0000
Subject: [PATCH] =Taxonomy selector fixes in Form.php and TaxonomySelector.js

---
 assets/js/concise/CRUD.js |  169 ++++++++++++++++++++++++++++++++++++++++++++++++++++----
 1 files changed, 156 insertions(+), 13 deletions(-)

diff --git a/assets/js/concise/CRUD.js b/assets/js/concise/CRUD.js
index 8d92f41..8c29ab2 100644
--- a/assets/js/concise/CRUD.js
+++ b/assets/js/concise/CRUD.js
@@ -371,6 +371,12 @@
 							if (name === 'date') {
 								this.handleCustomDateSelection()
 							}
+							if (['edit','bulkEdit','create'].includes(name)) {
+								//handle escapes (not form submits)
+								if (window.debouncer.timeouts.has(`save-${this.content}`)) {
+									this.scheduleSave(0);
+								}
+							}
 							break;
 						case 'modal-open':
 
@@ -396,7 +402,7 @@
 					keyPath: 'id',
 					endpoint: this.endpoint??'content',	//for taxonomy stores
 					headers: {
-						'action_nonce': window.auth.getNonce('dash'),
+						'X-Action-Nonce': window.auth.getNonce('dash'),
 					},
 					indexes: [
 						{name: 'id', keyPath: 'id'},
@@ -476,16 +482,29 @@
 		// 	}
 		// });
 
+		if (window.jvbUploads) {
+			window.jvbUploads.subscribe((event, data) => {
+				if (event === 'groups_uploaded' && data.content === this.content) {
+					this.handleGroupsUploaded(data);
+				}
+			});
+		}
+
 		this.queue.subscribe((event, data) => {
 			if (['image_upload', 'video_upload', 'document_upload'].includes(data.type)
 				&& event === 'operation-status'
 				&& data.status === 'completed') {
 				this.store.clearCache();
 			}
+			console.log('CRUD.js queue subscription');
+			console.log(event, data);
 			if (event === 'operation-status'
 				&& data.status === 'completed'
 				&& data.endpoint === 'uploads/groups') {
-
+				console.log('Grouped Uploads completed');
+				if (data.result && data.result.group_mappings) {
+					this.handleGroupMappings(data.result.group_mappings);
+				}
 				console.log('Cleared local cache. Refresh to see changes');
 				this.store.clearCache();
 			}
@@ -502,9 +521,7 @@
 				}
 
 				// Get successfully processed post IDs
-				const successfulIds = Object.keys(data.result.posts).filter(id => {
-					return data.result.posts[id]?.success === true;
-				});
+				const successfulIds = Object.keys(data.result.posts);
 
 				if (successfulIds.length === 0) {
 					return;
@@ -628,9 +645,7 @@
 		} else if (modal.classList.contains('create')) {
 			title = `Creating your new ${this.singular}`;
 		}
-		this.cancelBackup();
-		this.handleBackup().then(()=>{});
-		this.savePosts(title,false).then(()=>{});
+		this.scheduleSave(0);
 	}
 	handleChange(e) {
 		// Early bailout - target must be in an item or be a filter
@@ -733,11 +748,13 @@
 		if (!item) return;
 		item.dataset.itemId.split(',').forEach(itemId => {
 			let field = this.forms.getField(e.target);
+			if (['repeater', 'tag-list'].includes(field.dataset.fieldType)) {
+				return;
+			}
 			let name = field.dataset.field;
 			let value = this.forms.getFieldValue(e.target);
 			this.updateItem(itemId, name, value);
 		});
-		this.savePosts('', true).then(()=>{});
 	}
 	updateItem(itemId, name, value) {
 		if (!this.changes.has(itemId)) {
@@ -746,6 +763,10 @@
 		this.changes.get(itemId)[name] = value;
 
 		this.scheduleBackup();
+		//Only send actual itemIds to server. If this is a recently uploaded item, just store changes for now
+		if (typeof itemId === 'number' || !itemId.includes('group')) {
+			this.scheduleSave();
+		}
 	}
 	scheduleBackup() {
 		window.debouncer.schedule(
@@ -758,13 +779,39 @@
 			2000
 		);
 	}
-
 	cancelBackup() {
 		window.debouncer.cancel(`changes-${this.content}`);
 	}
 	async handleBackup() {
-		await this.changesStore.saveMany(this.changes);
+		const changesArray = Array.from(this.changes.values());
 		this.changes.clear();
+
+		const ids = changesArray.map(c => c.id);
+		const existing = await Promise.all(
+			ids.map(id => this.changesStore.get(id))
+		);
+
+		const changes = changesArray.map((change, i) =>
+			existing[i] ? window.deepMerge(existing[i], change) : change
+		);
+
+		await this.changesStore.saveMany(changes);
+	}
+
+	scheduleSave(delay = 10000) {
+		window.debouncer.schedule(
+			`save-${this.content}`,
+			async () => {
+				// Ensure latest changes are in IndexedDB
+				if (this.changes.size > 0) {
+					this.cancelBackup();
+					await this.handleBackup();
+				}
+
+				await this.savePosts('', false);
+			},
+			delay
+		);
 	}
 	handleFilterChange(target) {
 		let filter = target.dataset.filter;
@@ -1139,7 +1186,7 @@
 			await this.handleBackup();
 		}
 		const changes = await this.changesStore.getAll();
-
+		console.log('Saving Changes: ', changes);
 		if (changes.length === 0) return;
 
 		if (title === '') {
@@ -1168,7 +1215,7 @@
 		let operation = {
 			endpoint: this.endpoint,
 			headers: {
-				'action_nonce': window.auth.getNonce('dash'),
+				'X-Action-Nonce': window.auth.getNonce('dash'),
 			},
 			data: {
 				posts: allChanges,
@@ -1367,6 +1414,102 @@
 		});
 	}
 	/***************************************************************
+	 UPLOAD GROUP SUPPORT
+	 Handles:
+	  	- immediate UI feedback once the uploaded groups are sent to server
+	***************************************************************/
+	handleGroupsUploaded(data) {
+		const { posts, fieldId } = data;
+		let uploader = window.jvbUploads;
+		let field = uploader.fields.get(fieldId);
+
+
+		console.log(posts);
+		console.log(field);
+
+		let added = [];
+		posts.forEach(post => {
+			const placeholderPost = {
+				id: post.groupId,
+				title: post.fields.post_title || `New ${this.singular}`,
+				status: 'draft',
+				date: new Date().toISOString(),
+				modified: new Date().toISOString(),
+				thumbnail: null,
+				icon: this.content,
+				taxonomies: {},
+				fields: post.fields,
+				images: {},
+			};
+
+			post.images.forEach((uploadId, index) => {
+				let id = uploadId['upload_id'];
+				if (index === 0) {
+					placeholderPost.fields['post_thumbnail'] = uploadId;
+				}
+				let upload = uploader.stores.uploads.get(id);
+				if (upload) {
+					placeholderPost.images[id] = {
+						'image-alt-text': '',
+						'image-caption': '',
+						'image-title': upload.fields.originalName,
+						medium: uploader.createPreviewUrl(uploader.formatFile(upload))
+					};
+				}
+
+			});
+			//
+			// // Add to store (won't persist since it's a fake ID)
+			// this.store.data.set(post.groupId, placeholderPost);
+			//
+			//
+			// // Render immediately
+			// let element;
+			// switch (this.view) {
+			// 	case 'grid':
+			// 		element = this.renderGridItem(placeholderPost);
+			// 		this.ui.grid.prepend(element);
+			// 		break;
+			// 	case 'list':
+			// 		element = this.renderListItem(placeholderPost);
+			// 		this.ui.grid.prepend(element);
+			// 		break;
+			// 	case 'table':
+			// 		element = this.renderTableItem(placeholderPost);
+			// 		if (this.ui.table.body) {
+			// 			this.ui.table.body.prepend(element);
+			// 		}
+			// 		break;
+			// }
+			// element.classList.add('uploading');
+			added.push(placeholderPost);
+		});
+		this.store.saveMany(added).then(() => this.render());
+
+
+		this.a11y.announce(`${posts.length} ${posts.length === 1 ? this.singular : this.plural} created. Waiting for server confirmation...`);
+	}
+
+	handleGroupMappings(mappings) {
+		console.log('[CRUD] Applying group mappings:', mappings);
+		// mappings = { "group_abc123": 456, "group_def456": 789 }
+
+		for (const [groupId, postId] of Object.entries(mappings)) {
+			// Get any pending changes for this temp item
+			let changes = {};
+			if (this.changes.has(groupId)) {
+				changes = this.changes.get(groupId);
+				this.changes.delete(groupId);
+			}
+			let storedChanges = this.changesStore.get(groupId)??{};
+			if (changes.size > 0 || storedChanges.size > 0) {
+				changes = window.deepMerge(storedChanges, changes);
+				this.changes.set(postId, changes);
+				this.scheduleBackup();
+			}
+		}
+	}
+	/***************************************************************
 	 UTILITY
 	***************************************************************/
 	shouldRemoveItemUI(newStatus) {

--
Gitblit v1.10.0