Event will not delete (Google Scripts with Calendar API) - javascript

I am creating a script that takes an existing Google Calendar and matches another calendar with its information. For example, if an event is added in the existing calendar, the other calendar will add an event. If an event date is altered in the existing calendar, the other calendar will delete the event that previously matched and create one to match the altered event. I am having trouble with deleting the events.
I am unsure why I get the error "Failed with error listed_event.deleteEvent is not a function". I have tried for a few days and still have no clue what the issue could be in my code. The line in question is bolded with asterisks, although I have suspicions the issues lie elsewhere.
Any help would be greatly appreciated.
function CleaningCalendar() {
const CleaningId = 'primary';
// Add query parameters in optionalArgs
const HospitableId = 's4h3vvv6r47c3uqiknjhr4hrprgjua5g#import.calendar.google.com';
const optionalArgs = {
timeMin: (new Date()).toISOString(),
showDeleted: false,
singleEvents: true,
maxResults: 300,
orderBy: 'startTime'
// use other optional query parameter here as needed.
};
try {
// call Events.list method to list the calendar events using calendarId optional query parameter
var HospitableEvents = Calendar.Events.list(HospitableId, optionalArgs).items;
var CleaningEvents = Calendar.Events.list(CleaningId, optionalArgs).items;
const property_list = ["BREITHAUPT", "SPRING", "ELLIS 1", "ELLIS 2", "ELLIS 3", "ELLIS 5", "UNION 1", "UNION 2", "UNION 3"]
if (HospitableEvents.length === 0) {
Logger.log('No upcoming events found');
return;
}
for (let i = 0; i < HospitableEvents.length; i++){
event = HospitableEvents[i];
const start_date = event.start.dateTime;
//The fourth semi-colon in the Hospitable Calendar event description pertains to the property name
let first_colon_loc = event.description.indexOf(":");
let second_colon_loc = event.description.slice(first_colon_loc + 1).indexOf(":");
let third_colon_loc = event.description.slice(first_colon_loc + second_colon_loc + 2).indexOf(":");
let fourth_colon_loc = event.description.slice(first_colon_loc + second_colon_loc + third_colon_loc + 3).indexOf(":");
let property_colon_loc = first_colon_loc + second_colon_loc + third_colon_loc + fourth_colon_loc + 5;
let end_of_property_name = event.description.slice(property_colon_loc).indexOf("\n");
let property_name = event.description.slice(property_colon_loc, property_colon_loc + end_of_property_name);
var cleaning_event = {
'summary': property_name,
'location': '',
'description': '',
'start': {
'dateTime': start_date,
'timeZone': 'America/New_York'
},
'end': {
'dateTime': start_date,
'timeZone': 'America/New_York'
},
'recurrence': [
'RRULE:FREQ=DAILY;COUNT=1'
],
'attendees': [''],
'reminders': {
'useDefault': false,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10}
]
}
};
if (property_list.includes(property_name)){
count = 0
for (let i = 0; i < CleaningEvents.length; i++){
if ((property_name == CleaningEvents[i].summary) && (event.start.dateTime == CleaningEvents[i].start.dateTime)){
count = count + 1;
continue;
}}
if (count == 0){
created_event = CalendarApp.getDefaultCalendar().createEvent(property_name,
new Date(start_date),
new Date(start_date));
}}
else{
Logger.log(HospitableEvents[i]);
Logger.log("The above is not valid");
}
}
for (let k = 0; k < CleaningEvents.length; k++){
listed_event = CleaningEvents[k];
var count = 0;
for (let j = 0; j < HospitableEvents.length; j++){
event = HospitableEvents[j];
const start_date = event.start.dateTime;
//The fourth semi-colon in the Hospitable Calendar event description pertains to the property name
let first_colon_loc = event.description.indexOf(":");
let second_colon_loc = event.description.slice(first_colon_loc + 1).indexOf(":");
let third_colon_loc = event.description.slice(first_colon_loc + second_colon_loc + 2).indexOf(":");
let fourth_colon_loc = event.description.slice(first_colon_loc + second_colon_loc + third_colon_loc + 3).indexOf(":");
let property_colon_loc = first_colon_loc + second_colon_loc + third_colon_loc + fourth_colon_loc + 5;
let end_of_property_name = event.description.slice(property_colon_loc).indexOf("\n");
let hospitable_name = event.description.slice(property_colon_loc, property_colon_loc + end_of_property_name);
if ((listed_event.summary == hospitable_name) && (listed_event.start.dateTime == event.start.dateTime)){
count = count + 1;
continue;
}
}
if (count == 0){
**listed_event.deleteEvent();**
Logger.log(listed_event);
}}
}
catch (err) {
// TODO (developer) - Handle exception from Calendar API
Logger.log('Failed with error %s', err.message);
}
}

