diff --git a/package-lock.json b/package-lock.json index 04d2b408..914004eb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "timesafari", - "version": "1.1.0-beta", + "version": "1.1.1-beta", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "timesafari", - "version": "1.1.0-beta", + "version": "1.1.1-beta", "dependencies": { "@capacitor-community/electron": "^5.0.1", "@capacitor-community/sqlite": "6.0.2", diff --git a/src/components/ActivityListItem.vue b/src/components/ActivityListItem.vue index 6f27be86..ebc081d8 100644 --- a/src/components/ActivityListItem.vue +++ b/src/components/ActivityListItem.vue @@ -77,12 +77,86 @@ - -

- +

+
+ +
+ +
+ + + +
+ + +
+ +
+ +
+
+
+ + +

+

import { Component, Prop, Vue, Emit } from "vue-facing-decorator"; -import { GiveRecordWithContactInfo } from "@/interfaces/give"; +import VueMarkdown from "vue-markdown-render"; + +import { logger } from "../utils/logger"; +import { + createAndSubmitClaim, + getHeaders, + isHiddenDid, +} from "../libs/endorserServer"; import EntityIcon from "./EntityIcon.vue"; -import { isHiddenDid } from "../libs/endorserServer"; import ProjectIcon from "./ProjectIcon.vue"; -import { createNotifyHelpers, NotifyFunction } from "@/utils/notify"; +import { createNotifyHelpers, NotifyFunction, TIMEOUTS } from "@/utils/notify"; import { NOTIFY_PERSON_HIDDEN, NOTIFY_UNKNOWN_PERSON, } from "@/constants/notifications"; -import { TIMEOUTS } from "@/utils/notify"; -import VueMarkdown from "vue-markdown-render"; +import { EmojiSummaryRecord, GenericVerifiableCredential } from "@/interfaces"; +import { GiveRecordWithContactInfo } from "@/interfaces/give"; +import { PromiseTracker } from "@/libs/util"; @Component({ components: { @@ -274,15 +355,24 @@ import VueMarkdown from "vue-markdown-render"; }, }) export default class ActivityListItem extends Vue { + readonly QUICK_EMOJIS = ["👍", "👏", "❤️", "🎉", "😊", "😆", "🔥"]; + @Prop() record!: GiveRecordWithContactInfo; @Prop() lastViewedClaimId?: string; @Prop() isRegistered!: boolean; @Prop() activeDid!: string; + @Prop() apiServer!: string; isHiddenDid = isHiddenDid; notify!: ReturnType; $notify!: NotifyFunction; + // Emoji-related data + showEmojiPicker = false; + loadingEmojis = false; // Track if emojis are currently loading + + emojisOnActivity: PromiseTracker | null = null; // load this only when needed + created() { this.notify = createNotifyHelpers(this.$notify); } @@ -346,5 +436,186 @@ export default class ActivityListItem extends Vue { day: "numeric", }); } + + // Emoji-related computed properties and methods + get hasEmojis(): boolean { + return Object.keys(this.record.emojiCount).length > 0; + } + + triggerUserEmojiLoad(): PromiseTracker { + if (!this.emojisOnActivity) { + const promise = new Promise((resolve) => { + (async () => { + this.axios + .get( + `${this.apiServer}/api/v2/report/emoji?parentHandleId=${encodeURIComponent(this.record.handleId)}`, + { headers: await getHeaders(this.activeDid) }, + ) + .then((response) => { + const userEmojiRecords = response.data.data.filter( + (e: EmojiSummaryRecord) => e.issuerDid === this.activeDid, + ); + resolve(userEmojiRecords); + }) + .catch((error) => { + logger.error("Error loading user emojis:", error); + resolve([]); + }); + })(); + }); + + this.emojisOnActivity = new PromiseTracker(promise); + } + return this.emojisOnActivity; + } + + /** + * + * @param emoji - The emoji to check. + * @returns True if the emoji is in the user's emojis, false otherwise. + * + * @note This method is quick and synchronous, and can check resolved emojis + * without triggering a server request. Returns false if emojis haven't been loaded yet. + */ + isUserEmojiWithoutLoading(emoji: string): boolean { + if (this.emojisOnActivity?.isResolved && this.emojisOnActivity.value) { + return this.emojisOnActivity.value.some( + (record) => record.text === emoji, + ); + } + return false; + } + + async toggleEmojiPicker() { + this.triggerUserEmojiLoad(); // trigger it, but don't wait for it to complete + this.showEmojiPicker = !this.showEmojiPicker; + } + + async toggleThisEmoji(emoji: string) { + // Start loading indicator + this.loadingEmojis = true; + this.showEmojiPicker = false; // always close the picker when an emoji is clicked + + try { + this.triggerUserEmojiLoad(); // trigger just in case + + const userEmojiList = await this.emojisOnActivity!.promise; // must wait now that they've chosen + + const userHasEmoji: boolean = userEmojiList.some( + (record) => record.text === emoji, + ); + + if (userHasEmoji) { + this.$notify( + { + group: "modal", + type: "confirm", + title: "Remove Emoji", + text: `Do you want to remove your ${emoji} ?`, + yesText: "Remove", + onYes: async () => { + await this.removeEmoji(emoji); + }, + }, + TIMEOUTS.MODAL, + ); + } else { + // User doesn't have this emoji, add it + await this.submitEmoji(emoji); + } + } finally { + // Remove loading indicator + this.loadingEmojis = false; + } + } + + async submitEmoji(emoji: string) { + try { + // Create an Emoji claim and send to the server + const emojiClaim: GenericVerifiableCredential = { + "@context": "https://endorser.ch", + "@type": "Emoji", + text: emoji, + parentItem: { lastClaimId: this.record.jwtId }, + }; + const claim = await createAndSubmitClaim( + emojiClaim, + this.activeDid, + this.apiServer, + this.axios, + ); + if (claim.success && !claim.embeddedRecordError) { + // Update emoji count + this.record.emojiCount[emoji] = + (this.record.emojiCount[emoji] || 0) + 1; + + // Create a new emoji record (we'll get the actual jwtId from the server response later) + const newEmojiRecord: EmojiSummaryRecord = { + issuerDid: this.activeDid, + jwtId: claim.claimId || "", + text: emoji, + parentHandleId: this.record.jwtId, + }; + + // Update user emojis list by creating a new promise with the updated data + // (Trigger shouldn't be necessary since all calls should come through a toggle, but just in case someone calls this directly) + this.triggerUserEmojiLoad(); + const currentEmojis = await this.emojisOnActivity!.promise; // must wait now that they've clicked one + this.emojisOnActivity = new PromiseTracker( + Promise.resolve([...currentEmojis, newEmojiRecord]), + ); + } else { + this.notify.error("Failed to add emoji.", TIMEOUTS.STANDARD); + } + } catch (error) { + logger.error("Error submitting emoji:", error); + this.notify.error("Got error adding emoji.", TIMEOUTS.STANDARD); + } + } + + async removeEmoji(emoji: string) { + try { + // Create an Emoji claim and send to the server + const emojiClaim: GenericVerifiableCredential = { + "@context": "https://endorser.ch", + "@type": "Emoji", + text: emoji, + parentItem: { lastClaimId: this.record.jwtId }, + }; + const claim = await createAndSubmitClaim( + emojiClaim, + this.activeDid, + this.apiServer, + this.axios, + ); + if (claim.success && !claim.embeddedRecordError) { + // Update emoji count + const newCount = Math.max(0, (this.record.emojiCount[emoji] || 0) - 1); + if (newCount === 0) { + delete this.record.emojiCount[emoji]; + } else { + this.record.emojiCount[emoji] = newCount; + } + + // Update user emojis list by creating a new promise with the updated data + // (Trigger shouldn't be necessary since all calls should come through a toggle, but just in case someone calls this directly) + this.triggerUserEmojiLoad(); + const currentEmojis = await this.emojisOnActivity!.promise; // must wait now that they've clicked one + this.emojisOnActivity = new PromiseTracker( + Promise.resolve( + currentEmojis.filter( + (record) => + record.issuerDid === this.activeDid && record.text !== emoji, + ), + ), + ); + } else { + this.notify.error("Failed to remove emoji.", TIMEOUTS.STANDARD); + } + } catch (error) { + logger.error("Error removing emoji:", error); + this.notify.error("Got error removing emoji.", TIMEOUTS.STANDARD); + } + } } diff --git a/src/db-sql/migration.ts b/src/db-sql/migration.ts index ca5dad14..4a177786 100644 --- a/src/db-sql/migration.ts +++ b/src/db-sql/migration.ts @@ -234,32 +234,20 @@ export async function runMigrations( sqlQuery: (sql: string, params?: unknown[]) => Promise, extractMigrationNames: (result: T) => Set, ): Promise { - // Only log migration start in development - const isDevelopment = process.env.VITE_PLATFORM === "development"; - if (isDevelopment) { - logger.debug("[Migration] Starting database migrations"); - } + logger.debug("[Migration] Starting database migrations"); for (const migration of MIGRATIONS) { - if (isDevelopment) { - logger.debug("[Migration] Registering migration:", migration.name); - } + logger.debug("[Migration] Registering migration:", migration.name); registerMigration(migration); } - if (isDevelopment) { - logger.debug("[Migration] Running migration service"); - } + logger.debug("[Migration] Running migration service"); await runMigrationsService(sqlExec, sqlQuery, extractMigrationNames); - if (isDevelopment) { - logger.debug("[Migration] Database migrations completed"); - } + logger.debug("[Migration] Database migrations completed"); // Bootstrapping: Ensure active account is selected after migrations - if (isDevelopment) { - logger.debug("[Migration] Running bootstrapping hooks"); - } + logger.debug("[Migration] Running bootstrapping hooks"); try { // Check if we have accounts but no active selection const accountsResult = await sqlQuery("SELECT COUNT(*) FROM accounts"); @@ -274,18 +262,14 @@ export async function runMigrations( activeDid = (extractSingleValue(activeResult) as string) || null; } catch (error) { // Table doesn't exist - migration 004 may not have run yet - if (isDevelopment) { - logger.debug( - "[Migration] active_identity table not found - migration may not have run", - ); - } + logger.debug( + "[Migration] active_identity table not found - migration may not have run", + ); activeDid = null; } if (accountsCount > 0 && (!activeDid || activeDid === "")) { - if (isDevelopment) { - logger.debug("[Migration] Auto-selecting first account as active"); - } + logger.debug("[Migration] Auto-selecting first account as active"); const firstAccountResult = await sqlQuery( "SELECT did FROM accounts ORDER BY dateCreated, did LIMIT 1", ); diff --git a/src/interfaces/claims.ts b/src/interfaces/claims.ts index 1fc03529..49e2b4a8 100644 --- a/src/interfaces/claims.ts +++ b/src/interfaces/claims.ts @@ -14,6 +14,13 @@ export interface AgreeActionClaim extends ClaimObject { object: Record; } +export interface EmojiClaim extends ClaimObject { + // default context is "https://endorser.ch" + "@type": "Emoji"; + text: string; + parentItem: { lastClaimId: string }; +} + // Note that previous VCs may have additional fields. // https://endorser.ch/doc/html/transactions.html#id4 export interface GiveActionClaim extends ClaimObject { diff --git a/src/interfaces/common.ts b/src/interfaces/common.ts index b2e68d1f..f1f172e2 100644 --- a/src/interfaces/common.ts +++ b/src/interfaces/common.ts @@ -81,7 +81,9 @@ export interface UserInfo { export interface CreateAndSubmitClaimResult { success: boolean; + embeddedRecordError?: string; error?: string; + claimId?: string; handleId?: string; } diff --git a/src/interfaces/index.ts b/src/interfaces/index.ts index fbbe1c50..c4b12191 100644 --- a/src/interfaces/index.ts +++ b/src/interfaces/index.ts @@ -1,36 +1,6 @@ -export type { - // From common.ts - CreateAndSubmitClaimResult, - GenericCredWrapper, - GenericVerifiableCredential, - KeyMeta, - // Exclude types that are also exported from other files - // GiveVerifiableCredential, - // OfferVerifiableCredential, - // RegisterVerifiableCredential, - // PlanSummaryRecord, - // UserInfo, -} from "./common"; - -export type { - // From claims.ts - GiveActionClaim, - OfferClaim, - RegisterActionClaim, -} from "./claims"; - -export type { - // From records.ts - PlanSummaryRecord, -} from "./records"; - -export type { - // From user.ts - UserInfo, -} from "./user"; - -export * from "./limits"; -export * from "./deepLinks"; -export * from "./common"; +export * from "./claims"; export * from "./claims-result"; +export * from "./common"; +export * from "./deepLinks"; +export * from "./limits"; export * from "./records"; diff --git a/src/interfaces/records.ts b/src/interfaces/records.ts index ca82624c..03627904 100644 --- a/src/interfaces/records.ts +++ b/src/interfaces/records.ts @@ -1,14 +1,26 @@ import { GiveActionClaim, OfferClaim, PlanActionClaim } from "./claims"; import { GenericCredWrapper } from "./common"; +export interface EmojiSummaryRecord { + issuerDid: string; + jwtId: string; + text: string; + parentHandleId: string; +} + // a summary record; the VC is found the fullClaim field export interface GiveSummaryRecord { - [x: string]: PropertyKey | undefined | GiveActionClaim; + [x: string]: + | PropertyKey + | undefined + | GiveActionClaim + | Record; type?: string; agentDid: string; amount: number; amountConfirmed: number; description: string; + emojiCount: Record; // Map of emoji character to count fullClaim: GiveActionClaim; fulfillsHandleId: string; fulfillsPlanHandleId?: string; diff --git a/src/libs/endorserServer.ts b/src/libs/endorserServer.ts index a0e2bf6c..08a65934 100644 --- a/src/libs/endorserServer.ts +++ b/src/libs/endorserServer.ts @@ -630,11 +630,7 @@ async function performPlanRequest( return cred; } else { - // Use debug level for development to reduce console noise - const isDevelopment = process.env.VITE_PLATFORM === "development"; - const log = isDevelopment ? logger.debug : logger.log; - - log( + logger.debug( "[Plan Loading] ⚠️ Plan cache is empty for handle", handleId, " Got data:", @@ -1226,7 +1222,12 @@ export async function createAndSubmitClaim( timestamp: new Date().toISOString(), }); - return { success: true, handleId: response.data?.handleId }; + return { + success: true, + claimId: response.data?.claimId, + handleId: response.data?.handleId, + embeddedRecordError: response.data?.embeddedRecordError, + }; } catch (error: unknown) { // Enhanced error logging with comprehensive context const requestId = `claim_error_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; diff --git a/src/libs/util.ts b/src/libs/util.ts index 40d0fd3a..72dbf164 100644 --- a/src/libs/util.ts +++ b/src/libs/util.ts @@ -1147,3 +1147,29 @@ export async function checkForDuplicateAccount( return (existingAccount?.values?.length ?? 0) > 0; } + +export class PromiseTracker { + private _promise: Promise; + private _resolved = false; + private _value: T | undefined; + + constructor(promise: Promise) { + this._promise = promise.then((value) => { + this._resolved = true; + this._value = value; + return value; + }); + } + + get isResolved(): boolean { + return this._resolved; + } + + get value(): T | undefined { + return this._value; + } + + get promise(): Promise { + return this._promise; + } +} diff --git a/src/services/platforms/WebPlatformService.ts b/src/services/platforms/WebPlatformService.ts index 3d8248f5..b5b25622 100644 --- a/src/services/platforms/WebPlatformService.ts +++ b/src/services/platforms/WebPlatformService.ts @@ -48,15 +48,13 @@ export class WebPlatformService implements PlatformService { constructor() { WebPlatformService.instanceCount++; - // Use debug level logging for development mode to reduce console noise - const isDevelopment = process.env.VITE_PLATFORM === "development"; - const log = isDevelopment ? logger.debug : logger.log; - - log("[WebPlatformService] Initializing web platform service"); + logger.debug("[WebPlatformService] Initializing web platform service"); // Only initialize SharedArrayBuffer setup for web platforms if (this.isWorker()) { - log("[WebPlatformService] Skipping initBackend call in worker context"); + logger.debug( + "[WebPlatformService] Skipping initBackend call in worker context", + ); return; } diff --git a/src/views/ClaimView.vue b/src/views/ClaimView.vue index 3d09ac42..9671e801 100644 --- a/src/views/ClaimView.vue +++ b/src/views/ClaimView.vue @@ -91,12 +91,15 @@
- +
@@ -551,7 +554,7 @@ import VueMarkdown from "vue-markdown-render"; import { Router, RouteLocationNormalizedLoaded } from "vue-router"; import { copyToClipboard } from "../services/ClipboardService"; -import { GenericVerifiableCredential } from "../interfaces"; +import { EmojiClaim, GenericVerifiableCredential } from "../interfaces"; import GiftedDialog from "../components/GiftedDialog.vue"; import QuickNav from "../components/QuickNav.vue"; import { NotificationIface } from "../constants/app"; @@ -667,6 +670,10 @@ export default class ClaimView extends Vue { return giveClaim.description || ""; } + if (this.veriClaim.claimType === "Emoji") { + return (claim as EmojiClaim).text || ""; + } + // Fallback for other claim types return (claim as { description?: string })?.description || ""; } diff --git a/src/views/HomeView.vue b/src/views/HomeView.vue index 3e73cda4..9f087d85 100644 --- a/src/views/HomeView.vue +++ b/src/views/HomeView.vue @@ -245,6 +245,7 @@ Raymer * @version 1.0.0 */ :last-viewed-claim-id="feedLastViewedClaimId" :is-registered="isRegistered" :active-did="activeDid" + :api-server="apiServer" @load-claim="onClickLoadClaim" @view-image="openImageViewer" /> @@ -1264,6 +1265,7 @@ export default class HomeView extends Vue { provider, fulfillsPlan, providedByPlan, + record.emojiCount, ); } @@ -1487,12 +1489,14 @@ export default class HomeView extends Vue { provider: Provider | undefined, fulfillsPlan?: FulfillsPlan, providedByPlan?: ProvidedByPlan, + emojiCount?: Record, ): GiveRecordWithContactInfo { return { ...record, jwtId: record.jwtId, fullClaim: record.fullClaim, description: record.description || "", + emojiCount: emojiCount || {}, handleId: record.handleId, issuerDid: record.issuerDid, fulfillsPlanHandleId: record.fulfillsPlanHandleId,