feat: initial team invites implementation

Co-authored-by: Liyas Thomas <hi@liyasthomas.com>
This commit is contained in:
Andrew Bastin
2021-10-17 15:03:45 +05:30
parent 9ac1d23fd9
commit 0ba31b6c79
4 changed files with 306 additions and 306 deletions

View File

@@ -9,41 +9,68 @@
</div> </div>
<div class="divide-y divide-dividerLight border-divider border rounded"> <div class="divide-y divide-dividerLight border-divider border rounded">
<div <div
v-for="(member, index) in members" v-if="pendingInvites.loading"
:key="`member-${index}`" class="flex p-4 items-center justify-center"
>
<SmartSpinner />
</div>
<div v-else>
<div
v-if="!pendingInvites.loading && E.isRight(pendingInvites.data)"
>
<div
v-for="(invitee, index) in pendingInvites.data.right.team
.teamInvitations"
:key="`invitee-${index}`"
class="divide-x divide-dividerLight flex" class="divide-x divide-dividerLight flex"
> >
<input <input
class="bg-transparent text-secondaryLight flex flex-1 py-2 px-4" v-if="invitee"
:placeholder="$t('team.email')" class="
bg-transparent
flex flex-1
text-secondaryLight
py-2
px-4
"
:placeholder="`${$t('team.email')}`"
:name="'param' + index" :name="'param' + index"
:value="member.user.email" :value="invitee.inviteeEmail"
readonly readonly
/> />
<input <input
class="bg-transparent text-secondaryLight flex flex-1 py-2 px-4" class="
:placeholder="$t('team.permissions')" bg-transparent
flex flex-1
text-secondaryLight
py-2
px-4
"
:placeholder="`${$t('team.permissions')}`"
:name="'value' + index" :name="'value' + index"
:value=" :value="
typeof member.role === 'string' typeof invitee.inviteeRole === 'string'
? member.role ? invitee.inviteeRole
: JSON.stringify(member.role) : JSON.stringify(invitee.inviteeRole)
" "
readonly readonly
/> />
<div class="flex"> <div class="flex">
<ButtonSecondary <ButtonSecondary
id="member"
v-tippy="{ theme: 'tooltip' }" v-tippy="{ theme: 'tooltip' }"
:title="$t('action.remove')" :title="$t('action.remove')"
svg="trash" svg="trash"
color="red" color="red"
@click.native="removeExistingTeamMember(member.user.uid)" @click.native="removeInvitee(invitee.id)"
/> />
</div> </div>
</div> </div>
</div>
<div <div
v-if="members.length === 0" v-if="
E.isRight(pendingInvites.data) &&
pendingInvites.data.right.team.teamInvitations.length === 0
"
class=" class="
flex flex-col flex flex-col
text-secondaryLight text-secondaryLight
@@ -53,10 +80,18 @@
" "
> >
<SmartIcon class="opacity-75 pb-2" name="users" /> <SmartIcon class="opacity-75 pb-2" name="users" />
<span class="text-center pb-4"> <span class="text-center">
{{ $t("empty.pending_invites") }} {{ $t("empty.pending_invites") }}
</span> </span>
</div> </div>
<div
v-if="!pendingInvites.loading && E.isLeft(pendingInvites.data)"
class="flex flex-col p-4 items-center"
>
<i class="mb-4 material-icons">help_outline</i>
{{ $t("error.something_went_wrong") }}
</div>
</div>
</div> </div>
<div class="flex flex-1 justify-between items-center"> <div class="flex flex-1 justify-between items-center">
<label for="memberList" class="p-4"> <label for="memberList" class="p-4">
@@ -66,21 +101,21 @@
<ButtonSecondary <ButtonSecondary
svg="plus" svg="plus"
:label="$t('add.new')" :label="$t('add.new')"
@click.native="addTeamMember" @click.native="addNewInvitee"
/> />
</div> </div>
</div> </div>
<div class="divide-y divide-dividerLight border-divider border rounded"> <div class="divide-y divide-dividerLight border-divider border rounded">
<div <div
v-for="(member, index) in newMembers" v-for="(invitee, index) in newInvites"
:key="`new-member-${index}`" :key="`new-invitee-${index}`"
class="divide-x divide-dividerLight flex" class="divide-x divide-dividerLight flex"
> >
<input <input
v-model="member.key" v-model="invitee.key"
class="bg-transparent flex flex-1 py-2 px-4" class="bg-transparent flex flex-1 py-2 px-4"
:placeholder="$t('team.email')" :placeholder="$t('team.email')"
:name="'member' + index" :name="'invitee' + index"
autofocus autofocus
/> />
<span> <span>
@@ -104,9 +139,9 @@
:placeholder="$t('team.permissions')" :placeholder="$t('team.permissions')"
:name="'value' + index" :name="'value' + index"
:value=" :value="
typeof member.value === 'string' typeof invitee.value === 'string'
? member.value ? invitee.value
: JSON.stringify(member.value) : JSON.stringify(invitee.value)
" "
readonly readonly
/> />
@@ -114,15 +149,15 @@
</template> </template>
<SmartItem <SmartItem
label="OWNER" label="OWNER"
@click.native="updateNewMemberRole(index, 'OWNER')" @click.native="updateNewInviteeRole(index, 'OWNER')"
/> />
<SmartItem <SmartItem
label="EDITOR" label="EDITOR"
@click.native="updateNewMemberRole(index, 'EDITOR')" @click.native="updateNewInviteeRole(index, 'EDITOR')"
/> />
<SmartItem <SmartItem
label="VIEWER" label="VIEWER"
@click.native="updateNewMemberRole(index, 'VIEWER')" @click.native="updateNewInviteeRole(index, 'VIEWER')"
/> />
</tippy> </tippy>
</span> </span>
@@ -133,12 +168,12 @@
:title="$t('action.remove')" :title="$t('action.remove')"
svg="trash" svg="trash"
color="red" color="red"
@click.native="removeTeamMember(index)" @click.native="removeNewInvitee(index)"
/> />
</div> </div>
</div> </div>
<div <div
v-if="newMembers.length === 0" v-if="newInvites.length === 0"
class=" class="
flex flex-col flex flex-col
text-secondaryLight text-secondaryLight
@@ -154,7 +189,7 @@
<ButtonSecondary <ButtonSecondary
:label="$t('add.new')" :label="$t('add.new')"
filled filled
@click.native="addTeamMember" @click.native="addNewInvitee"
/> />
</div> </div>
</div> </div>
@@ -162,7 +197,7 @@
</template> </template>
<template #footer> <template #footer>
<span> <span>
<ButtonPrimary :label="$t('team.invite')" @click.native="saveTeam" /> <ButtonPrimary :label="$t('team.invite')" @click.native="sendInvites" />
<ButtonSecondary <ButtonSecondary
:label="$t('action.cancel')" :label="$t('action.cancel')"
@click.native="hideModal" @click.native="hideModal"
@@ -172,145 +207,81 @@
</SmartModal> </SmartModal>
</template> </template>
<script> <script setup lang="ts">
import cloneDeep from "lodash/cloneDeep" import { watch, ref, reactive } from "@nuxtjs/composition-api"
import { defineComponent } from "@nuxtjs/composition-api" import * as E from "fp-ts/Either"
import * as teamUtils from "~/helpers/teams/utils" import { useGQLQuery } from "~/helpers/backend/GQLClient"
import TeamMemberAdapter from "~/helpers/teams/TeamMemberAdapter" import {
GetPendingInvitesDocument,
GetPendingInvitesQuery,
GetPendingInvitesQueryVariables,
} from "~/helpers/backend/graphql"
export default defineComponent({ const props = defineProps({
props: {
show: Boolean, show: Boolean,
editingTeam: { type: Object, default: () => {} },
editingteamID: { type: String, default: null }, editingteamID: { type: String, default: null },
}, })
data() {
return { const emit = defineEmits<{
members: [], (e: "hide-modal"): void
newMembers: [], }>()
membersAdapter: new TeamMemberAdapter(null),
const pendingInvites = useGQLQuery<
GetPendingInvitesQuery,
GetPendingInvitesQueryVariables,
""
>({
query: GetPendingInvitesDocument,
variables: reactive({
teamID: props.editingteamID,
}),
defer: true,
})
watch(
() => props.editingteamID,
() => {
if (props.editingteamID) {
pendingInvites.execute({
teamID: props.editingteamID,
})
}
} }
},
watch: {
editingteamID(teamID) {
this.membersAdapter.changeTeamID(teamID)
},
},
mounted() {
this.membersAdapter.members$.subscribe((list) => {
this.members = cloneDeep(list)
})
},
methods: {
updateMemberRole(id, role) {
this.members[id].role = role
this.$refs[`memberOptions-${id}`][0].tippy().hide()
},
updateNewMemberRole(id, role) {
this.newMembers[id].value = role
this.$refs[`newMemberOptions-${id}`][0].tippy().hide()
},
addTeamMember() {
const member = { key: "", value: "" }
this.newMembers.push(member)
},
removeExistingTeamMember(userID) {
teamUtils
.removeTeamMember(this.$apollo, userID, this.editingteamID)
.then(() => {
this.$toast.success(this.$t("team.member_removed"), {
icon: "done",
})
this.hideModal()
})
.catch((e) => {
this.$toast.error(this.$t("error.something_went_wrong"), {
icon: "error_outline",
})
console.error(e)
})
},
removeTeamMember(index) {
this.newMembers.splice(index, 1)
},
validateEmail(emailID) {
if (
/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(
emailID
) )
) {
return true watch(
() => pendingInvites,
() => {
console.log(pendingInvites)
} }
return false
},
saveTeam() {
let invalidEmail = false
this.$data.newMembers.forEach((element) => {
if (!this.validateEmail(element.key)) {
this.$toast.error(this.$t("team.invalid_email_format"), {
icon: "error_outline",
})
invalidEmail = true
}
})
if (invalidEmail) return
let invalidPermission = false
this.$data.newMembers.forEach((element) => {
if (!element.value) {
this.$toast.error(this.$t("invalid_member_permission"), {
icon: "error_outline",
})
invalidPermission = true
}
})
if (invalidPermission) return
this.$data.newMembers.forEach((element) => {
// Call to the graphql mutation
teamUtils
.addTeamMemberByEmail(
this.$apollo,
element.value,
element.key,
this.editingteamID
) )
.then(() => {
this.$toast.success(this.$t("team.saved"), { const removeInvitee = (id: string) => {
icon: "done", console.log(id)
}) }
})
.catch((e) => { const newInvites = ref([])
this.$toast.error(e, {
icon: "error_outline", const addNewInvitee = () => {
}) newInvites.value.push({
console.error(e) key: "",
}) value: "",
})
this.members.forEach((element) => {
teamUtils
.updateTeamMemberRole(
this.$apollo,
element.user.uid,
element.role,
this.editingteamID
)
.then(() => {
this.$toast.success(this.$t("team.member_role_updated"), {
icon: "done",
})
})
.catch((e) => {
this.$toast.error(e, {
icon: "error_outline",
})
console.error(e)
})
})
this.hideModal()
},
hideModal() {
this.newMembers = []
this.$emit("hide-modal")
},
},
}) })
}
const updateNewInviteeRole = (index: number, role: string) => {
newInvites.value[index].value = role
}
const removeNewInvitee = (id: number) => {
newInvites.value.splice(id, 1)
}
const sendInvites = () => {
console.log(newInvites.value)
}
const hideModal = () => {
emit("hide-modal")
}
</script> </script>