Related

Pass value from .gs to htmlService

I'm quite new to GAS & JS so please bear with me.
Problem 1 solved by #Cooper
I'm trying to pass the pdf link that gets generated by pdf.gs to an href in PDFlinkHTML.html.
I initially just had a Html output in the generatePDF() function and used href:"${pdf.getURl()}" but this is not viable anymore since the htmlService uses a lot of CSS, jQuery and needs a separate File.
Problem 2
I also have a loading spinner (essentially just a fixed div) in my htmlService which i want to hide (with either pure JS or jQuery) as soon as the PDF is generated and the link has been passed on to the href.
(My current "workaround" is just displaying the loading spinner in a separate ModalDialog at the start of the function & the PDFlinkHTML.html the at the end. Looks fine but feels cheap.)
I'd really appreciate some help & input.
Regards
pdf.gs
function createPDF(ssId, sheet, pdfName, lr) {
const fr = 0, fc = 0, lc = 9;
const url = "https://docs.google.com/spreadsheets/d/" + ssId + "/export" +
"?format=pdf&" +
"size=7&" +
"fzr=true&" +
"portrait=true&" +
"fitw=true&" +
"gridlines=false&" +
"printtitle=false&" +
"top_margin=0.5&" +
"bottom_margin=0.25&" +
"left_margin=0.5&" +
"right_margin=0.5&" +
"sheetnames=false&" +
"pagenum=UNDEFINED&" +
"attachment=true&" +
"gid=" + sheet.getSheetId() + '&' +
"r1=" + fr + "&c1=" + fc + "&r2=" + lr + "&c2=" + lc;
const params = { method: "GET", headers: { "authorization": "Bearer " + ScriptApp.getOAuthToken() } };
const blob = UrlFetchApp.fetch(url, params).getBlob().setName(pdfName + '.pdf');
const destinationFolder = DriveApp.getFolderById('1BI_cD628wyqHWgagwmkxYBhvHo1irrQY'); // PDF destination folder
const pdfFile = destinationFolder.createFile(blob);
return pdfFile;
}
function generatePDF() {
var lock = LockService.getScriptLock();
try {
lock.waitLock(20000); // Attempts to acquire the lock, timing out with an exception after 20 seconds
} catch (e) {
Logger.log('Could not obtain lock after 20 seconds.');
return Browser.msgBox("Server beschäftigt bitte versuche es in einem Moment erneut.");
};
var html = HtmlService.createTemplateFromFile('PDFloadingHTML')
.evaluate()
.setWidth(400)
.setHeight(250);
ui.showModalDialog(html, "‎");
const templateSheet = SpreadsheetApp.openById('1entOMh9MqliPJjQm7W9loDYeghJEnqTCqcaXDoU1FCc');
const destinationSS = templateSheet.copy('Inventory');
const destinationSheet = destinationSS.getSheets()[0];
const destinationID = destinationSS.getId();
const f2 = iSheet.getRange(2, 6).getValue();
const timestamp = Utilities.formatDate(new Date(), "GMT+2", "yyyy/MM/dd HH:mm");
const pdfname = "" + f2 + " " + timestamp + ""; // PDF output name
// PDF generation & cleanup.
sortedArr = sortRange();
var letter = "";
var counter = 0;
var i = 5;
while (!destinationSheet.getRange(i, 1).isBlank()) {
if (destinationSheet.getRange(i, 1).getValue().toString().trim().length == 1) {
letter = destinationSheet.getRange(i, 1).getValue().toString().trim().toLowerCase();
} else if (String(sortedArr[counter]).trim().toLowerCase().startsWith(letter) && String(sortedArr[counter]).trim().toLowerCase() != "undefined") {
destinationSheet.getRange(i, 1).setValue(sortedArr[counter][0]);
destinationSheet.getRange(i, 2).setValue(sortedArr[counter][1]);
counter += 1;
for (var j = counter; j < sortedArr.length; j++) {
if (String(sortedArr[counter]).trim().toLowerCase().startsWith(letter)) {
destinationSheet.insertRowAfter(i);
if (letter == "z") {
destinationSheet.getRange(i, 1, 1, 9).copyTo(destinationSheet.getRange(i + 1, 1, 1, 2), { formatOnly: true });
} else {
destinationSheet.getRange(i, 1, 1, 2).copyTo(destinationSheet.getRange(i + 1, 1, 1, 2), { formatOnly: true });
};
i += 1;
destinationSheet.getRange(i, 1).setValue(sortedArr[counter][0]);
destinationSheet.getRange(i, 2).setValue(sortedArr[counter][1])
counter += 1;
};
};
} else {
destinationSheet.getRange(i, 1).setValue("-");
destinationSheet.getRange(i, 2).setValue("-");
};
i += 1;
};
SpreadsheetApp.flush();
destinationSheet.autoResizeColumns(2, 1);
Utilities.sleep(500); // Using to offset any potential latency in creating .pdf
const pdf = createPDF(destinationID, destinationSheet, pdfname, destinationSheet.getLastRow());
DriveApp.getFileById(destinationID).setTrashed(true);
var html = HtmlService.createTemplateFromFile('PDFlinkHTML')
.evaluate()
.setWidth(400)
.setHeight(250);
ui.showModalDialog(html, "‎");
return;
}
function sortRange() {
arr = iSheet.getRange(`D6:E${iSheet.getLastRow()}`).getDisplayValues();
arr.sort(function (x, y) {
var xp = x[0];
var yp = y[0];
return xp == yp ? 0 : xp < yp ? -1 : 1;
});
return arr;
}
How about something like this:
var temp = HtmlService.createTemplateFromFile('PDFlinkHTML')
temp.pdflink = pdflinkData;
var html = temp.evaluate().setWidth(400).setHeight(250);
ui.showModalDialog(html, "‎");
href= <?= pdflink ?>

