ES5 → 7: Use for in/of and let

This commit is contained in:
miruka 2019-07-18 05:18:13 -04:00
parent 8a38274280
commit 1fa8b70359
12 changed files with 59 additions and 77 deletions

View File

@ -15,8 +15,8 @@ HScalingBox {
default property alias body: interfaceBody.children default property alias body: interfaceBody.children
function clickEnterButtonTarget() { function clickEnterButtonTarget() {
for (var i = 0; i < buttonModel.length; i++) { for (let i = 0; i < buttonModel.length; i++) {
var btn = interfaceButtonsRepeater.itemAt(i) let btn = interfaceButtonsRepeater.itemAt(i)
if (btn.name === enterButtonTarget) { btn.clicked() } if (btn.name === enterButtonTarget) { btn.clicked() }
} }
} }

View File

@ -25,20 +25,18 @@ SortFilterProxyModel {
} }
function extend(newItems) { function extend(newItems) {
for (var i = 0; i < newItems.length; i++) { for (let item of newItems) { model.append(item) }
model.append(newItems[i])
}
} }
function getIndices(whereRolesAre, maxResults=null, maxTries=null) { function getIndices(whereRolesAre, maxResults=null, maxTries=null) {
// maxResults, maxTries: null or int // maxResults, maxTries: null or int
var results = [] let results = []
for (var i = 0; i < model.count; i++) { for (let i = 0; i < model.count; i++) {
var item = model.get(i) let item = model.get(i)
var include = true let include = true
for (var role in whereRolesAre) { for (let role in whereRolesAre) {
if (item[role] != whereRolesAre[role]) { if (item[role] != whereRolesAre[role]) {
include = false include = false
break break
@ -60,33 +58,31 @@ SortFilterProxyModel {
} }
function getWhere(rolesAre, maxResults=null, maxTries=null) { function getWhere(rolesAre, maxResults=null, maxTries=null) {
var indices = getIndices(rolesAre, maxResults, maxTries) let items = []
var items = []
for (var i = 0; i < indices.length; i++) { for (let indice of getIndices(rolesAre, maxResults, maxTries)) {
items.push(model.get(indices[i])) items.push(model.get(indice))
} }
return items return items
} }
function forEachWhere(rolesAre, func, maxResults=null, maxTries=null) { function forEachWhere(rolesAre, func, maxResults=null, maxTries=null) {
var items = getWhere(rolesAre, maxResults, maxTries) for (let item of getWhere(rolesAre, maxResults, maxTries)) {
for (var i = 0; i < items.length; i++) { func(item)
func(items[i])
} }
} }
function upsert( function upsert(
whereRolesAre, newItem, updateIfExist=true, maxTries=null whereRolesAre, newItem, updateIfExist=true, maxTries=null
) { ) {
var indices = getIndices(whereRolesAre, 1, maxTries) let indices = getIndices(whereRolesAre, 1, maxTries)
if (indices.length == 0) { if (indices.length == 0) {
model.append(newItem) model.append(newItem)
return model.get(model.count) return model.get(model.count)
} }
var existing = model.get(indices[0]) let existing = model.get(indices[0])
if (! updateIfExist) { return existing } if (! updateIfExist) { return existing }
// Really update only if existing and new item have a difference // Really update only if existing and new item have a difference
@ -107,31 +103,29 @@ SortFilterProxyModel {
} }
function pop(index) { function pop(index) {
var item = model.get(index) let item = model.get(index)
model.remove(index) model.remove(index)
return item return item
} }
function popWhere(rolesAre, maxResults=null, maxTries=null) { function popWhere(rolesAre, maxResults=null, maxTries=null) {
var indices = getIndices(rolesAre, maxResults, maxTries) let items = []
var items = []
for (var i = 0; i < indices.length; i++) { for (let indice of getIndices(rolesAre, maxResults, maxTries)) {
items.push(model.get(indices[i])) items.push(model.get(indice))
model.remove(indices[i]) model.remove(indice)
} }
return items return items
} }
function toObject(itemList=sortFilteredModel) { function toObject(itemList=sortFilteredModel) {
var objList = [] let objList = []
for (var i = 0; i < itemList.count; i++) { for (let item of itemList) {
var item = itemList.get(i) let obj = JSON.parse(JSON.stringify(item))
var obj = JSON.parse(JSON.stringify(item))
for (var role in obj) { for (let role in obj) {
if (obj[role]["objectName"] != undefined) { if (obj[role]["objectName"] != undefined) {
obj[role] = toObject(item[role]) obj[role] = toObject(item[role])
} }

View File

@ -68,7 +68,7 @@ HRectangle {
if (textArea.text === "") { return } if (textArea.text === "") { return }
var args = [chatPage.roomId, textArea.text] let args = [chatPage.roomId, textArea.text]
py.callClientCoro(chatPage.userId, "send_markdown", args) py.callClientCoro(chatPage.userId, "send_markdown", args)
area.clear() area.clear()
}) })

View File

@ -58,7 +58,7 @@ Column {
readonly property int verticalPadding: theme.spacing / 2 readonly property int verticalPadding: theme.spacing / 2
ListView.onAdd: { ListView.onAdd: {
var nextDelegate = eventList.contentItem.children[index] let nextDelegate = eventList.contentItem.children[index]
if (nextDelegate) { nextDelegate.reloadPreviousItem() } if (nextDelegate) { nextDelegate.reloadPreviousItem() }
} }

View File

@ -6,13 +6,11 @@
Qt.include("../utils.js") Qt.include("../utils.js")
function typingTextFor(members, ourUserId) { function typingTextFor(members, ourUserId) {
var profiles = [] let profiles = []
var names = [] let names = []
for (var i = 0; i < members.length; i++) { for (let member of members) {
if (members[i] != ourUserId) { if (member != ourUserId) { profiles.push(users.find(member)) }
profiles.push(users.find(members[i]))
}
} }
profiles.sort((left, right) => { profiles.sort((left, right) => {
@ -21,15 +19,14 @@ function typingTextFor(members, ourUserId) {
return 0 return 0
}) })
for (var i = 0; i < profiles.length; i++) { for (let profile of profiles) {
var profile = profiles[i]
names.push(coloredNameHtml(profile.displayName, profile.userId)) names.push(coloredNameHtml(profile.displayName, profile.userId))
} }
if (names.length == 0) { return "" } if (names.length == 0) { return "" }
if (names.length == 1) { return qsTr("%1 is typing...").arg(names[0]) } if (names.length == 1) { return qsTr("%1 is typing...").arg(names[0]) }
var text = qsTr("%1 and %2 are typing...") let text = qsTr("%1 and %2 are typing...")
if (names.length == 2) { return text.arg(names[0]).arg(names[1]) } if (names.length == 2) { return text.arg(names[0]).arg(names[1]) }
@ -44,16 +41,16 @@ function onRoomUpdated(
roomCategories.upsert({userId, name: category}, {userId, name: category}) roomCategories.upsert({userId, name: category}, {userId, name: category})
function find(category) { function find(category) {
var found = rooms.getIndices({userId, roomId, category}, 1) let found = rooms.getIndices({userId, roomId, category}, 1)
return found.length > 0 ? found[0] : null return found.length > 0 ? found[0] : null
} }
var replace = null let replace = null
if (category == "Invites") { replace = find("Rooms") || find("Left") } if (category == "Invites") { replace = find("Rooms") || find("Left") }
else if (category == "Rooms") { replace = find("Invites") || find("Left") } else if (category == "Rooms") { replace = find("Invites") || find("Left") }
else if (category == "Left") { replace = find("Invites") || find("Rooms")} else if (category == "Left") { replace = find("Invites") || find("Rooms")}
var item = { let item = {
typingText: typingTextFor(typingMembers, userId), typingText: typingTextFor(typingMembers, userId),
userId, category, roomId, displayName, avatarUrl, topic, members, userId, category, roomId, displayName, avatarUrl, topic, members,
@ -77,7 +74,7 @@ function onTimelineEventReceived(
eventType, roomId, eventId, senderId, date, content, eventType, roomId, eventId, senderId, date, content,
contentType, isLocalEcho, showNameLine, translatable, targetUserId contentType, isLocalEcho, showNameLine, translatable, targetUserId
) { ) {
var item = { let item = {
eventType: py.getattr(eventType, "__name__"), eventType: py.getattr(eventType, "__name__"),
roomId, eventId, senderId, date, content, contentType, isLocalEcho, roomId, eventId, senderId, date, content, contentType, isLocalEcho,
@ -90,7 +87,7 @@ function onTimelineEventReceived(
} }
// Replace first matching local echo // Replace first matching local echo
var found = timelines.getIndices( let found = timelines.getIndices(
{roomId, senderId, content, "isLocalEcho": true}, 1, 250 {roomId, senderId, content, "isLocalEcho": true}, 1, 250
) )

View File

@ -7,12 +7,11 @@ import "../Base"
HListModel { HListModel {
function lastEventOf(roomId) { function lastEventOf(roomId) {
// Return an event item or undefined if none found for (let i = 0; i < count; i++) {
let item = get(i) // TODO: standardize
for (var i = 0; i < count; i++) {
var item = get(i) // TODO: standardize
if (item.roomId == roomId) { return item } if (item.roomId == roomId) { return item }
} }
return null
} }
sorters: ExpressionSorter { sorters: ExpressionSorter {

View File

@ -11,7 +11,7 @@ HListModel {
// the expression with invalid data to establish property bindings // the expression with invalid data to establish property bindings
if (! userId) { return } if (! userId) { return }
var found = getWhere({userId}, 1) let found = getWhere({userId}, 1)
if (found.length > 0) { return found[0] } if (found.length > 0) { return found[0] }
py.callCoro("request_user_update_event", [userId]) py.callCoro("request_user_update_event", [userId])

View File

@ -21,7 +21,7 @@ HGridLayout {
if (avatar.changed) { if (avatar.changed) {
saveButton.avatarChangeRunning = true saveButton.avatarChangeRunning = true
var path = Qt.resolvedUrl(avatar.imageUrl).replace(/^file:/, "") let path = Qt.resolvedUrl(avatar.imageUrl).replace(/^file:/, "")
py.callClientCoro( py.callClientCoro(
userId, "set_avatar_from_file", [path], response => { userId, "set_avatar_from_file", [path], response => {

View File

@ -27,7 +27,7 @@ Item {
login: button => { login: button => {
button.loading = true button.loading = true
var args = [idField.text, passwordField.text] let args = [idField.text, passwordField.text]
py.callCoro("login_client", args, userId => { py.callCoro("login_client", args, userId => {
pageStack.showPage("RememberAccount", {loginWith, userId}) pageStack.showPage("RememberAccount", {loginWith, userId})

View File

@ -20,14 +20,14 @@ Python {
} }
function callCoro(name, args=[], callback=null) { function callCoro(name, args=[], callback=null) {
var uuid = Math.random() + "." + name let uuid = Math.random() + "." + name
pendingCoroutines[uuid] = callback || function() {} pendingCoroutines[uuid] = callback || function() {}
call("APP.call_backend_coro", [name, uuid, args]) call("APP.call_backend_coro", [name, uuid, args])
} }
function callClientCoro(accountId, name, args=[], callback=null) { function callClientCoro(accountId, name, args=[], callback=null) {
var uuid = Math.random() + "." + name let uuid = Math.random() + "." + name
pendingCoroutines[uuid] = callback || function() {} pendingCoroutines[uuid] = callback || function() {}
call("APP.call_client_coro", [accountId, name, uuid, args]) call("APP.call_client_coro", [accountId, name, uuid, args])

View File

@ -64,8 +64,7 @@ Item {
} }
function showRoom(userId, category, roomId) { function showRoom(userId, category, roomId) {
var info = rooms.getWhere({userId, roomId, category}, 1)[0] let info = rooms.getWhere({userId, roomId, category}, 1)[0]
pageStack.replace("Chat/Chat.qml", {"roomInfo": info}) pageStack.replace("Chat/Chat.qml", {"roomInfo": info})
} }

View File

@ -18,11 +18,11 @@ function hsla(hue, saturation, lightness, alpha=1.0) {
function arrayToModelItem(keysName, array) { function arrayToModelItem(keysName, array) {
// Convert an array to an object suitable to be in a model, example: // Convert an array to an object suitable to be in a model, example:
// [1, 2, 3] → [{keysName: 1}, {keysName: 2}, {keysName: 3}] // [1, 2, 3] → [{keysName: 1}, {keysName: 2}, {keysName: 3}]
var items = [] let items = []
for (var i = 0; i < array.length; i++) { for (let item of array) {
var obj = {} let obj = {}
obj[keysName] = array[i] obj[keysName] = item
items.push(obj) items.push(obj)
} }
return items return items
@ -31,8 +31,8 @@ function arrayToModelItem(keysName, array) {
function hueFrom(string) { function hueFrom(string) {
// Calculate and return a unique hue between 0 and 1 for the string // Calculate and return a unique hue between 0 and 1 for the string
var hue = 0 let hue = 0
for (var i = 0; i < string.length; i++) { for (let i = 0; i < string.length; i++) {
hue += string.charCodeAt(i) * 99 hue += string.charCodeAt(i) * 99
} }
return hue % 360 / 360 return hue % 360 / 360
@ -87,23 +87,16 @@ function translatedEventContent(ev) {
if (ev.translatable == false) { return ev.content } if (ev.translatable == false) { return ev.content }
// %S → sender display name // %S → sender display name
var name = users.find(ev.senderId).displayName let name = users.find(ev.senderId).displayName
var text = ev.content.replace("%S", coloredNameHtml(name, ev.senderId)) let text = ev.content.replace("%S", coloredNameHtml(name, ev.senderId))
// %T → target (event state_key) display name // %T → target (event state_key) display name
if (ev.targetUserId) { if (ev.targetUserId) {
var tname = users.find(ev.targetUserId).displayName let tname = users.find(ev.targetUserId).displayName
text = text.replace("%T", coloredNameHtml(tname, ev.targetUserId)) text = text.replace("%T", coloredNameHtml(tname, ev.targetUserId))
} }
text = qsTr(text) return qsTr(text)
if (ev.translatable == true) { return text }
// Else, model.translatable should be an array of args
for (var i = 0; ev.translatable.length; i++) {
text = text.arg(ev.translatable[i])
}
return text
} }
@ -111,10 +104,10 @@ function filterMatches(filter, text) {
filter = filter.toLowerCase() filter = filter.toLowerCase()
text = text.toLowerCase() text = text.toLowerCase()
var words = filter.split(" ") let words = filter.split(" ")
for (var i = 0; i < words.length; i++) { for (let word of words) {
if (words[i] && ! text.includes(words[i])) { if (word && ! text.includes(word)) {
return false return false
} }
} }