View File

@@ -49,7 +49,7 @@
</div> </div>
<div <div
v-if="!myTeams.loading && E.isLeft(myTeams.data)" v-if="!myTeams.loading && E.isLeft(myTeams.data)"
class="flex items-center flex-col" class="flex flex-col items-center"
> >
<i class="mb-4 material-icons">help_outline</i> <i class="mb-4 material-icons">help_outline</i>
{{ $t("error.something_went_wrong") }} {{ $t("error.something_went_wrong") }}
@@ -65,7 +65,6 @@
" "
:team="myTeams.data.right.myTeams[0]" :team="myTeams.data.right.myTeams[0]"
:show="showModalEdit" :show="showModalEdit"
:editing-team="editingTeam"
:editingteam-i-d="editingTeamID" :editingteam-i-d="editingTeamID"
@hide-modal="displayModalEdit(false)" @hide-modal="displayModalEdit(false)"
@invite-team="inviteTeam(editingTeam, editingTeamID)" @invite-team="inviteTeam(editingTeam, editingTeamID)"
@@ -110,7 +109,9 @@ const myTeams = useGQLQuery<
MyTeamsQuery, MyTeamsQuery,
MyTeamsQueryVariables, MyTeamsQueryVariables,
MyTeamsQueryError MyTeamsQueryError
>(MyTeamsDocument) >({
query: MyTeamsDocument,
})
watchEffect(() => { watchEffect(() => {
console.log(myTeams) console.log(myTeams)

View File

@@ -1,10 +1,11 @@
import { import {
computed,
ref, ref,
onMounted,
onBeforeUnmount,
reactive, reactive,
Ref, Ref,
unref,
watchEffect,
watchSyncEffect,
WatchStopHandle,
} from "@nuxtjs/composition-api" } from "@nuxtjs/composition-api"
import { import {
createClient, createClient,
@@ -14,6 +15,8 @@ import {
OperationContext, OperationContext,
fetchExchange, fetchExchange,
makeOperation, makeOperation,
GraphQLRequest,
createRequest,
} from "@urql/core" } from "@urql/core"
import { authExchange } from "@urql/exchange-auth" import { authExchange } from "@urql/exchange-auth"
import { offlineExchange } from "@urql/exchange-graphcache" import { offlineExchange } from "@urql/exchange-graphcache"
@@ -22,8 +25,7 @@ import { devtoolsExchange } from "@urql/devtools"
import * as E from "fp-ts/Either" import * as E from "fp-ts/Either"
import * as TE from "fp-ts/TaskEither" import * as TE from "fp-ts/TaskEither"
import { pipe, constVoid } from "fp-ts/function" import { pipe, constVoid } from "fp-ts/function"
import { subscribe } from "wonka" import { Source, subscribe, pipe as wonkaPipe, onEnd } from "wonka"
import clone from "lodash/clone"
import { keyDefs } from "./caching/keys" import { keyDefs } from "./caching/keys"
import { optimisticDefs } from "./caching/optimistic" import { optimisticDefs } from "./caching/optimistic"
import { updatesDef } from "./caching/updates" import { updatesDef } from "./caching/updates"
@@ -45,7 +47,7 @@ const storage = makeDefaultStorage({
maxAge: 7, maxAge: 7,
}) })
const client = createClient({ export const client = createClient({
url: BACKEND_GQL_URL, url: BACKEND_GQL_URL,
exchanges: [ exchanges: [
devtoolsExchange, devtoolsExchange,
@@ -97,6 +99,15 @@ const client = createClient({
], ],
}) })
type MaybeRef<X> = X | Ref<X>
type UseQueryOptions<T = any, V = object> = {
query: TypedDocumentNode<T, V>
variables?: MaybeRef<V>
defer?: boolean
}
/** /**
* A wrapper type for defining errors possible in a GQL operation * A wrapper type for defining errors possible in a GQL operation
*/ */
@@ -110,83 +121,90 @@ export type GQLError<T extends string> =
error: T error: T
} }
const DEFAULT_QUERY_OPTIONS = { export const useGQLQuery = <DocType, DocVarType, DocErrorType extends string>(
noPolling: false, _args: UseQueryOptions<DocType, DocVarType>
pause: undefined as Ref<boolean> | undefined, ) => {
const stops: WatchStopHandle[] = []
const args = reactive(_args)
const loading: Ref<boolean> = ref(true)
const isStale: Ref<boolean> = ref(true)
const data: Ref<E.Either<GQLError<DocErrorType>, DocType>> = ref() as any
const isPaused: Ref<boolean> = ref(args.defer ?? false)
const request: Ref<GraphQLRequest<DocType, DocVarType>> = ref(
createRequest<DocType, DocVarType>(
args.query,
unref<DocVarType>(args.variables as any) as any
)
) as any
const source: Ref<Source<OperationResult> | undefined> = ref()
stops.push(
watchEffect(
() => {
const newRequest = createRequest<DocType, DocVarType>(
args.query,
unref<DocVarType>(args.variables as any) as any
)
if (request.value.key !== newRequest.key) {
request.value = newRequest
} }
},
{ flush: "pre" }
)
)
type GQL_QUERY_OPTIONS = typeof DEFAULT_QUERY_OPTIONS stops.push(
watchEffect(
type UseQueryLoading = { () => {
loading: true source.value = !isPaused.value
} ? client.executeQuery<DocType, DocVarType>(request.value, {
type UseQueryLoaded<
QueryFailType extends string = "",
QueryReturnType = any
> = {
loading: false
data: E.Either<GQLError<QueryFailType>, QueryReturnType>
}
type UseQueryReturn<QueryFailType extends string = "", QueryReturnType = any> =
| UseQueryLoading
| UseQueryLoaded<QueryFailType, QueryReturnType>
export function isLoadedGQLQuery<QueryFailType extends string, QueryReturnType>(
x: UseQueryReturn<QueryFailType, QueryReturnType>
): x is {
loading: false
data: E.Either<GQLError<QueryFailType>, QueryReturnType>
} {
return !x.loading
}
export function useGQLQuery<
QueryReturnType = any,
QueryVariables extends object = {},
QueryFailType extends string = ""
>(
query: TypedDocumentNode<QueryReturnType, QueryVariables>,
variables?: QueryVariables,
options: Partial<GQL_QUERY_OPTIONS> = DEFAULT_QUERY_OPTIONS
):
| { loading: false; data: E.Either<GQLError<QueryFailType>, QueryReturnType> }
| { loading: true } {
type DataType = E.Either<GQLError<QueryFailType>, QueryReturnType>
const finalOptions = Object.assign(clone(DEFAULT_QUERY_OPTIONS), options)
const data = ref<DataType>()
let subscription: { unsubscribe(): void } | null = null
onMounted(() => {
const gqlQuery = client.query<any, QueryVariables>(query, variables, {
requestPolicy: "cache-and-network", requestPolicy: "cache-and-network",
}) })
: undefined
},
{ flush: "pre" }
)
)
const processResult = (result: OperationResult<any, QueryVariables>) => watchSyncEffect((onInvalidate) => {
pipe( if (source.value) {
loading.value = true
isStale.value = false
onInvalidate(
wonkaPipe(
source.value,
onEnd(() => {
loading.value = false
isStale.value = false
}),
subscribe((res) => {
data.value = pipe(
// The target // The target
result.data as QueryReturnType | undefined, res.data as DocType | undefined,
// Define what happens if data does not exist (it is an error) // Define what happens if data does not exist (it is an error)
E.fromNullable( E.fromNullable(
pipe( pipe(
// Take the network error value // Take the network error value
result.error?.networkError, res.error?.networkError,
// If it null, set the left to the generic error name // If it null, set the left to the generic error name
E.fromNullable(result.error?.message), E.fromNullable(res.error?.message),
E.match( E.match(
// The left case (network error was null) // The left case (network error was null)
(gqlErr) => (gqlErr) =>
<GQLError<QueryFailType>>{ <GQLError<DocErrorType>>{
type: "gql_error", type: "gql_error",
error: gqlErr as QueryFailType, error: gqlErr as DocErrorType,
}, },
// The right case (it was a GraphQL Error) // The right case (it was a GraphQL Error)
(networkErr) => (networkErr) =>
<GQLError<QueryFailType>>{ <GQLError<DocErrorType>>{
type: "network_error", type: "network_error",
error: networkErr, error: networkErr,
} }
@@ -195,33 +213,33 @@ export function useGQLQuery<
) )
) )
if (finalOptions.noPolling) { loading.value = false
gqlQuery.toPromise().then((result) => {
data.value = processResult(result)
})
} else {
subscription = pipe(
gqlQuery,
subscribe((result) => {
data.value = processResult(result)
}) })
).unsubscribe
) )
} }
}) })
onBeforeUnmount(() => { const execute = (updatedVars?: DocVarType) => {
subscription?.unsubscribe() if (updatedVars) {
args.variables = updatedVars as any
}
isPaused.value = false
}
const response = reactive({
loading,
data,
isStale,
execute,
}) })
return reactive({ watchEffect(() => {
loading: computed(() => !data.value), console.log(JSON.stringify(response))
data: data!, })
}) as
| { return response
loading: false
data: DataType
}
| { loading: true }
} }
export const runMutation = < export const runMutation = <

View File

@@ -0,0 +1,10 @@
query GetPendingInvites($teamID: ID!) {
team(teamID: $teamID) {
id
teamInvitations {
inviteeRole
inviteeEmail
id
}
}
}