Is it possible to create a new function then assign it to a trigger when you click a button or use an existing function?

At the moment, I manually create code then manually ask the user to set the trigger for the said function in order for the said user to receive a task and update task.
Heres an example of my coding:
User's Function
function Person1Variables () {
taskedPerson = assignedPerson.filter(x => x == "Person1 (assigned by Somebody)").length
taskReceiver = "Person1 (assigned by Somebody)"
taskReceived = "Person1 (Sent)"
functionCaller = "Person1 "
myTask = "My Tasks"
}
function taskSendPerson1() {
Person1Variables()
if (taskedPerson + 1 > 1){taskSending(taskTitle(myTask)); console.log("Snag")}
}
function updateTaskPerson1() {
Person1Variables()
taskComplete(taskTitle(myTask));
}
Task Creation and Update
function taskTitle(titleTasksList) {
if (typeof titleTasksList === 'undefined') { titleTasksList = 'default'; }
var rezultId = 0;
var response = Tasks.Tasklists.list();
var taskLists = response.items;
if (taskLists && taskLists.length > 0) {
for (var i = 0; i < taskLists.length; i++) {
var taskList = taskLists[i];
if (titleTasksList == 'default') {
rezultId = taskList.id; //return first item
break;
} else {
Logger.log('%s (%s)', taskList.title, taskList.id);
if (titleTasksList == taskList.title) {
rezultId = taskList.id;
break;
}
}
}
} else {
Logger.log('No task lists found.');
}
return rezultId;
}
function taskSending(taskListId) {
// Task details with title and notes for inserting new task
var currentResult = 1
var nextResult = 1
for (var resultsFound = 0; resultsFound < taskedPerson; resultsFound++){
console.log("pong")
var searchEngine = "Assigned Person"
var searchRange = sheet.getRange(nextResult,(lastColumn[0].indexOf(searchEngine) + 1),
sheet.getLastRow(), 1)
var searchRangeValues= searchRange.getValues()
currentResult = searchRangeValues.map(String).indexOf(taskReceiver) + nextResult
var resultTitle = responseNumber[currentResult -1]
var resultNote = typeSupport[currentResult - 1] + " = " + typeRequest[currentResult - 1]
let task = {
title: String(resultTitle),
notes: resultNote,
};
// Call insert method with taskDetails and taskListId to insert Task to specified tasklist.
console.log(task)
console.log(taskListId)
task = Tasks.Tasks.insert(task, taskListId);
// Print the Task ID of created task.
Logger.log('Task with ID "%s" was created.', task.id);
sheet.getRange(currentResult,2).setValue (taskReceived)
nextResult = currentResult + 1
console.log(nextResult + " " + "processed")
}
}
function newTask(taskListId) {
// Task details with title and notes for inserting new task
var allResults = [];
var allTitles = [];
for (var j = 0; j < itemResponses.length + 1; j++) {
var itemResponse = itemResponses[j];
for (var g = 0; g < 30; g++){ try {allResults [g] = String(itemResponses[g].getResponse()); allTitles [g] = itemResponses[g].getItem().getTitle();var lastResponse = g} catch(err) {}}
}
console.log("PING")
var refNumber = new Date().getFullYear().toString().substr(-2) + String(("00000000" + (formResponses.length))).substr(String(("00000000" + (formResponses.length))).length - 8);
let task = {
title: refNumber,
notes: allTitles [3] + " = " + allResults [3],
};
try {
// Call insert method with taskDetails and taskListId to insert Task to specified tasklist.
task = Tasks.Tasks.insert(task, taskListId);
// Print the Task ID of created task.
Logger.log('Task with ID "%s" was created.', task.id);
} catch (err) {
// TODO (developer) - Handle exception from Tasks.insert() of Task API
Logger.log('Failed with an error %s', err.message);
}
}
function taskComplete(taskListId) {
var optionalArgs = {
maxResults: 100,
showHidden: true
};
var tasks = Tasks.Tasks.list(taskListId, optionalArgs);
if (tasks.items) {
for (var i = 0; i < tasks.items.length; i++) {
var task = tasks.items[i];
for (var x = 0; x < responseNumber.length; x++){
if (responseNumber[x] == task.title){sheet.getRange(x + 1,lastColumn[0].indexOf("Status")+1).setValue(task.status); }
}
}
var dataFound = 0
//Tasks.Tasks.remove(taskListId,tasks.items[dataFound].id)
for (var x = 0; x < responseNumber.length; x++)
{try{if (tasks.items[dataFound].status == "completed" && (responseNumber.map(String).indexOf(String(tasks.items[dataFound].title))) > 1){Tasks.Tasks.remove(taskListId,tasks.items[dataFound].id); sheet.getRange(responseNumber.map(String).indexOf(String(tasks.items[dataFound].title)) + 1,lastColumn[0].indexOf("Assigned Person")+1).setValue(functionCaller)}; dataFound++} catch(err){}}
}
}
My plan was to create a button that can detect if that user has or has not created a function. If the user does not have dedicated function, then this button will create a function and assigned the trigger.
You don't need another function. The typical way to handle per user data is to store it in propertiesService and link it to triggerUid of the installed trigger.
Related:
Best way to create and manage someone's triggers (GAS)
Can the function called by ScriptApp.newTrigger identify the triggerID?
Is it possible to create a function on the fly and create triggers though? Maybe as a two step process through google-apps-script-api, but it's unnecessarily complicated for your case.

