Skip to content

Commit

Permalink
refactor: get rid of mutations with settings
Browse files Browse the repository at this point in the history
  • Loading branch information
alsakhaev committed Jan 23, 2025
1 parent 761ba19 commit 65ee2c7
Show file tree
Hide file tree
Showing 23 changed files with 151 additions and 173 deletions.
21 changes: 15 additions & 6 deletions apps/extension/src/contentscript/hooks/use-side-panel.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { IContextNode } from '@mweb/core'
import { useEffect } from 'react'
import { useEffect, useState } from 'react'
import browser from 'webextension-polyfill'
import { EventEmitter as NEventEmitter } from 'events'
import { useMutableWeb } from '@mweb/engine'

export const useSidePanel = () => {
const { tree, selectedMutation, switchMutation } = useMutableWeb()
const { tree, selectedMutationId, switchMutation } = useMutableWeb()
const [port, setPort] = useState<browser.Runtime.Port | null>(null)

useEffect(() => {
if (!tree) return
Expand Down Expand Up @@ -33,9 +34,6 @@ export const useSidePanel = () => {
return
}

port.postMessage({ type: 'contextTree', data: tree.toTransferable({ dir: 'down' }) })
port.postMessage({ type: 'setSelectedMutationId', data: selectedMutation?.id })

const handleChildContextAdded = (data: IContextNode) =>
port.postMessage({ type: 'childContextAdded', data })
const handleChildContextRemoved = (data: IContextNode) =>
Expand All @@ -58,7 +56,10 @@ export const useSidePanel = () => {
ee.removeListener('childContextAdded', handleChildContextAdded)
ee.removeListener('childContextRemoved', handleChildContextRemoved)
ee.removeListener('contextChanged', handleContextChanged)
setPort(null)
})

setPort(port)
}

browser.runtime.onConnect.addListener(handleConnect)
Expand All @@ -70,5 +71,13 @@ export const useSidePanel = () => {
ee.removeAllListeners('childContextRemoved')
ee.removeAllListeners('contextChanged')
}
}, [tree, selectedMutation])
}, [tree])

useEffect(() => {
port?.postMessage({ type: 'setSelectedMutationId', data: selectedMutationId })
}, [port, selectedMutationId])