Updating multiple Firebase nodes from multiple Google Calendar inserts with a callback functions inside a loop

this is my first post on Stack, and I am new to creating web apps. I've done some searching and I think my issue has to do closures/forEach/let...
Found here - JavaScript closure inside loops – simple practical example
But I am struggling on incorporating that into my app and need some help please.
I am using Firebase Realtime DB where I am pushing some data and pulling the uID of that push, then I use that same data to create a Google Calendar entry. I then retrieve that eventID from Calendar and then update the corresponding database node. So this works when I create a single entry at a time. What I then did, was I added the option to send multiple entries at once (this depends on a datetime-local input). So I have put these multiple datetimes into an array and they send correctly to Firebase and to Calendar, but where my bug is, is that only the last Calendar eventID is being updated in Firebase. It seems that the for loop over the array of date runs through before calendar can get the eventID and update Firebase. This was seen due to only my last date in the array having the associated calendar eventID. So yeah I think the issue is the global variable newPushId, but I am not sure at the moment how to fix it. All this is new and struggling to understand.
Sorry it's long, I would rather leave my code in there in case someone has any tips. If people would prefer me to shorten it, I will. Thank you in advance for the assistance.
Here's my main function that runs on submit.
function sendInstantBook() {
// checkBookForm listed in services
if (checkInstantBookForm()) {
// Get variables from the form.
var address = $('#instant-book-change-address').val();
var instructor = $("#instant-book-instructor").children(":selected").attr("id");
var transmission = $("#instant-book-transmission").children(":selected").attr("id");
var duration = $("#instant-book-duration").children(":selected").attr("id");
var start0 = $('#instant-book-start0').val();
var multipleLessons;
if (getLessonTimes() !== false) {
multipleLessons = getLessonTimes();
}
multipleLessons = multipleLessons.split(',');
// var recurring, interval, frequency, count;
// if ($('#recurring-checkbox').is(":checked")) {
// recurring = true;
// interval = $('#instant-recurring-interval').val();
// frequency = $("#instant-recurring-freq").children(":selected").attr("id");
// count = $('#instant-recurring-count').val();
// } else {
// recurring = false;
// interval = false;
// frequency = false;
// count = false;
// }
var sortAsc = new Date(start0).getTime();
// var sortDes = 9999999999999 - sortAsc;
var date0 = start0.split('T')[0];
var timeStart0 = start0.split('T')[1];
var timeFinish0 = addTimes(timeStart0, duration);
var paymentType = $('input[name="instantPayment"]:checked').val();
var paid = $('input[name="instantPaymentCheck"]:checked').val();
var paymentNumber = getPaymentNumber(paymentType);
var paymentDate = getPaymentDate(paid, date0);
var email = adminStudentDetails.email;
var phoneNumber = adminStudentDetails.phoneNumber;
phoneNumber = phoneNumber.replace(/\s/g, "");
var firstName = adminStudentDetails.firstName;
var lastName = adminStudentDetails.lastName;
var studentName = firstName + ' ' + lastName;
var amount = getAmount(duration);
var tracking = getTracking(duration);
if (multipleLessons.length == 1) {
// Create JSON object With the request's details and push to server
var data = {
"address" : address,
"amount" : amount,
"booked" : true,
"calID" : false,
"cancelled" : false,
"date" : date0,
"dateSortAsc" : sortAsc,
// "dateSortDes" : sortDes,
"duration" : duration,
"email" : email,
"firstName" : firstName,
"instructor" : instructor,
"lastName" : lastName,
// "newStudent" : newStudent,
"paymentDate" : paymentDate,
"paymentType" : paymentType,
"paymentNumber" : paymentNumber,
"phoneNumber" : phoneNumber,
"prepaid" : paid,
// "recurring" : recurring,
"studentName": studentName,
"time": timeStart0 + ' - ' + timeFinish0,
"tracking": tracking,
"transmission" : transmission,
"type" : "Lesson",
};
// var recurringData = {
// "interval" : interval,
// "frequency" : frequency,
// "count" : count,
// };
// push data to firebase
dbrefLessons.push(data).then((snap) => {
newPushUid = snap.key;
// this is a global variable
});
insertCalEvent(data, updCalIdCallback);
showSnackbar();
}
else if (multipleLessons.length > 1) {
for (var i = 0; i < multipleLessons.length; i++) {
eachDate = multipleLessons[i].split('T')[0];
eachDateSortAsc = new Date(i).getTime();
eachStart = multipleLessons[i].split('T')[1];
eachFinish = addTimes(eachStart, duration);
// Create JSON object With the request's details and push to server
var dataMultiple = {
"address" : address,
"amount" : amount,
"booked" : true,
"calID" : false,
"cancelled" : false,
"date" : eachDate,
"dateSortAsc" : eachDateSortAsc,
// "dateSortDes" : sortDes,
"duration" : duration,
"email" : email,
"firstName" : firstName,
"instructor" : instructor,
"lastName" : lastName,
// "newStudent" : newStudent,
"paymentDate" : paymentDate,
"paymentType" : paymentType,
"paymentNumber" : paymentNumber,
"phoneNumber" : phoneNumber,
"prepaid" : paid,
"studentName": studentName,
"time": eachStart + ' - ' + eachFinish,
"tracking": tracking,
"transmission" : transmission,
"type" : "Lesson",
};
// push data to firebase
dbrefLessons.push(dataMultiple).then((snap) => {
newPushUid = snap.key;
});
// push to calendar
insertCalEvent(dataMultiple, updCalIdCallback);
}
}
showSnackbar();
}
}
And the calendar insert code.
function insertCalEvent(linfo, updCalIdCallback) {
// function insertCalEvent(linfo, linfoRecur, updCalIdCallback) {
// THIS WILL NEED TO CHANGE TO LOGGED IN USER RATHER THAN STUDENT DETAILS
// or change it over to organizer
var loggedInFirstName = studentDetails.firstName;
var loggedInLastName = studentDetails.lastName;
var today = new Date().toISOString();
var todayDate = today.split('T')[0];
var todayTime = today.split('T')[1].split('.')[0];
// var interval = linfoRecur.interval;
// var frequency = linfoRecur.frequency;
// var count = linfoRecur.count;
// if (interval == false) {
// interval = 0;
// frequency = 0;
// count = 0;
// }
var address = linfo.address;
var amount = linfo.amount;
var cancelled = linfo.cancelled;
var date = linfo.date;
var duration = linfo.duration;
var email = linfo.email;
var firstName = linfo.firstName;
var lastName = linfo.lastName;
var location;
var newStudent;
var instructor = linfo.instructor;
var paymentType = linfo.paymentType;
var paid = linfo.prepaid;
var transmission = linfo.transmission;
var type = linfo.type;
var phoneNumber = linfo.phoneNumber;
var time = linfo.time;
var time1 = time.split(' - ')[0];
var time2 = time.split(' - ')[1];
if (linfo.location == undefined) {
} else {
location = linfo.location;
}
if (linfo.newStudent == true){
newStudent = "NEW ";
} else if (linfo.newStudent == undefined || linfo.newStudent == false) {
newStudent = "";
}
if (paid == "Yes") {
paid = "PD ";
} else {
paid = "Owes ";
}
if (paymentType == "Instructor") {
paymentType = "Instructor ";
} else if (paymentType == "Office") {
paymentType = "Office ";
} else if (paymentType == "Pack") {
paymentType = "(input pack) ";
}
var event = {
'summary': paid + paymentType + amount + ' - ' + newStudent + transmission + ' ' + type + ' - ' + firstName + ' ' + lastName + ' - ' + address + ' - ' + phoneNumber,
'location': address,
'description': 'Lesson generated by XLR8 app. \nInstructor - ' + instructor + '\nBooked by ' + loggedInFirstName + ' ' + loggedInLastName + ' at ' + todayDate + ' - ' + todayTime + '.\nStudent email - ' + email,
'start': {
'dateTime': date + 'T' + time1 + ':00+10:00',
'timeZone': 'Australia/Brisbane'
},
'end': {
'dateTime': date + 'T' + time2 + ':00+10:00',
'timeZone': 'Australia/Brisbane'
},
// 'attendees': [
// {'email': 'simon.curran.89#gmail.com'},
// ],
'reminders': {
'useDefault': false,
'overrides': [
{'method': 'popup', 'minutes': 30}
]
},
// "recurrence": [
// "RRULE:FREQ="+ frequency + ";COUNT=" + count + ";INTERVAL=" + interval + ";"
// ],
// 'originalStartTime': date + 'T' + time1 + ':00+10:00',
// 'recurringEventId': 'recurringEventId',
// 'colourId': 10,
};
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.insert({
"calendarId": "primary",
"resource": event
}, function(err, event) {
if (err) {
console.log("There was an error contacting the Calendar service: " + err);
return;
} else {
console.log("Event created: %s", event.htmlLink);
}
});
request.execute(function(resp) {
// console.log(resp);
// var calID = resp.id;
return updCalIdCallback(resp.id);
});
});
}
And the callback function:
function updCalIdCallback(calID) {
var updatedCalID = {
"calID" : calID,
};
dbrefLessons.child(newPushUid).update(updatedCalID);
console.log(calID);
console.log(newPushUid);
newPushUid = '';
}

ExtendScript - Use Arrow Keys to shift focus from searchbox to list

I have the below script:
picked = myItems (['item 1', 'item 2', 'item 3', 'item 4', 'new item 1', 'new item 2']);
function myItems (templates) {
var w = new Window ('dialog {text: "Item List", alignChildren: "fill"}');
var entry = w.add ('edittext {active: true}')
entry.graphics.font= ScriptUI.newFont ("Arial", "Bold", 12);
var list = w.add ('listbox', [0, 0, 200, 100], templates);
list.selection = 0;
list.graphics.font= ScriptUI.newFont ("Arial", "Italic", 14);
entry.onChanging = function ()
{
var temp = entry.text,
tempArray = [];
for (var i = 0; i < templates.length; i++)
if (templates[i].toLowerCase().indexOf (temp) == 0)
tempArray.push (templates[i]);
else if (templates[i].toUpperCase().indexOf (temp) == 0)
tempArray.push (templates[i]);
if (tempArray.length > 0)
{
tempList = w.add ("listbox", list.bounds, tempArray, {scrolling: true});
tempList.graphics.font= ScriptUI.newFont ("Times New Roman", "Regular", 14);
w.remove(list);
list = tempList;
list.selection = 0;
list.onDoubleClick=function(){
if (list.selected){
var buttonname = list.selection.text
var templatefile = new File (searchpath + "/" + buttonname + '.psd');
mainfunction (templatefile)
}
w.close();
}
}
}
ListItem.add
var B = w.add ('button', undefined, 'Ok', {name: 'ok'})
list.onDoubleClick=function(){
if (list.selected){
var buttonname = list.selection.text
var templatefile = new File (searchpath + "/" + buttonname + '.psd');
mainfunction (templatefile)
}
w.close();
}
if (w.show () != 2){
var buttonname = list.selection.text
var templatefile = new File (searchpath + "/" + buttonname + '.psd');
mainfunction (templatefile)
}
w.close();
}
On ExtendScript this creates a search box with a list below. Using the tab key you can switch between the search box and the list. I want to be able to also use the arrow keys to switch between the search box and the list. Can anyone advise if this is possible?
I have seen some results on jQuery, but sadly ExtendScript does not support jQuery, however it does support ScriptUI.
Many Thanks,
EDIT
I found this to be a resolution:
w.addEventListener ("keydown", function (kd) {pressed (kd)});
function pressed (k)
{
if (k.keyIdentifier === "Down" && entry.active = true)
list.active = true;
else if (k.keyIdentifier === "Up" && list.active = true)
entry.active = true ;
else
list.scrolling = true;
}
However, it does not work with Photoshop CC 2014. Does anyone know what I may be able to change to allow backwards compatibility?