useEffect(() => {
port?.postMessage({ type: 'contextTree', data: tree?.toTransferable({ dir: 'down' }) })
}, [port, tree])
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const MultitablePanel: FC = () => {
const { accountId, networkId } = useWallet()
const { connectWallet } = useConnectWallet()
const { disconnectWallet } = useDisconnectWallet()
const { tree, mutations, selectedMutation, switchMutation } = useMutableWeb()
const { tree, mutations, selectedMutationId, switchMutation } = useMutableWeb()

// The notch can be opened from the extension's context menu on websites without any mutation
if (mutations.length === 0) return null
Expand All @@ -36,7 +36,7 @@ export const MultitablePanel: FC = () => {
nearNetwork={networkId}
onConnectWallet={connectWallet}
onDisconnectWallet={disconnectWallet}
selectedMutationId={selectedMutation?.id ?? null}
selectedMutationId={selectedMutationId}
onSwitchMutation={switchMutation}
>
<UberSausageWrapper>
Expand Down
2 changes: 1 addition & 1 deletion libs/backend/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export { Engine } from './engine'
export { EntityId, EntitySourceType } from './services/base/base.entity'
export { MutationWithSettings, AppInMutation } from './services/mutation/mutation.entity'
export { AppInMutation } from './services/mutation/mutation.entity'
export { MutationDto } from './services/mutation/dtos/mutation.dto'
export { SaveMutationOptions } from './services/mutation/mutation.service'
export { MutationCreateDto } from './services/mutation/dtos/mutation-create.dto'
Expand Down
6 changes: 0 additions & 6 deletions libs/backend/src/services/mutation/mutation.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,6 @@ export class Mutation extends Base {
}
}

export type MutationWithSettings = MutationDto & {
settings: {
lastUsage: string | null
}
}

function normalizeApps(apps: any): AppInMutation[] {
return apps.map((app: any) => (typeof app === 'string' ? { appId: app, documentId: null } : app))
}
Expand Down
69 changes: 30 additions & 39 deletions libs/backend/src/services/mutation/mutation.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { IContextNode } from '@mweb/core'
import { TargetService } from '../target/target.service'
import { Mutation, MutationId, MutationWithSettings } from './mutation.entity'
import { Mutation, MutationId } from './mutation.entity'
import { Transaction } from '../unit-of-work/transaction'
import { UnitOfWorkService } from '../unit-of-work/unit-of-work.service'
import { NotificationService } from '../notification/notification.service'
Expand Down Expand Up @@ -58,19 +58,16 @@ export class MutationService {
.map((mutation) => mutation.toDto())
}

async getMutationsWithSettings(context: IContextNode | null): Promise<MutationWithSettings[]> {
const mutations = await this.getMutationsForContext(context)

return Promise.all(mutations.map((mut) => this.populateMutationWithSettings(mut)))
}

getLastUsedMutation = async (context: IContextNode): Promise<string | null> => {
const allMutations = await this.getMutationsWithSettings(context)
const hostname = window.location.hostname
if (!context.id) return null
const contextId = context.id

// ToDo: refactor it, too complicated
const allMutations = await this.getMutationsForContext(context)
const lastUsedData = await Promise.all(
allMutations.map(async (m) => ({
id: m.id,
lastUsage: await this.settingsService.getMutationLastUsage(m.id, hostname),
lastUsage: await this.settingsService.getMutationLastUsage(m.id, contextId),
}))
)
const usedMutationsData = lastUsedData
Expand Down Expand Up @@ -125,7 +122,7 @@ export class MutationService {
applyChangesToOrigin: false,
askOriginToApplyChanges: false,
}
): Promise<MutationWithSettings> {
): Promise<MutationDto> {
const { applyChangesToOrigin, askOriginToApplyChanges } = options

const mutation = await this._fixMutationErrors(await this.mutationRepository.constructItem(dto))
Expand All @@ -144,7 +141,7 @@ export class MutationService {
throw new Error('Invalid entity source')
}

return this.populateMutationWithSettings(mutation.toDto())
return mutation.toDto()
}

async editMutation(
Expand All @@ -154,7 +151,7 @@ export class MutationService {
askOriginToApplyChanges: false,
},
tx?: Transaction
): Promise<MutationWithSettings> {
): Promise<MutationDto> {
const { applyChangesToOrigin, askOriginToApplyChanges } = options

const mutation = await this._fixMutationErrors(Mutation.create(dto))
Expand Down Expand Up @@ -188,7 +185,7 @@ export class MutationService {
throw new Error('Invalid entity source')
}

return this.populateMutationWithSettings(editedMutation.toDto())
return editedMutation.toDto()
}

async saveMutation(
Expand All @@ -198,7 +195,7 @@ export class MutationService {
askOriginToApplyChanges: false,
},
tx?: Transaction
): Promise<MutationWithSettings> {
): Promise<MutationDto> {
const { applyChangesToOrigin, askOriginToApplyChanges } = options

const mutation = await this._fixMutationErrors(
Expand All @@ -225,7 +222,7 @@ export class MutationService {
throw new Error('Invalid entity source')
}

return this.populateMutationWithSettings(mutation.toDto())
return mutation.toDto()
}

async deleteMutation(mutationId: EntityId): Promise<void> {
Expand Down Expand Up @@ -289,36 +286,30 @@ export class MutationService {
return freshNotification
}

async removeMutationFromRecents(mutationId: MutationId): Promise<void> {
await this.settingsService.setMutationLastUsage(mutationId, null, window.location.hostname)
async removeMutationFromRecents(mutationId: MutationId, context: IContextNode): Promise<void> {
if (!context.id) return
await this.settingsService.setMutationLastUsage(mutationId, null, context.id)
}

public async updateMutationLastUsage(mutationId: MutationId, hostname: string): Promise<string> {
public async getMutationLastUsage(
mutationId: MutationId,
context: IContextNode
): Promise<string | null> {
if (!context.id) return null
return this.settingsService.getMutationLastUsage(mutationId, context.id)
}

public async updateMutationLastUsage(
mutationId: MutationId,
context: IContextNode
): Promise<string> {
if (!context.id) throw new Error('Context ID is not defined')
// save last usage
const currentDate = new Date().toISOString()
await this.settingsService.setMutationLastUsage(mutationId, currentDate, hostname)
await this.settingsService.setMutationLastUsage(mutationId, currentDate, context.id)
return currentDate
}

async getMutationWithSettings(
mutationId: string,
source?: EntitySourceType,
version?: string
): Promise<MutationWithSettings | null> {
const mutation = await this.getMutation(mutationId, source, version)
return mutation ? this.populateMutationWithSettings(mutation) : null
}

public async populateMutationWithSettings(mutation: MutationDto): Promise<MutationWithSettings> {
const lastUsage = await this.settingsService.getMutationLastUsage(
mutation.id,
window.location.hostname // ToDo: bug for side panels
)

// ToDo: do not mix MutationWithSettings and Mutation
return { ...mutation, settings: { lastUsage } }
}

private async _applyChangesToOrigin(forkedMutation: Mutation, tx?: Transaction) {
const originalMutationId = forkedMutation.metadata.fork_of

Expand Down
1 change: 0 additions & 1 deletion libs/engine/src/app/components/context-manager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ import {
useContextApps,
useCreateUserLink,
useDeleteUserLink,
useUpdateMutationLastUsage,
useUserLinks,
} from '@mweb/react-engine'

Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
import { Engine, EntitySourceType } from '@mweb/backend'
import { createContext } from 'react'
import { AppInstanceWithSettings } from '@mweb/backend'
import { MutationWithSettings } from '@mweb/backend'
import { MutationDto } from '@mweb/backend'
import { NearConfig } from '@mweb/backend'
import { IContextNode } from '@mweb/core'

export type MutableWebContextState = {
config: NearConfig
engine: Engine
tree: IContextNode | null
mutations: MutationWithSettings[]
mutations: MutationDto[]
mutationApps: AppInstanceWithSettings[]
activeApps: AppInstanceWithSettings[]
selectedMutation: MutationWithSettings | null
selectedMutation: MutationDto | null
selectedMutationId: string | null
isLoading: boolean
switchMutation: (mutationId: string | null) => void
switchPreferredSource: (mutationId: string, source: EntitySourceType | null) => void
Expand All @@ -29,6 +30,7 @@ export const contextDefaultValues: MutableWebContextState = {
activeApps: [],
isLoading: false,
selectedMutation: null,
selectedMutationId: null,
switchMutation: () => undefined,
switchPreferredSource: () => undefined,
switchMutationVersion: () => undefined,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ import { EngineConfig, EntitySourceType, getNearConfig, utils } from '@mweb/back
import { useCore } from '@mweb/react'
import {
useEngine,
useMutation,
useMutationApps,
useMutationParsers,
useMutations,
useMutationWithSettings,
useUpdateMutationLastUsage,
} from '@mweb/react-engine'
import React, { FC, ReactNode, useCallback, useEffect, useMemo, useState } from 'react'
import { ModalContextState } from '../modal-context/modal-context'
Expand All @@ -31,8 +30,6 @@ const MutableWebProvider: FC<Props> = ({ config, defaultMutationId, modalApi, ch

const { mutations, isLoading: isMutationsLoading } = useMutations(tree)

const { updateMutationLastUsage } = useUpdateMutationLastUsage()

const [selectedMutationId, setSelectedMutationId] = useState<string | null>(null)
const [preferredSources, setPreferredSources] = useState<{
[key: string]: EntitySourceType | null
Expand Down Expand Up @@ -73,7 +70,7 @@ const MutableWebProvider: FC<Props> = ({ config, defaultMutationId, modalApi, ch
return lastUsedMutation ?? favoriteMutation
}, [engine, tree])

const { selectedMutation, isSelectedMutationLoading } = useMutationWithSettings(
const { mutation: selectedMutation, isMutationLoading: isSelectedMutationLoading } = useMutation(
selectedMutationId,
selectedMutationId ? preferredSources[selectedMutationId] : undefined,
selectedMutationId ? mutationVersions[selectedMutationId] : undefined
Expand Down Expand Up @@ -146,13 +143,8 @@ const MutableWebProvider: FC<Props> = ({ config, defaultMutationId, modalApi, ch

// ToDo: move to separate hook
const switchMutation = useCallback(
async (mutationId: string | null) => {
(mutationId: string | null) => {
if (selectedMutationId === mutationId) return

if (mutationId) {
updateMutationLastUsage({ mutationId: mutationId, hostname: window.location.hostname })
}

setSelectedMutationId(mutationId)
},
[selectedMutationId]
Expand Down Expand Up @@ -210,6 +202,7 @@ const MutableWebProvider: FC<Props> = ({ config, defaultMutationId, modalApi, ch
mutationApps,
activeApps,
selectedMutation,
selectedMutationId,
isLoading,
switchMutation,
switchPreferredSource,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useEngine } from '../engine'
import { DocumentCommitDto, MutationWithSettings } from '@mweb/backend'
import { DocumentCommitDto, MutationDto } from '@mweb/backend'

export const useCommitDocumentToMutation = () => {
const { engine } = useEngine()
Expand All @@ -24,7 +24,7 @@ export const useCommitDocumentToMutation = () => {
// ToDo: workaround to wait when blockchain changes will be propagated
await new Promise((res) => setTimeout(res, 3000))

queryClient.setQueryData(['mutations'], (prev: MutationWithSettings[]) => {
queryClient.setQueryData(['mutations'], (prev: MutationDto[]) => {
const index = prev.findIndex((m) => m.id === mutation.id && m.source === mutation.source)
if (index === -1) {
return [...prev, mutation]
Expand Down
2 changes: 1 addition & 1 deletion libs/react-engine/src/mutation/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ export * from './use-delete-local-mutation'
export * from './use-edit-mutation'
export * from './use-favorite-mutation'
export * from './use-mutation-versions'
export * from './use-mutation-with-settings'
export * from './use-mutation'
export * from './use-mutations-last-usage'
export * from './use-mutations'
export * from './use-preferred-source'
export * from './use-remove-mutation-from-recents'
Expand Down
4 changes: 2 additions & 2 deletions libs/react-engine/src/mutation/use-create-mutation.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useEngine } from '../engine'
import { MutationWithSettings, SaveMutationOptions } from '@mweb/backend'
import { MutationDto, SaveMutationOptions } from '@mweb/backend'
import { MutationCreateDto } from '@mweb/backend'

export function useCreateMutation() {
Expand All @@ -16,7 +16,7 @@ export function useCreateMutation() {
options?: SaveMutationOptions
}) => engine.mutationService.createMutation(creatingMutation, options),
onSuccess: (mutation) => {
queryClient.setQueryData(['mutations'], (prev: MutationWithSettings[]) => [...prev, mutation])
queryClient.setQueryData(['mutations'], (prev: MutationDto[]) => [...prev, mutation])
},
})

Expand Down
4 changes: 2 additions & 2 deletions libs/react-engine/src/mutation/use-edit-mutation.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useEngine } from '../engine'
import { MutationDto, MutationWithSettings, SaveMutationOptions } from '@mweb/backend'
import { MutationDto, SaveMutationOptions } from '@mweb/backend'

export function useEditMutation() {
const queryClient = useQueryClient()
Expand All @@ -15,7 +15,7 @@ export function useEditMutation() {
options?: SaveMutationOptions
}) => engine.mutationService.editMutation(editingMutation, options),
onSuccess: (editedMutation) => {
queryClient.setQueryData(['mutations'], (prev: MutationWithSettings[]) =>
queryClient.setQueryData(['mutations'], (prev: MutationDto[]) =>
prev.map((mut) =>
mut.id === editedMutation.id && mut.source === editedMutation.source
? editedMutation
Expand Down
Loading

0 comments on commit 65ee2c7

Please sign in to comment.