How to clear list files before listing another one?

function listFiles() {
var x = document.getElementById("ResultShown").value;
var date = new Date();
date.setDate(date.getDate() - 180);
var n = date.toISOString().split('.')[0] ;
var test = false;
gapi.client.drive.files.list({
pageSize: x,
q: "starred = "+test+" and viewedByMeTime < '"+n+"'",
orderBy: 'quotaBytesUsed desc',
fields: "nextPageToken, files(id, name, viewedByMeTime, mimeType, quotaBytesUsed, webViewLink)",
}
).then(function(response) {
var table = document.getElementById('content');
appendPre('Files:');
appendRow(table, ['Name', 'Last Viewed', 'Link', 'Size'], 'th');
var files = response.result.files;
var table = document.getElementById('content');
if (files && files.length > 0) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
appendRow(table, [
file.name +" ",
file.viewedByMeTime.split('.')[0]+" ",
link(file.webViewLink),
file.quotaBytesUsed + ' bytes'
])
}
} else {
appendPre('No files found.');
}
});
}
Currently, every time I click a button to activate this function, a new list comes up, what can I add to it that will make the button clear the old list before putting a new one out?
Edit #1:
In this screenshot, you can see that every time I press a button to call on list file function, a new list comes up, instead of having a million list, I want it so everytime I clear the button, it clears the old list and replaces it with a new list
I only want one thing showing at a time.
You can remove all but the header row in your table element before adding new rows to it:
var table = document.getElementById('content');
var rows = table.rows;
while (rows.length > 1) rows[1].parentNode.removeChild(rows[1]);
Full Updated Code
appendPre('Files:');
appendRow(table, ['Name', 'Last Viewed', 'Link', 'Size'], 'th');
function listFiles() {
var x = document.getElementById("ResultShown").value;
var date = new Date();
date.setDate(date.getDate() - 180);
var n = date.toISOString().split('.')[0];
var test = false;
gapi.client.drive.files.list({
pageSize: x,
q: "starred = " + test + " and viewedByMeTime < '" + n + "'",
orderBy: 'quotaBytesUsed desc',
fields: "nextPageToken, files(id, name, viewedByMeTime, mimeType, quotaBytesUsed, webViewLink)",
}
).then(function(response) {
var table = document.getElementById('content');
var files = response.result.files;
var table = document.getElementById('content');
var rows = table.rows;
while (rows.length > 1) rows[1].parentNode.removeChild(rows[1]);
if (files && files.length > 0) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
appendRow(table, [
file.name + " ",
file.viewedByMeTime.split('.')[0] + " ",
link(file.webViewLink),
file.quotaBytesUsed + ' bytes'
])
}
} else {
appendPre('No files found.');
}
});
}
Note: This answer may seem out of context, because it builds on my answers to additional questions OP has asked concerning the same project.

Categories